diff --git a/.github/nightly-reviewers.txt b/.github/nightly-reviewers.txt new file mode 100644 index 000000000..5b737439c --- /dev/null +++ b/.github/nightly-reviewers.txt @@ -0,0 +1,7 @@ +# Trusted reviewers: they pick the pull requests the Nightly holds with `/nightly 2640 2642` in any issue or pull +# request (docs/release-flow.md "Nightly channel", tools/ci/nightly_set.py). Ludovic is always allowed and isn't +# listed. One GitHub login per line, with who added it and when. Removing a line revokes that login at once. +# A line with only `paused` stops every reviewer's `/nightly` (Ludovic's still work). +kacpherek # added by Ludovic, 2026-10-27 +rdbtCVS # added by Ludovic, 2026-10-27 +levzzz5154 # added by Ludovic, 2026-10-27 diff --git a/.github/workflows/game-build.yml b/.github/workflows/game-build.yml new file mode 100644 index 000000000..7e075ea63 --- /dev/null +++ b/.github/workflows/game-build.yml @@ -0,0 +1,291 @@ +name: game build +# Builds the game for every platform from `ref`: the Java exporters, then Linux and the Linux server and Windows on +# GitHub, macOS on the Mac mini's runner with a 1500-frame offscreen run of a new world (smoke-test.json). Called by +# release.yml (the releases) and nightly-build.yml (the opt-in Nightly), always from main's copy of this file: the +# caller's commit, never the one being built. It holds no secrets: signing the checksums is the callers' own job, +# which never runs what this one built. See docs/release-flow.md. +on: + workflow_call: + inputs: + ref: + description: The commit to build + type: string + required: true + version: + description: The version built in (HORIZON_VERSION), e.g. 0.2.81 or nightly-2026-10-28 + type: string + required: true + nightly: + description: A nightly's " " (HORIZON_NIGHTLY), shown by the game; empty for a release + type: string + default: '' + trusted: + # Only release.yml says true: it builds main. A nightly can hold pull requests nobody reviewed yet, whose + # build scripts and tests run here and could rewrite target/, the cargo home or a compiler cache. So an + # untrusted build never runs on the release runner, never saves the Rust cache (its key is its own anyway), + # and a trusted one never reads the machine's shared sccache, which pull requests' jobs write + # (tests/test_nightly.py pins all of it). + description: The source is main (a release); false for anything else (a nightly) + type: boolean + default: false + developer_id: + description: Sign the macOS programs with Developer ID and notarize the zip (the runner's keychain) + type: boolean + default: true +permissions: + contents: read +jobs: + exporters: + # This runner holds the maintainer's own pinned Minecraft jars. Only our classes leave it. An untrusted build + # goes to the Mac mini runner that already runs pull requests' parity jobs (macOS + horizon-game: + # ludovics-mac-mini), never the release runner (MAC_RUNNER: ludovics-mac-mini-release) nor parity-main's. + runs-on: ${{ inputs.trusted && vars.MAC_RUNNER || fromJSON('["self-hosted", "macOS", "horizon-game"]') }} + # Three full preparations (two isolated, one batched) besides the compile. + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + clean: true + - uses: dtolnay/rust-toolchain@stable + - run: bash tools/ci/runner-env.sh + env: + HORIZON_NO_SCCACHE: ${{ inputs.trusted && '1' || '' }} + - run: bash tools/ci/vanilla-data.sh + - name: Compile and validate original exporters against the pinned jars + shell: bash + run: | + set -euo pipefail + # target/ is gone after the clean checkout, and vanilla-data.sh builds the preparer only when it + # prepares afresh. + cargo build --release --locked -p horizon-prepare + # Compiled here, never taken from the runner's shared preparations: pull requests' parity jobs + # write those (vanilla-data.sh links .local/exporters to them). + rm -rf .local/exporters + bundle=$(target/release/horizon-prepare compile-exporters --root "$PWD" | tail -1) + mkdir -p exporters + cp -R "$bundle/server" "$bundle/client" "$bundle/manifest.json" exporters/ + # Only our classes and their manifest leave this runner. + stray=$(find exporters -type f ! -path exporters/manifest.json \ + ! \( -name '*.class' \( -path 'exporters/server/dev/horizonlab/parity/*' -o -path 'exporters/client/dev/horizonlab/parity/*' \) \)) + [ -z "$stray" ] || { echo "::error::not one of our classes: $stray"; exit 1; } + python3 tools/check_prepare_exporters.py --binary target/release/horizon-prepare + - uses: actions/upload-artifact@v4 + with: + name: original-exporters + path: exporters/ + if-no-files-found: error + retention-days: 3 + + build: + needs: exporters + name: build ${{ matrix.name }} + strategy: + fail-fast: false + matrix: + include: + - name: linux + os: ubuntu-22.04 + dir: horizon-linux-x86_64 + asset: horizon-linux-x86_64.tar.gz + # The server build too: packaging/server/install.sh installs it on Linux. + server_dir: horizon-server-linux-x86_64 + server_asset: horizon-server-linux-x86_64.tar.gz + - name: windows + os: windows-latest + dir: horizon-windows-x64 + asset: horizon-windows-x64.zip + exe: .exe + # The C runtime linked in, so the game runs without the Visual C++ redistributable. + rustflags: -C target-feature=+crt-static + - name: macos + mac: true + dir: horizon-macos-arm64 + asset: horizon-macos-arm64.zip + runs-on: ${{ matrix.mac && (inputs.trusted && vars.MAC_RUNNER || fromJSON('["self-hosted", "macOS", "horizon-game"]')) || matrix.os }} + # Notarizing the zip can take a few minutes. + timeout-minutes: ${{ matrix.mac && 60 || 40 }} + env: + RUSTFLAGS: ${{ matrix.rustflags }} + # The release's version, built in (horizon_core::release): --version, user agents, crash reports and + # telemetry say it. No version-bump commits. + HORIZON_VERSION: ${{ inputs.version }} + # A nightly's date and commit ("2026-10-28 0c02067"), which the game shows; empty for a release. + HORIZON_NIGHTLY: ${{ inputs.nightly }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + # Always from a clean checkout, the Mac mini's runner too: its work folder is shared with pull requests' + # parity jobs, and nothing they leave (target/, an untracked .cargo/config.toml, a build script's output) + # may end up in a release. target/ is rebuilt from scratch; .local/ is relinked by vanilla-data.sh, which + # keeps its preparations outside the checkout. + clean: true + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + if: runner.environment == 'github-hosted' + with: + # A release restores only what a release saved: an untrusted build has its own key and saves nothing. + shared-key: ${{ inputs.trusted && 'release' || 'nightly' }}-${{ matrix.name }} + save-if: ${{ inputs.trusted }} + - name: ALSA and udev headers + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev + - name: Build the client, horizon-ctl, horizon-prepare and horizon-server + # `horizon-client/mods`: every released game runs code mods (the feature is off in dev builds). + run: cargo build --release --locked --features horizon-client/mods -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server + - name: Every program the release folder takes was built + run: | + for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do + test -f "target/release/$binary${{ matrix.exe }}" || { echo "::error::target/release/$binary${{ matrix.exe }} is missing"; exit 1; } + done + - name: The signing keychain, unlocked + if: runner.os == 'macOS' && vars.MACOS_SIGN_IDENTITY != '' && inputs.developer_id + env: + MACOS_SIGN_IDENTITY: ${{ vars.MACOS_SIGN_IDENTITY }} + run: packaging/macos/keychain.sh unlock + - name: Signed with Developer ID and the hardened runtime + # Before the checks below, so they run the programs as players will. + if: runner.os == 'macOS' && vars.MACOS_SIGN_IDENTITY != '' && inputs.developer_id + env: + MACOS_SIGN_IDENTITY: ${{ vars.MACOS_SIGN_IDENTITY }} + run: | + for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do + codesign --force --options runtime --timestamp --keychain "$MACOS_SIGN_KEYCHAIN" \ + --identifier "dev.horizon.${binary#horizon-}" --sign "$MACOS_SIGN_IDENTITY" "target/release/$binary" + codesign --verify --strict --verbose=2 "target/release/$binary" + done + - name: Only system libraries + # Windows: no non-system DLL (a "DLL not found" dialog on some players' machines). Linux: the standard + # loader and libraries every desktop distribution has. macOS: only the system's own libraries. + run: | + for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do + file="target/release/$binary${{ matrix.exe }}" + if [[ "$RUNNER_OS" == macOS ]]; then + others=$(otool -L "$file" | tail -n +2 | awk '{print $1}' | grep -v -E '^(/usr/lib/|/System/Library/)' || true) + [[ -z "$others" ]] || { echo "::error::$binary links $others"; exit 1; } + else + ${{ runner.os == 'Windows' && 'python' || 'python3' }} tools/check_imports.py "$file" + fi + done + - name: Every program starts + run: | + set -euo pipefail + bin=target/release + "$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources' + "$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null + "$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir' + # The version is the release's. + for binary in horizon-prepare horizon-server; do + out=$("$bin/$binary${{ matrix.exe }}" --version | tr -d '\r') + echo "$out" + [[ "$out" == "$binary $HORIZON_VERSION" ]] || { echo "::error::expected $binary $HORIZON_VERSION"; exit 1; } + done + - name: Tools from the runner + if: runner.environment == 'self-hosted' + env: + HORIZON_NO_SCCACHE: ${{ inputs.trusted && '1' || '' }} + run: bash tools/ci/runner-env.sh + - name: Resources prepared from the runner's own Minecraft + if: runner.environment == 'self-hosted' + run: bash tools/ci/vanilla-data.sh + - name: The game runs (offscreen, a new world, 1500 frames) + if: runner.environment == 'self-hosted' + run: | + set -euo pipefail + # From a scratch folder: the game keeps its saves and options in the folder it starts in. + home="$RUNNER_TEMP/horizon-smoke" + rm -rf "$home" && mkdir -p "$home" + version=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' research-lock.json | head -1) + client="$PWD/target/release/horizon-client" + resources="$PWD/.local/horizon-client/$version" + (cd "$home" && HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 "$client" --resources "$resources" --offscreen \ + --world smoke --seed 1 --render-distance 4 --world-frames 1500 --timeout-seconds 180 \ + --smoke-report "$home/smoke.json" > "$home/client.log" 2>&1) || { tail -40 "$home/client.log"; exit 1; } + python3 - "$home/smoke.json" <<'EOF' + import json, sys + report = json.load(open(sys.argv[1])) + print(json.dumps(report)) + if report.get("error") is not None or report.get("frames", 0) < 1500 or not report.get("chunks") \ + or not report.get("meshed_sections") or not report.get("player"): + sys.exit("the smoke run did not draw a world") + EOF + # Published with the release; the publish job checks it again before it publishes anything. + cp "$home/smoke.json" "$RUNNER_TEMP/smoke-test.json" + - uses: actions/upload-artifact@v4 + if: runner.environment == 'self-hosted' + with: + name: smoke-test.json + path: ${{ runner.temp }}/smoke-test.json + if-no-files-found: error + retention-days: 3 + - uses: actions/download-artifact@v4 + with: + name: original-exporters + path: exporters + - name: Package + run: | + set -euo pipefail + cargo run --locked -p xtask -- package "target/release/horizon-client${{ matrix.exe }}" "dist/${{ matrix.dir }}" + cd dist + rm -f "${{ matrix.asset }}" + case "${{ matrix.asset }}" in + *.tar.gz) tar czf "${{ matrix.asset }}" "${{ matrix.dir }}" ;; + *) if [[ "$RUNNER_OS" == Windows ]]; then 7z a -tzip "${{ matrix.asset }}" "${{ matrix.dir }}" > /dev/null + else + # Without resource forks and extended attributes: plain ditto adds an + # AppleDouble `._` file beside every file that has any. + ditto -c -k --norsrc --noextattr --noqtn --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}" + if unzip -Z1 "${{ matrix.asset }}" | grep -E '(^|/)(\._|__MACOSX/)'; then + echo "::error::macOS metadata files in ${{ matrix.asset }}"; exit 1 + fi + fi ;; + esac + ls -l "${{ matrix.asset }}" + - name: Notarized + # A zip of programs can't be stapled: Gatekeeper asks Apple the first time each one runs. + if: runner.os == 'macOS' && vars.MACOS_SIGN_IDENTITY != '' && inputs.developer_id + run: | + for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do + codesign --verify --strict "dist/${{ matrix.dir }}/$binary" + done + packaging/macos/notarize.sh "dist/${{ matrix.asset }}" + - uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.asset }} + path: dist/${{ matrix.asset }} + if-no-files-found: error + retention-days: 3 + - name: The server build (the game without sound or controllers, as horizon-engine) + if: matrix.server_asset + run: | + set -euo pipefail + # After the client is packaged: target/release/horizon-client is rebuilt without the audio and + # controllers features, so it needs neither libasound nor libudev (minimal server images lack them), + # and with code mods like the client. + cargo build --release --locked -p horizon-client --no-default-features --features mods --bin horizon-client + cargo run --locked -p xtask -- package-server target/release/horizon-client "dist/${{ matrix.server_dir }}" + folder="dist/${{ matrix.server_dir }}" + python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" + "$folder/horizon-engine" --help | grep -q -- '--resources' + [[ "$("$folder/horizon-server" --version)" == "horizon-server $HORIZON_VERSION" ]] + cd dist + rm -f "${{ matrix.server_asset }}" + tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}" + ls -l "${{ matrix.server_asset }}" + - uses: actions/upload-artifact@v4 + if: matrix.server_asset + with: + name: ${{ matrix.server_asset }} + path: dist/${{ matrix.server_asset }} + if-no-files-found: error + retention-days: 3 + - name: The signing keychain, locked again + if: always() && runner.os == 'macOS' && vars.MACOS_SIGN_IDENTITY != '' && inputs.developer_id + run: packaging/macos/keychain.sh lock + diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml new file mode 100644 index 000000000..24b6974a5 --- /dev/null +++ b/.github/workflows/nightly-build.yml @@ -0,0 +1,229 @@ +name: nightly build +run-name: nightly build${{ inputs.request && format(' (request {0})', inputs.request) || '' }} +# The opt-in Nightly channel (docs/release-flow.md "Nightly"; Ludovic, 2026-10-27). Once a night, and when a trusted +# reviewer asks (`/nightly 2640 2642`, nightly-command.yml), it builds main plus the pull requests the reviewers +# picked, merged in order (tools/ci/nightly_set.py). With none picked, it builds the newest union branch on origin +# (union/-: main plus pull requests the contribution gate proved together), or main when no union is +# newer. It publishes the result as the `nightly` pre-release. Launchers install it only for players who turn Nightly +# on. The previous nightly stays a week as nightly-. +# +# Why the signing key never meets the pull requests' code: +# - `pick` merges the picked heads onto main with `git merge-tree --write-tree`: git objects only, no working tree, +# so none of their files reaches the disk and no hook, filter or script of theirs runs. It refuses any pull +# request that changes a path CODEOWNERS gives to Ludovic (this folder, tools/ci/, the signing and update code), +# pushes the merge as nightly/build-- and saves the set on the nightly-state branch. +# - This file, game-build.yml and every script below run from main's copy: a schedule runs the default branch, and +# `uses: ./…` takes the caller's commit. The union's own .github/ is never read. +# - `build` (game-build.yml, `trusted: false`) never reaches a release's tools: its macOS jobs run on the runner +# that already runs pull requests' parity jobs, never the release runner; its Rust cache has its own key and is +# never saved; and releases don't read the machine's shared sccache. +# - `build` (game-build.yml) checks out and compiles the merge (or the union) with no secrets: its token reads contents only and +# isn't kept in the checkout; the macOS programs are signed ad hoc (Developer ID needs the runner's keychain, +# which stays locked for nightlies). +# - `sign` is the only job with RELEASE_SIGNING_KEY. It checks out nothing but main's tools/ci/sign_release.sh, which +# runs the runner's sha256sum and OpenSSL over the archives: it hashes them, never runs them. The signed message +# names the channel ("horizon release nightly"), so a nightly's signature can't pass for a release's. +# - `publish` verifies the signature with main's horizon-release-sign, checks the smoke test, and only then moves +# the tag. Like sign, it never executes what build produced. +# gh workflow run "nightly build" # now (skips when the pick is the same commit as last night's) +# gh workflow run "nightly build" -f force=true # build and publish even if unchanged +# gh workflow run "nightly build" -f dry_run=true # build and sign with a throwaway key, publish nothing +on: + schedule: + - cron: '17 20 * * *' # 20:17 UTC: after the day's waves, before the 03:07 Paris parity audit takes the Mac mini + workflow_dispatch: + inputs: + force: + description: Build and publish even if tonight's pick is the commit already published + type: boolean + default: false + dry_run: + description: Build and sign with a throwaway key, publish nothing + type: boolean + default: false + issue: + description: The issue or pull request whose `/nightly` comment asked for this build (answered there) + type: string + default: '' + request: + description: The command's id, in the run's name so it can link the run + type: string + default: '' + prs: + description: A dry run's own set, `2640@ 2642@` (the saved set stays) + type: string + default: '' +permissions: + contents: read +concurrency: + # One build at a time. A newer request replaces one still waiting: it builds the set as it is by then, so no pick + # is lost. + group: nightly-build + cancel-in-progress: false +jobs: + pick: + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write # nightly/build-- and the nightly-state branch (main is protected) + issues: write # says in the thread when the picked pull requests conflict + pull-requests: write + outputs: + build: ${{ steps.pick.outputs.build }} + sha: ${{ steps.pick.outputs.sha }} + short: ${{ steps.pick.outputs.short }} + source: ${{ steps.pick.outputs.source }} + date: ${{ steps.pick.outputs.date }} + version: ${{ steps.pick.outputs.version }} + nightly: ${{ steps.pick.outputs.nightly }} + dry_run: ${{ steps.mode.outputs.dry_run }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + - id: mode + # A dry run never publishes; a hand-started run off main is always one. + run: echo "dry_run=${{ github.event_name == 'workflow_dispatch' && (inputs.dry_run || github.ref != 'refs/heads/main') }}" >> "$GITHUB_OUTPUT" + - id: pick + env: + GH_TOKEN: ${{ github.token }} + FORCE: ${{ (inputs.force || steps.mode.outputs.dry_run == 'true') && 'yes' || '' }} + DRY_RUN: ${{ steps.mode.outputs.dry_run }} + NIGHTLY_ISSUE: ${{ inputs.issue }} + NIGHTLY_PRS: ${{ inputs.prs }} + run: | + python3 tools/ci/nightly.py pick ${FORCE:+--force} | tee -a "$GITHUB_STEP_SUMMARY" + { echo; cat nightly-notes.md; } >> "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@v4 + with: + name: nightly-notes + path: nightly-notes.md + retention-days: 3 + + build: + needs: pick + if: needs.pick.outputs.build == 'true' + uses: ./.github/workflows/game-build.yml + with: + ref: ${{ needs.pick.outputs.sha }} + version: ${{ needs.pick.outputs.version }} + nightly: ${{ needs.pick.outputs.nightly }} + developer_id: false + trusted: false # it can hold unreviewed pull requests: their own cache key, never saved, not the release runner + + sign: + needs: [pick, build] + runs-on: ubuntu-latest + timeout-minutes: 10 + # The key's only job: main's sign_release.sh hashes the archives and signs with the runner's OpenSSL. + environment: ${{ needs.pick.outputs.dry_run != 'true' && 'release' || '' }} + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: tools/ci/sign_release.sh + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + path: dist + pattern: horizon-* + merge-multiple: true + - name: Sign the checksums (SHA256SUMS, SHA256SUMS.sig) for the nightly channel + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + RELEASE_SIGNING_KEY_NEXT: ${{ secrets.RELEASE_SIGNING_KEY_NEXT }} + EPHEMERAL: ${{ needs.pick.outputs.dry_run == 'true' && 'yes' || '' }} + run: | + bash tools/ci/sign_release.sh nightly dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \ + dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz + - uses: actions/upload-artifact@v4 + with: + name: signature + path: dist/SHA256SUMS* + if-no-files-found: error + retention-days: 3 + - uses: actions/upload-artifact@v4 + if: needs.pick.outputs.dry_run == 'true' + with: + name: ephemeral.pub + path: dist/ephemeral.pub + retention-days: 3 + + publish: + needs: [pick, build, sign] + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + path: dist + merge-multiple: true + - name: The signature, checked as launchers check it + env: + EPHEMERAL: ${{ needs.pick.outputs.dry_run == 'true' && 'yes' || '' }} + run: | + key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)") + cargo run --locked --quiet -p horizon-release-sign -- verify --tag nightly --publishing "${key[@]}" dist + - name: The smoke test drew a world + # No release-blocker check: a nightly is how blockers get tested. + run: python3 tools/release_train.py gate --kind game --smoke dist/smoke-test.json + - name: Publish as the `nightly` pre-release + if: needs.pick.outputs.dry_run != 'true' + env: + GH_TOKEN: ${{ github.token }} + SHA: ${{ needs.pick.outputs.sha }} + DATE: ${{ needs.pick.outputs.date }} + run: | + set -euo pipefail + python3 tools/ci/nightly.py rotate + signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) + # A pre-release, never GitHub's latest: launchers on the release channel never see it. + gh release create nightly --prerelease --latest=false --target "$SHA" \ + --title "Nightly $DATE · ${SHA:0:7}" --notes-file dist/nightly-notes.md \ + "dist/horizon-linux-x86_64.tar.gz#Nightly game files: Linux (horizon-linux-x86_64.tar.gz)" \ + "dist/horizon-windows-x64.zip#Nightly game files: Windows (horizon-windows-x64.zip)" \ + "dist/horizon-macos-arm64.zip#Nightly game files: macOS (horizon-macos-arm64.zip)" \ + "dist/horizon-server-linux-x86_64.tar.gz#Nightly dedicated server for Linux (horizon-server-linux-x86_64.tar.gz)" \ + dist/SHA256SUMS "${signature[@]}" dist/smoke-test.json + python3 tools/ci/nightly.py prune --days 7 + - name: Dry run, the nightly that would be published + if: needs.pick.outputs.dry_run == 'true' + run: | + echo "Would publish nightly at ${{ needs.pick.outputs.sha }} (${{ needs.pick.outputs.source }})" + ls -l dist + + answer: + # Tells the thread that asked for this build how it ended. A conflict `pick` already explained there. + needs: [pick, build, sign, publish] + if: always() && inputs.issue != '' && needs.pick.result == 'success' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + issues: write + pull-requests: write + steps: + - env: + GH_TOKEN: ${{ github.token }} + ISSUE: ${{ inputs.issue }} + BUILD: ${{ needs.pick.outputs.build }} + PUBLISHED: ${{ needs.publish.result }} + DRY_RUN: ${{ needs.pick.outputs.dry_run }} + NAME: Nightly ${{ needs.pick.outputs.date }} · ${{ needs.pick.outputs.short }} + RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + if [[ "$BUILD" != true ]]; then + text="nothing new: the published Nightly is already this build." + elif [[ "$PUBLISHED" == success && "$DRY_RUN" == true ]]; then + text="the dry run built and signed $NAME; nothing was published. $RUN" + elif [[ "$PUBLISHED" == success ]]; then + text="published $NAME: https://github.com/$GITHUB_REPOSITORY/releases/tag/nightly. Launchers with Nightly on install it at their next start." + else + text="the build failed, nothing was published: $RUN" + fi + gh api "repos/$GITHUB_REPOSITORY/issues/$ISSUE/comments" -f body="🤖 Nightly: $text" diff --git a/.github/workflows/nightly-command.yml b/.github/workflows/nightly-command.yml new file mode 100644 index 000000000..340988d93 --- /dev/null +++ b/.github/workflows/nightly-command.yml @@ -0,0 +1,46 @@ +name: nightly command +# `/nightly …` comments: the trusted reviewers in .github/nightly-reviewers.txt (and Ludovic) pick the pull requests +# the Nightly holds (docs/release-flow.md "Nightly channel", tools/ci/nightly_set.py). This job only checks who asked, +# saves the set on the nightly-state branch, starts `nightly build` and answers in the thread. +# +# Why no pull request's code runs here, though the token can write: +# - `issue_comment` always runs this file from main, whoever comments and wherever; a pull request's own copy of it +# is never read. +# - It checks out main and runs main's nightly_set.py. The comment's text and author reach it as env vars, never in +# a shell line. +# - It never checks out, fetches or merges a pull request: it reads their file lists through the API. The merge +# happens in nightly-build.yml's `pick`, with git objects only; their code runs in its `build`, without secrets. +on: + issue_comment: + types: [created] +permissions: + contents: read +jobs: + command: + # Every other comment skips here, before a runner starts. + if: startsWith(github.event.comment.body, '/nightly') && github.event.comment.user.type != 'Bot' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: write # the nightly-state branch (main is protected) + actions: write # starts `nightly build` + issues: write # answers in the thread + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + ref: main + persist-credentials: false + sparse-checkout: | + .github/CODEOWNERS + .github/nightly-reviewers.txt + tools/ci/nightly_set.py + sparse-checkout-cone-mode: false + - name: Run the command + env: + GH_TOKEN: ${{ github.token }} + BODY: ${{ github.event.comment.body }} + AUTHOR: ${{ github.event.comment.user.login }} + ISSUE: ${{ github.event.issue.number }} + COMMENT_URL: ${{ github.event.comment.html_url }} + run: python3 tools/ci/nightly_set.py command diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d879f0d61..0065a380a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,7 +40,10 @@ permissions: # The open release-blocker issues (decide). issues: read concurrency: - group: game-release + # One release at a time. A hand-started dry run publishes nothing, so it can't race a real release: it gets a + # group of its own. In the shared group, a release queued behind it replaced it as the pending run and GitHub + # cancelled it (#2779's dry run, 2026-10-27), which happens all day while releases go out in batches. + group: game-release${{ github.event_name == 'workflow_dispatch' && inputs.dry_run && '-dry-run' || '' }} cancel-in-progress: false jobs: decide: @@ -79,252 +82,15 @@ jobs: # A dry run builds whatever the decision, to test the builds. if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi - exporters: + build: needs: decide if: needs.decide.outputs.release == 'true' - # This runner holds the maintainer's own pinned Minecraft jars. Only our classes leave it. - runs-on: ${{ vars.MAC_RUNNER || 'ludovics-mac-mini' }} - # Three full preparations (two isolated, one batched) besides the compile. - timeout-minutes: 60 - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ needs.decide.outputs.head }} - persist-credentials: false - clean: true - - uses: dtolnay/rust-toolchain@stable - - run: bash tools/ci/runner-env.sh - - run: bash tools/ci/vanilla-data.sh - - name: Compile and validate original exporters against the pinned jars - shell: bash - run: | - set -euo pipefail - # target/ is gone after the clean checkout, and vanilla-data.sh builds the preparer only when it - # prepares afresh. - cargo build --release --locked -p horizon-prepare - # Compiled here, never taken from the runner's shared preparations: pull requests' parity jobs - # write those (vanilla-data.sh links .local/exporters to them). - rm -rf .local/exporters - bundle=$(target/release/horizon-prepare compile-exporters --root "$PWD" | tail -1) - mkdir -p exporters - cp -R "$bundle/server" "$bundle/client" "$bundle/manifest.json" exporters/ - # Only our classes and their manifest leave this runner. - stray=$(find exporters -type f ! -path exporters/manifest.json \ - ! \( -name '*.class' \( -path 'exporters/server/dev/horizonlab/parity/*' -o -path 'exporters/client/dev/horizonlab/parity/*' \) \)) - [ -z "$stray" ] || { echo "::error::not one of our classes: $stray"; exit 1; } - python3 tools/check_prepare_exporters.py --binary target/release/horizon-prepare - - uses: actions/upload-artifact@v4 - with: - name: original-exporters - path: exporters/ - if-no-files-found: error - retention-days: 3 - - build: - needs: [decide, exporters] - if: needs.decide.outputs.release == 'true' - name: build ${{ matrix.name }} - strategy: - fail-fast: false - matrix: - include: - - name: linux - os: ubuntu-22.04 - dir: horizon-linux-x86_64 - asset: horizon-linux-x86_64.tar.gz - # The server build too: packaging/server/install.sh installs it on Linux. - server_dir: horizon-server-linux-x86_64 - server_asset: horizon-server-linux-x86_64.tar.gz - - name: windows - os: windows-latest - dir: horizon-windows-x64 - asset: horizon-windows-x64.zip - exe: .exe - # The C runtime linked in, so the game runs without the Visual C++ redistributable. - rustflags: -C target-feature=+crt-static - - name: macos - mac: true - dir: horizon-macos-arm64 - asset: horizon-macos-arm64.zip - runs-on: ${{ matrix.mac && (vars.MAC_RUNNER || 'ludovics-mac-mini') || matrix.os }} - # Notarizing the zip can take a few minutes. - timeout-minutes: ${{ matrix.mac && 60 || 40 }} - env: - RUSTFLAGS: ${{ matrix.rustflags }} - # The release's version, built in (horizon_core::release): --version, user agents, crash reports and - # telemetry say it. No version-bump commits. - HORIZON_VERSION: ${{ needs.decide.outputs.version }} - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ needs.decide.outputs.head }} - persist-credentials: false - # Always from a clean checkout, the Mac mini's runner too: its work folder is shared with pull requests' - # parity jobs, and nothing they leave (target/, an untracked .cargo/config.toml, a build script's output) - # may end up in a release. target/ is rebuilt from scratch; .local/ is relinked by vanilla-data.sh, which - # keeps its preparations outside the checkout. - clean: true - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 - if: runner.environment == 'github-hosted' - with: - shared-key: release-${{ matrix.name }} - - name: ALSA and udev headers - if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev - - name: Build the client, horizon-ctl, horizon-prepare and horizon-server - # `horizon-client/mods`: every released game runs code mods (the feature is off in dev builds). - run: cargo build --release --locked --features horizon-client/mods -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server - - name: Every program the release folder takes was built - run: | - for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do - test -f "target/release/$binary${{ matrix.exe }}" || { echo "::error::target/release/$binary${{ matrix.exe }} is missing"; exit 1; } - done - - name: The signing keychain, unlocked - if: runner.os == 'macOS' && vars.MACOS_SIGN_IDENTITY != '' - env: - MACOS_SIGN_IDENTITY: ${{ vars.MACOS_SIGN_IDENTITY }} - run: packaging/macos/keychain.sh unlock - - name: Signed with Developer ID and the hardened runtime - # Before the checks below, so they run the programs as players will. - if: runner.os == 'macOS' && vars.MACOS_SIGN_IDENTITY != '' - env: - MACOS_SIGN_IDENTITY: ${{ vars.MACOS_SIGN_IDENTITY }} - run: | - for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do - codesign --force --options runtime --timestamp --keychain "$MACOS_SIGN_KEYCHAIN" \ - --identifier "dev.horizon.${binary#horizon-}" --sign "$MACOS_SIGN_IDENTITY" "target/release/$binary" - codesign --verify --strict --verbose=2 "target/release/$binary" - done - - name: Only system libraries - # Windows: no non-system DLL (a "DLL not found" dialog on some players' machines). Linux: the standard - # loader and libraries every desktop distribution has. macOS: only the system's own libraries. - run: | - for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do - file="target/release/$binary${{ matrix.exe }}" - if [[ "$RUNNER_OS" == macOS ]]; then - others=$(otool -L "$file" | tail -n +2 | awk '{print $1}' | grep -v -E '^(/usr/lib/|/System/Library/)' || true) - [[ -z "$others" ]] || { echo "::error::$binary links $others"; exit 1; } - else - ${{ runner.os == 'Windows' && 'python' || 'python3' }} tools/check_imports.py "$file" - fi - done - - name: Every program starts - run: | - set -euo pipefail - bin=target/release - "$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources' - "$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null - "$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir' - # The version is the release's. - for binary in horizon-prepare horizon-server; do - out=$("$bin/$binary${{ matrix.exe }}" --version | tr -d '\r') - echo "$out" - [[ "$out" == "$binary $HORIZON_VERSION" ]] || { echo "::error::expected $binary $HORIZON_VERSION"; exit 1; } - done - - name: Tools from the runner - if: runner.environment == 'self-hosted' - run: bash tools/ci/runner-env.sh - - name: Resources prepared from the runner's own Minecraft - if: runner.environment == 'self-hosted' - run: bash tools/ci/vanilla-data.sh - - name: The game runs (offscreen, a new world, 1500 frames) - if: runner.environment == 'self-hosted' - run: | - set -euo pipefail - # From a scratch folder: the game keeps its saves and options in the folder it starts in. - home="$RUNNER_TEMP/horizon-smoke" - rm -rf "$home" && mkdir -p "$home" - version=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' research-lock.json | head -1) - client="$PWD/target/release/horizon-client" - resources="$PWD/.local/horizon-client/$version" - (cd "$home" && HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 "$client" --resources "$resources" --offscreen \ - --world smoke --seed 1 --render-distance 4 --world-frames 1500 --timeout-seconds 180 \ - --smoke-report "$home/smoke.json" > "$home/client.log" 2>&1) || { tail -40 "$home/client.log"; exit 1; } - python3 - "$home/smoke.json" <<'EOF' - import json, sys - report = json.load(open(sys.argv[1])) - print(json.dumps(report)) - if report.get("error") is not None or report.get("frames", 0) < 1500 or not report.get("chunks") \ - or not report.get("meshed_sections") or not report.get("player"): - sys.exit("the smoke run did not draw a world") - EOF - # Published with the release; the publish job checks it again before it publishes anything. - cp "$home/smoke.json" "$RUNNER_TEMP/smoke-test.json" - - uses: actions/upload-artifact@v4 - if: runner.environment == 'self-hosted' - with: - name: smoke-test.json - path: ${{ runner.temp }}/smoke-test.json - if-no-files-found: error - retention-days: 3 - - uses: actions/download-artifact@v4 - with: - name: original-exporters - path: exporters - - name: Package - run: | - set -euo pipefail - cargo run --locked -p xtask -- package "target/release/horizon-client${{ matrix.exe }}" "dist/${{ matrix.dir }}" - cd dist - rm -f "${{ matrix.asset }}" - case "${{ matrix.asset }}" in - *.tar.gz) tar czf "${{ matrix.asset }}" "${{ matrix.dir }}" ;; - *) if [[ "$RUNNER_OS" == Windows ]]; then 7z a -tzip "${{ matrix.asset }}" "${{ matrix.dir }}" > /dev/null - else - # Without resource forks and extended attributes: plain ditto adds an - # AppleDouble `._` file beside every file that has any. - ditto -c -k --norsrc --noextattr --noqtn --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}" - if unzip -Z1 "${{ matrix.asset }}" | grep -E '(^|/)(\._|__MACOSX/)'; then - echo "::error::macOS metadata files in ${{ matrix.asset }}"; exit 1 - fi - fi ;; - esac - ls -l "${{ matrix.asset }}" - - name: Notarized - # A zip of programs can't be stapled: Gatekeeper asks Apple the first time each one runs. - if: runner.os == 'macOS' && vars.MACOS_SIGN_IDENTITY != '' - run: | - for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do - codesign --verify --strict "dist/${{ matrix.dir }}/$binary" - done - packaging/macos/notarize.sh "dist/${{ matrix.asset }}" - - uses: actions/upload-artifact@v4 - with: - name: ${{ matrix.asset }} - path: dist/${{ matrix.asset }} - if-no-files-found: error - retention-days: 3 - - name: The server build (the game without sound or controllers, as horizon-engine) - if: matrix.server_asset - run: | - set -euo pipefail - # After the client is packaged: target/release/horizon-client is rebuilt without the audio and - # controllers features, so it needs neither libasound nor libudev (minimal server images lack them), - # and with code mods like the client. - cargo build --release --locked -p horizon-client --no-default-features --features mods --bin horizon-client - cargo run --locked -p xtask -- package-server target/release/horizon-client "dist/${{ matrix.server_dir }}" - folder="dist/${{ matrix.server_dir }}" - python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" - "$folder/horizon-engine" --help | grep -q -- '--resources' - [[ "$("$folder/horizon-server" --version)" == "horizon-server $HORIZON_VERSION" ]] - cd dist - rm -f "${{ matrix.server_asset }}" - tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}" - ls -l "${{ matrix.server_asset }}" - - uses: actions/upload-artifact@v4 - if: matrix.server_asset - with: - name: ${{ matrix.server_asset }} - path: dist/${{ matrix.server_asset }} - if-no-files-found: error - retention-days: 3 - - name: The signing keychain, locked again - if: always() && runner.os == 'macOS' && vars.MACOS_SIGN_IDENTITY != '' - run: packaging/macos/keychain.sh lock + # Every platform's archive, and macOS's smoke test (game-build.yml). + uses: ./.github/workflows/game-build.yml + with: + ref: ${{ needs.decide.outputs.head }} + version: ${{ needs.decide.outputs.version }} + trusted: true # main: the release runner, the release cache, no shared sccache sign: needs: [decide, build] diff --git a/crates/horizon-client-core/src/block_entity_nbt.rs b/crates/horizon-client-core/src/block_entity_nbt.rs index 6e214fd61..a4387bf48 100644 --- a/crates/horizon-client-core/src/block_entity_nbt.rs +++ b/crates/horizon-client-core/src/block_entity_nbt.rs @@ -61,6 +61,16 @@ fn f32_tag(v: f32) -> Tag { Tag::Float(v.to_bits()) } +/// `TheEndGatewayBlockEntity.loadAdditional`: BlockPos.CODEC and Level.isInSpawnableBounds. +pub fn gateway_exit(tag: &Tag) -> Option<[i32; 3]> { + let Tag::IntArray(v) = tag else { return None }; + let p: [i32; 3] = v.as_slice().try_into().ok()?; + ((-30_000_000..30_000_000).contains(&p[0]) + && (-20_000_000..20_000_000).contains(&p[1]) + && (-30_000_000..30_000_000).contains(&p[2])) + .then_some(p) +} + /// What a block entity reads and writes, in `saveAdditional` order. struct Fields<'a> { input: &'a Tag, @@ -424,10 +434,7 @@ pub fn canonical(tag: &Tag) -> Option { } "minecraft:end_gateway" => { f.long("Age", 0); - f.keep("exit_portal", |t| { - is_pos(t) - && matches!(t, Tag::IntArray(v) if v[1].abs() <= 30_000_000 && v[0].abs() <= 30_000_000 && v[2].abs() <= 30_000_000) - }); + f.keep("exit_portal", |t| gateway_exit(t).is_some()); if flag(tag.get("ExactTeleport")) == Some(true) { f.put("ExactTeleport", boolean(true)); } diff --git a/crates/horizon-client-core/src/component.rs b/crates/horizon-client-core/src/component.rs index 5b828b305..afb68fa98 100644 --- a/crates/horizon-client-core/src/component.rs +++ b/crates/horizon-client-core/src/component.rs @@ -173,6 +173,22 @@ fn object_style(o: &serde_json::Map) -> Style { if let Some(e) = o.get("click_event").and_then(Value::as_object) { let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned); style.click = match e.get("action").and_then(Value::as_str) { + // ClickEvent.OpenUrl.CODEC: ExtraCodecs.UNTRUSTED_URI allows http and + // https only, the scheme in any case (Util.parseAndValidateUntrustedUri). + Some("open_url") => text("url") + .filter(|u| { + u.split_once(':').is_some_and(|(scheme, _)| { + scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") + }) + }) + .map(crate::text::ClickEvent::OpenUrl), + // ClickEvent.ChangePage.CODEC: ExtraCodecs.POSITIVE_INT. + Some("change_page") => e + .get("page") + .and_then(Value::as_i64) + .and_then(|p| i32::try_from(p).ok()) + .filter(|p| *p >= 1) + .map(crate::text::ClickEvent::ChangePage), Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand), Some("copy_to_clipboard") => { text("value").map(crate::text::ClickEvent::CopyToClipboard) diff --git a/crates/horizon-client-core/src/lib.rs b/crates/horizon-client-core/src/lib.rs index ca40141d1..7721668ca 100644 --- a/crates/horizon-client-core/src/lib.rs +++ b/crates/horizon-client-core/src/lib.rs @@ -1,8 +1,9 @@ //! 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`, ...). +//! sound source tables commands name, and the `pack.mcmeta` filter regex. +//! horizon-client re-exports each module under its old path +//! (`horizon_client::text`, ...). #![forbid(unsafe_code)] pub mod block_entity_nbt; pub mod bossbar; @@ -14,6 +15,8 @@ pub mod key_display; pub mod lang; pub mod nbt_path; pub mod particle_type; +pub mod pattern; +pub mod potions; pub mod registries; pub mod scoreboard; pub mod snbt; diff --git a/crates/horizon-client/src/packs/pattern.rs b/crates/horizon-client-core/src/pattern.rs similarity index 100% rename from crates/horizon-client/src/packs/pattern.rs rename to crates/horizon-client-core/src/pattern.rs diff --git a/crates/horizon-client-core/src/potions.rs b/crates/horizon-client-core/src/potions.rs new file mode 100644 index 000000000..044b25e3a --- /dev/null +++ b/crates/horizon-client-core/src/potions.rs @@ -0,0 +1,249 @@ +//! The `MobEffects` and `Potions` registries (code in vanilla, ported as +//! tables): each effect's colour and category, each potion's effects, and the +//! potion colour mix. horizon-client re-exports them from `brewing`. +use std::{collections::HashMap, sync::OnceLock}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Category { + Beneficial, + Harmful, + Neutral, +} +/// A `MobEffect`: id (without namespace), colour, category, instantaneous. +#[derive(Clone, Copy, Debug)] +pub struct EffectDef { + pub id: &'static str, + pub color: u32, + pub category: Category, + pub instant: bool, +} +const fn fx(id: &'static str, color: u32, category: Category) -> EffectDef { + EffectDef { + id, + color, + category, + instant: false, + } +} +use Category::{Beneficial as B, Harmful as H, Neutral as N}; +/// `MobEffects` in registration order. +pub const EFFECTS: &[EffectDef] = &[ + fx("speed", 3402751, B), + fx("slowness", 9154528, H), + fx("haste", 14270531, B), + fx("mining_fatigue", 4866583, H), + fx("strength", 16762624, B), + EffectDef { + id: "instant_health", + color: 16262179, + category: B, + instant: true, + }, + EffectDef { + id: "instant_damage", + color: 11101546, + category: H, + instant: true, + }, + fx("jump_boost", 16646020, B), + fx("nausea", 5578058, H), + fx("regeneration", 13458603, B), + fx("resistance", 9520880, B), + fx("fire_resistance", 16750848, B), + fx("water_breathing", 10017472, B), + fx("invisibility", 16185078, B), + fx("blindness", 2039587, H), + fx("night_vision", 12779366, B), + fx("hunger", 5797459, H), + fx("weakness", 4738376, H), + fx("poison", 8889187, H), + fx("wither", 7561558, H), + fx("health_boost", 16284963, B), + fx("absorption", 2445989, B), + EffectDef { + id: "saturation", + color: 16262179, + category: B, + instant: true, + }, + fx("glowing", 9740385, N), + fx("levitation", 13565951, H), + fx("luck", 5882118, B), + fx("unluck", 12624973, H), + fx("slow_falling", 15978425, B), + fx("conduit_power", 1950417, B), + fx("dolphins_grace", 8954814, B), + fx("bad_omen", 745784, N), + fx("hero_of_the_village", 4521796, B), + fx("darkness", 2696993, H), + fx("trial_omen", 1484454, N), + fx("raid_omen", 14565464, N), + fx("wind_charged", 12438015, H), + fx("weaving", 7891290, H), + fx("oozing", 10092451, H), + fx("infested", 9214860, H), + fx("breath_of_the_nautilus", 65518, B), +]; +pub fn effect(id: &str) -> Option<&'static EffectDef> { + let id = id.trim_start_matches("minecraft:"); + EFFECTS.iter().find(|e| e.id == id) +} +/// Namespaced effect ids for mob effect storage. +pub fn namespaced(id: &'static str) -> &'static str { + static IDS: OnceLock> = OnceLock::new(); + IDS.get_or_init(|| { + EFFECTS + .iter() + .map(|e| { + ( + e.id, + &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()), + ) + }) + .collect() + }) + .get(id) + .copied() + .unwrap_or(id) +} +/// A `Potion`: id, name suffix (`item.minecraft.potion.effect.`) and +/// effects as (effect, duration ticks, amplifier). +#[derive(Clone, Copy, Debug)] +pub struct PotionDef { + pub id: &'static str, + pub name: &'static str, + pub effects: &'static [(&'static str, i32, i32)], +} +const fn p( + id: &'static str, + name: &'static str, + effects: &'static [(&'static str, i32, i32)], +) -> PotionDef { + PotionDef { id, name, effects } +} +/// `Potions` in registration order. +pub const POTIONS: &[PotionDef] = &[ + p("water", "water", &[]), + p("mundane", "mundane", &[]), + p("thick", "thick", &[]), + p("awkward", "awkward", &[]), + p("night_vision", "night_vision", &[("night_vision", 3600, 0)]), + p( + "long_night_vision", + "night_vision", + &[("night_vision", 9600, 0)], + ), + p("invisibility", "invisibility", &[("invisibility", 3600, 0)]), + p( + "long_invisibility", + "invisibility", + &[("invisibility", 9600, 0)], + ), + p("leaping", "leaping", &[("jump_boost", 3600, 0)]), + p("long_leaping", "leaping", &[("jump_boost", 9600, 0)]), + p("strong_leaping", "leaping", &[("jump_boost", 1800, 1)]), + p( + "fire_resistance", + "fire_resistance", + &[("fire_resistance", 3600, 0)], + ), + p( + "long_fire_resistance", + "fire_resistance", + &[("fire_resistance", 9600, 0)], + ), + p("swiftness", "swiftness", &[("speed", 3600, 0)]), + p("long_swiftness", "swiftness", &[("speed", 9600, 0)]), + p("strong_swiftness", "swiftness", &[("speed", 1800, 1)]), + p("slowness", "slowness", &[("slowness", 1800, 0)]), + p("long_slowness", "slowness", &[("slowness", 4800, 0)]), + p("strong_slowness", "slowness", &[("slowness", 400, 3)]), + p( + "turtle_master", + "turtle_master", + &[("slowness", 400, 3), ("resistance", 400, 2)], + ), + p( + "long_turtle_master", + "turtle_master", + &[("slowness", 800, 3), ("resistance", 800, 2)], + ), + p( + "strong_turtle_master", + "turtle_master", + &[("slowness", 400, 5), ("resistance", 400, 3)], + ), + p( + "water_breathing", + "water_breathing", + &[("water_breathing", 3600, 0)], + ), + p( + "long_water_breathing", + "water_breathing", + &[("water_breathing", 9600, 0)], + ), + p("healing", "healing", &[("instant_health", 1, 0)]), + p("strong_healing", "healing", &[("instant_health", 1, 1)]), + p("harming", "harming", &[("instant_damage", 1, 0)]), + p("strong_harming", "harming", &[("instant_damage", 1, 1)]), + p("poison", "poison", &[("poison", 900, 0)]), + p("long_poison", "poison", &[("poison", 1800, 0)]), + p("strong_poison", "poison", &[("poison", 432, 1)]), + p("regeneration", "regeneration", &[("regeneration", 900, 0)]), + p( + "long_regeneration", + "regeneration", + &[("regeneration", 1800, 0)], + ), + p( + "strong_regeneration", + "regeneration", + &[("regeneration", 450, 1)], + ), + p("strength", "strength", &[("strength", 3600, 0)]), + p("long_strength", "strength", &[("strength", 9600, 0)]), + p("strong_strength", "strength", &[("strength", 1800, 1)]), + p("weakness", "weakness", &[("weakness", 1800, 0)]), + p("long_weakness", "weakness", &[("weakness", 4800, 0)]), + p("luck", "luck", &[("luck", 6000, 0)]), + p("slow_falling", "slow_falling", &[("slow_falling", 1800, 0)]), + p( + "long_slow_falling", + "slow_falling", + &[("slow_falling", 4800, 0)], + ), + p("wind_charged", "wind_charged", &[("wind_charged", 3600, 0)]), + p("weaving", "weaving", &[("weaving", 3600, 0)]), + p("oozing", "oozing", &[("oozing", 3600, 0)]), + p("infested", "infested", &[("infested", 3600, 0)]), +]; +pub fn potion(id: &str) -> Option<&'static PotionDef> { + let id = id.trim_start_matches("minecraft:"); + POTIONS.iter().find(|p| p.id == id) +} +/// `PotionContents.BASE_POTION_COLOR` (ARGB -13083194) as RGB. +pub const BASE_POTION_COLOR: u32 = 0x385DC6; +/// `PotionContents.getColor`: amplifier-weighted mix of visible effect colours. +pub fn potion_color(id: Option<&str>) -> u32 { + let Some(def) = id.and_then(potion) else { + return BASE_POTION_COLOR; + }; + let (mut r, mut g, mut b, mut total) = (0u32, 0u32, 0u32, 0u32); + for (e, _, amp) in def.effects { + let Some(e) = effect(e) else { continue }; + let w = *amp as u32 + 1; + r += w * (e.color >> 16 & 255); + g += w * (e.color >> 8 & 255); + b += w * (e.color & 255); + total += w; + } + match ( + r.checked_div(total), + g.checked_div(total), + b.checked_div(total), + ) { + (Some(r), Some(g), Some(b)) => (r << 16) | (g << 8) | b, + _ => BASE_POTION_COLOR, + } +} diff --git a/crates/horizon-client-core/src/text.rs b/crates/horizon-client-core/src/text.rs index 0a2b6eadb..3a0bf301b 100644 --- a/crates/horizon-client-core/src/text.rs +++ b/crates/horizon-client-core/src/text.rs @@ -42,6 +42,10 @@ pub fn named_color(name: &str) -> Option { /// Click actions carried by locally constructed text components. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ClickEvent { + /// `ClickEvent.OpenUrl`: an http or https link. + OpenUrl(String), + /// `ClickEvent.ChangePage`: a book's page, counted from 1. + ChangePage(i32), SuggestCommand(String), CopyToClipboard(String), /// A local file to open with the system handler. @@ -529,6 +533,8 @@ fn style_json(style: &Style) -> Vec<(String, Value)> { } if let Some(click) = &style.click { let event = match click { + ClickEvent::OpenUrl(url) => json!({ "action": "open_url", "url": url }), + ClickEvent::ChangePage(page) => json!({ "action": "change_page", "page": page }), ClickEvent::SuggestCommand(command) => { json!({ "action": "suggest_command", "command": command }) } diff --git a/crates/horizon-client/examples/probe/emitter_particles_probe.rs b/crates/horizon-client/examples/probe/emitter_particles_probe.rs index 6349eb8dc..949b306ff 100644 --- a/crates/horizon-client/examples/probe/emitter_particles_probe.rs +++ b/crates/horizon-client/examples/probe/emitter_particles_probe.rs @@ -54,7 +54,7 @@ pub fn main() -> Result<()> { match c["axis"].as_i64() { Some(axis @ 0..=2) => { let line = record("electric_spark"); - particles::along_axis(&mut random, axis as usize, p, |p, v| { + particles::along_axis(&mut random, axis as usize, p, (10, 19), |p, v| { lines.push(line(p, v)) }); } diff --git a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs index 3f47ba787..f05bd8b83 100644 --- a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs @@ -24,6 +24,7 @@ fn stack(spec: &str) -> LootStack { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), }; for e in parts { let (name, level) = e.rsplit_once(':').unwrap_or((e, "1")); diff --git a/crates/horizon-client/examples/probe/hud_fixture.rs b/crates/horizon-client/examples/probe/hud_fixture.rs index a6f27fcda..5fc77309b 100644 --- a/crates/horizon-client/examples/probe/hud_fixture.rs +++ b/crates/horizon-client/examples/probe/hud_fixture.rs @@ -223,6 +223,7 @@ fn decorations(c: &Value, atlas: &HudAtlas) -> Vec { display_health: int("displayHealth", 0), last_health_time: millis - i64::from(int("lastHealthAgo", 0)), health_blink_time: i64::from(int("healthBlinkTime", 0)), + ..HealthHud::default() }; let kind = if has("minecraft:poison") { HeartKind::Poisoned diff --git a/crates/horizon-client/examples/probe/hud_fixture/kinds.rs b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs index 9ba66abe1..f45c122fa 100644 --- a/crates/horizon-client/examples/probe/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs @@ -101,7 +101,7 @@ fn title(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { } let partial = float(c, "partial", 0.0); let bg = background(c); - let mut out = t.overlay_message(w, h, partial, &atlas.font, bg); + let mut out = t.overlay_message(w, h, 39, partial, &atlas.font, bg); out.extend(t.title(w, h, partial, &atlas.font, bg)); out } @@ -129,7 +129,7 @@ fn selected(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { } let mode = c["gameMode"].as_str().unwrap_or("survival"); let can_hurt = mode == "survival" || mode == "adventure"; - highlight.draw(w, h, can_hurt, &atlas.font, background(c)) + highlight.draw(w, h, 39, can_hurt, &atlas.font, background(c)) } fn boss(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { diff --git a/crates/horizon-client/examples/probe/marker_particles_probe.rs b/crates/horizon-client/examples/probe/marker_particles_probe.rs index 72ebaff22..3041a84d7 100644 --- a/crates/horizon-client/examples/probe/marker_particles_probe.rs +++ b/crates/horizon-client/examples/probe/marker_particles_probe.rs @@ -75,6 +75,10 @@ pub fn main() -> Result<()> { registry: assets.registry, raining_at: &|_| false, marker: target.map(|name| (name, &options as &dyn Fn(_) -> _)), + model_offset: &|_, _, _| None, + gateway_particles: &|_, _| 0, + thundering: false, + ultrawarm: false, }; engine.seed_randoms(1057, 0, 0); engine.requested = Some(Vec::new()); diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index 5b6c26d2f..a59e3ac05 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -567,7 +567,9 @@ fn print_heart( /// The damage of a mob's direct hit on the player (others count as none). fn player_damage(e: &MobEvent) -> f32 { match e { - MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount, + MobEvent::AttackPlayer(amount, _) + | MobEvent::AttackPlayerWithEffect { amount, .. } + | MobEvent::DamagePlayer { amount, .. } => *amount, _ => 0.0, } } @@ -578,9 +580,11 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { return false; }; match e { - MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, + MobEvent::AttackPlayer(amount, _) + | MobEvent::AttackPlayerWithEffect { amount, .. } + | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, // ServerExplosion.hurtEntities: within twice the radius every hit does damage. - MobEvent::Explode(at, radius) => { + MobEvent::Explode(at, radius, _) => { let d = Vec3::new(at[0], at[1], at[2]) .distance_squared(p.position) .sqrt(); @@ -1045,22 +1049,27 @@ pub fn main() -> horizon_client::Result<()> { alive: true, creative: s.creative, sneaking: false, + swimming: false, look: [0.0, 0.0, 1.0], main_hand: s.hand.as_deref().map(Into::into), off_hand: None, head: None, armor_cover: 0.0, + invisible: false, spectator: false, gold_armor: false, hurt_by: None, last_hurt: None, velocity: Vec3::ZERO, yaw: 0.0, + sprinting: false, + riding: false, hero: false, effects: Vec::new(), uuid: PLAYER_UUID, allies: Default::default(), remote: false, + passenger: false, } }); let mut scratch = LegacyRandom::new(0); @@ -1070,6 +1079,8 @@ pub fn main() -> horizon_client::Result<()> { for (i, m) in mobs.iter().enumerate() { print(&mut out, 0, i, m, s.creative, world.game_time); } + // No player has a chest open in the scenarios. + let lid_openers = std::collections::HashMap::new(); // The MobWorld every step sees, over a snapshot of the mobs. macro_rules! mob_world { ($snapshot:expr) => { @@ -1081,6 +1092,7 @@ pub fn main() -> horizon_client::Result<()> { world: &world, registry, facts: &facts, + fluid_tables: &motion.fluids, movement: &motion.blocks, collision: &collision, data: &data, @@ -1098,12 +1110,14 @@ pub fn main() -> horizon_client::Result<()> { block_tags: &items.block_tags, biomes: &biomes, mob_griefing: true, + mob_drops: true, difficulty: LocalDifficulty::new(s.difficulty, world.day_time, 0, 0.0), end: false, world_seed: 0, // FlatLevelSource.getSeaLevel. sea_level: -63, items: Some(&items), + lid_openers: &lid_openers, } }; } diff --git a/crates/horizon-client/examples/probe/scene_motion_probe.rs b/crates/horizon-client/examples/probe/scene_motion_probe.rs index 6153e098b..66856858f 100644 --- a/crates/horizon-client/examples/probe/scene_motion_probe.rs +++ b/crates/horizon-client/examples/probe/scene_motion_probe.rs @@ -208,7 +208,7 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { )), MotionEvent::Emission { state, - in_water: true, + muffled: true, .. } => Some(format!("muffled-step {}", state.0)), MotionEvent::BubbleColumnParticle { bubble, position } => Some(format!( @@ -353,6 +353,7 @@ pub fn main() -> Result<()> { horizon_world::food::Difficulty::Hard, ][op["difficulty"].as_u64().unwrap() as usize], natural_regeneration: op["regenerate"].as_bool().unwrap(), + ..Default::default() }; } "food" => { diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 6706532b7..229510dd7 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -4,7 +4,7 @@ //! conditions advancements use). use serde_json::Value; use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, BTreeSet, HashMap}, path::Path, }; @@ -437,6 +437,8 @@ pub struct EntityView { /// mainhand, offhand, head, chest, legs, feet, body. pub equipment: [Option; 7], pub vehicle: Option>, + /// Player: what it looks at within 100 blocks (`PlayerPredicate.lookingAt`). + pub looking_at: Option>, pub effects: Vec<(String, i32, i32)>, /// Player: game mode name. pub gamemode: Option, @@ -458,7 +460,7 @@ fn range_f(v: &Value, x: f64) -> bool { _ => false, } } -fn range_i(v: &Value, x: i64) -> bool { +pub fn range_i(v: &Value, x: i64) -> bool { range_f(v, x as f64) } /// A registry id, `#tag`, or list matched against one id. @@ -473,6 +475,51 @@ pub fn id_matches(v: &Value, registry: &str, id: &str, w: &dyn World) -> bool { _ => false, } } +/// `PotionsPredicate`: the potion in a `HolderSet`, plus a `CollectionPredicate` +/// over the potion's effects (`contains`, `count`, `size`). +pub fn potions(v: &Value, potion: Option<&str>, w: &dyn World) -> bool { + if v.is_null() { + return true; + } + if !v["potions"].is_null() && !potion.is_some_and(|p| id_matches(&v["potions"], "potion", p, w)) + { + return false; + } + let c = &v["effects"]; + if c.is_null() { + return true; + } + let effects: Vec<(String, i32, i32)> = potion + .and_then(crate::brewing::potion) + .map(|d| { + d.effects + .iter() + .map(|(id, dur, amp)| (format!("minecraft:{id}"), *amp, *dur)) + .collect() + }) + .unwrap_or_default(); + // `MobEffectsPredicate.test`: the one listed effect, amplifier and duration. + let test = |pred: &Value, e: &(String, i32, i32)| { + pred.as_object().is_some_and(|m| { + m.get(&e.0).is_some_and(|want| { + range_i(&want["amplifier"], i64::from(e.1)) + && range_i(&want["duration"], i64::from(e.2)) + && want["ambient"].as_bool().is_none_or(|b| !b) + && want["visible"].as_bool().is_none_or(|b| b) + }) + }) + }; + c["contains"] + .as_array() + .is_none_or(|l| l.iter().all(|p| effects.iter().any(|e| test(p, e)))) + && c["count"].as_array().is_none_or(|l| { + l.iter().all(|entry| { + let n = effects.iter().filter(|e| test(&entry["test"], e)).count(); + range_i(&entry["count"], n as i64) + }) + }) + && range_i(&c["size"], effects.len() as i64) +} /// `ItemPredicate`. pub fn item(v: &Value, it: &ItemView, w: &dyn World) -> bool { if v.is_null() { @@ -614,6 +661,18 @@ fn components(expected: &Value, have: &[(String, String)]) -> bool { }) }) } +/// `DistancePredicate.matches` between two points. +pub fn distance(v: &Value, a: [f64; 3], b: [f64; 3]) -> bool { + let d = [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + range_f(&v["x"], d[0].abs()) + && range_f(&v["y"], d[1].abs()) + && range_f(&v["z"], d[2].abs()) + && range_f(&v["horizontal"], (d[0] * d[0] + d[2] * d[2]).sqrt()) + && range_f( + &v["absolute"], + (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(), + ) +} /// `EntityPredicate` (26.x keyed sub-predicates). pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> bool { if v.is_null() { @@ -629,21 +688,7 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo "minecraft:stepping_on" => { location(p, [e.position[0], e.position[1] - 0.5, e.position[2]], w) } - "minecraft:distance" | "distance" => { - let d = [ - e.position[0] - origin[0], - e.position[1] - origin[1], - e.position[2] - origin[2], - ]; - range_f(&p["x"], d[0].abs()) - && range_f(&p["y"], d[1].abs()) - && range_f(&p["z"], d[2].abs()) - && range_f(&p["horizontal"], (d[0] * d[0] + d[2] * d[2]).sqrt()) - && range_f( - &p["absolute"], - (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(), - ) - } + "minecraft:distance" | "distance" => distance(p, e.position, origin), "minecraft:flags" | "flags" => { let f = |k: &str, have: bool| p[k].as_bool().is_none_or(|want| want == have); f("is_on_fire", e.on_fire) @@ -678,11 +723,16 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo }) }) }), - "minecraft:type_specific/player" => p["gamemode"].as_array().is_none_or(|modes| { - e.gamemode - .as_deref() - .is_some_and(|g| modes.iter().any(|m| m.as_str() == Some(g))) - }), + "minecraft:type_specific/player" => { + p["gamemode"].as_array().is_none_or(|modes| { + e.gamemode + .as_deref() + .is_some_and(|g| modes.iter().any(|m| m.as_str() == Some(g))) + }) && (p["looking_at"].is_null() + || e.looking_at + .as_ref() + .is_some_and(|t| entity(&p["looking_at"], t, w, origin))) + } "minecraft:type_specific/lightning" => { range_i(&p["blocks_set_on_fire"], 0) && (p["entity_struck"].is_null() @@ -703,6 +753,87 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo } true } +/// `KilledByArrowTrigger.TriggerInstance.matches`: the weapon, each listed +/// victim condition matched by a distinct victim, and the count of entity types. +pub fn killed_by_arrow( + c: &Value, + me: &EntityView, + victims: &[EntityView], + weapon: Option<&ItemView>, + w: &dyn World, +) -> bool { + fn ctx<'a>(e: &'a EntityView, me: &EntityView) -> Entities<'a> { + Entities { + this: Some(e), + origin: me.position, + tool: None, + block_pos: None, + } + } + if !conditions(&c["player"], &ctx(me, me), w) { + return false; + } + if !c["fired_from_weapon"].is_null() + && !weapon.is_some_and(|it| item(&c["fired_from_weapon"], it, w)) + { + return false; + } + let mut left: Vec<&EntityView> = victims.iter().collect(); + for want in c["victims"].as_array().into_iter().flatten() { + let Some(i) = left.iter().position(|e| conditions(want, &ctx(e, me), w)) else { + return false; + }; + left.remove(i); + } + let kinds: BTreeSet<&str> = victims.iter().map(|e| e.kind.as_str()).collect(); + range_i(&c["unique_entity_types"], kinds.len() as i64) +} +/// A damage event as `DamagePredicate` sees it. +#[derive(Clone, Debug, Default)] +pub struct DamageView { + /// The damage type id (`minecraft:arrow`). + pub kind: String, + /// `DamageSource.getDirectEntity` and `getEntity`. + pub direct: Option, + pub source: Option, + /// `DamageSource.isDirect`: the direct entity is the causing one. + pub is_direct: bool, + /// The damage before and after the shield took its share. + pub original: f32, + pub actual: f32, + pub blocked: bool, +} +/// `DamagePredicate`, with its `DamageSourcePredicate` as `type`. +pub fn damage(v: &Value, d: &DamageView, w: &dyn World, origin: [f64; 3]) -> bool { + if v.is_null() { + return true; + } + let by = |key: &str, e: &Option| { + v[key].is_null() || e.as_ref().is_some_and(|e| entity(&v[key], e, w, origin)) + }; + if !range_f(&v["dealt"], f64::from(d.original)) + || !range_f(&v["taken"], f64::from(d.actual)) + || !by("source_entity", &d.source) + || v["blocked"].as_bool().is_some_and(|b| b != d.blocked) + { + return false; + } + let ty = &v["type"]; + let tags_ok = ty["tags"].as_array().into_iter().flatten().all(|t| { + let tag = t["id"].as_str().unwrap_or(""); + let tag = tag.strip_prefix('#').unwrap_or(tag); + w.in_tag("damage_type", tag, &d.kind) == t["expected"].as_bool().unwrap_or(true) + }); + let direct_ok = ty["direct_entity"].is_null() + || d.direct + .as_ref() + .is_some_and(|e| entity(&ty["direct_entity"], e, w, origin)); + let source_ok = ty["source_entity"].is_null() + || d.source + .as_ref() + .is_some_and(|e| entity(&ty["source_entity"], e, w, origin)); + tags_ok && direct_ok && source_ok && ty["is_direct"].as_bool().is_none_or(|b| b == d.is_direct) +} /// The entities a loot-style condition list may refer to. pub struct Entities<'a> { pub this: Option<&'a EntityView>, diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 07548e208..068e7d076 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -8,7 +8,7 @@ use crate::{ blocks::{BlockFacts, Fluid}, command::args::GameMode, items::ItemStack, - particles::{ParticleEngine, ParticleOptions, ParticleType as T}, + particles::{ParticleEngine, ParticleOptions, ParticleType as T, along_axis}, world::World, }; use horizon_core::{ @@ -36,8 +36,9 @@ enum Animate { spawn_particles: bool, }, /// Leaves: optional falling-leaf particle and chance; a tinted leaf takes - /// the biome foliage colour unless a fixed colour is given (azalea). - Leaves(Option<(T, f32)>, Option), + /// the biome foliage colour unless a fixed colour is given (azalea); and + /// whether they have the poplar ambient sound (`AmbientLeavesBlockSoundPlayer`). + Leaves(Option<(T, f32)>, Option, bool), NetherPortal, EnchantingTable, EndRod([i32; 3]), @@ -48,8 +49,9 @@ enum Animate { CandleCake, BrewingStand, EnderChest, - /// FallingBlock with its dust colour. - Falling(u32), + /// FallingBlock with its dust colour; sand also has the ambient desert sound + /// (`SandBlock.animateTick`). + Falling(u32, bool), /// A beehive or bee nest full of honey (`BeehiveBlock.animateTick`). Beehive, RedstoneOre, @@ -73,6 +75,22 @@ enum Animate { waterlogged: bool, }, EndPortal, + /// A powered lever: its facing and the direction it is attached toward. + Lever { + facing: [i32; 3], + connected: [i32; 3], + }, + /// A powered repeater. + Repeater { + facing: [i32; 3], + delay: i32, + }, + /// A free-hanging stalactite tip that is not waterlogged. + PointedDripstone, + WitherRose, + EndGateway, + /// A lightning rod, by the axis it points along (0, 1, 2 for X, Y, Z). + LightningRod(usize), /// `WetSpongeBlock.animateTick`. WetSponge, } @@ -89,6 +107,7 @@ fn step(facing: &str) -> [i32; 3] { fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { let name = name.strip_prefix("minecraft:").unwrap_or(name); let lit = prop("lit").as_deref() == Some("true"); + let powered = prop("powered").as_deref() == Some("true"); let facing = || step(&prop("facing").unwrap_or_default()); match name { "torch" => Animate::Torch(T::Flame), @@ -109,17 +128,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { spawn_particles: false, }, "oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" - | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None), - "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None), - "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None), - "red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None), - "orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None), - "yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None), + | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None, false), + "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None, false), + "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None, false), + "red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None, true), + "orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None, true), + "yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None, true), // The azalea blocks drop tinted leaves of the fixed colour -9399763. "azalea_leaves" | "flowering_azalea_leaves" => { - Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D)) + Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D), false) } - "spruce_leaves" => Animate::Leaves(None, None), + "spruce_leaves" => Animate::Leaves(None, None, false), "nether_portal" => Animate::NetherPortal, "enchanting_table" => Animate::EnchantingTable, "end_rod" => Animate::EndRod(facing()), @@ -128,16 +147,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { "mycelium" => Animate::Mycelium, "brewing_stand" => Animate::BrewingStand, "ender_chest" => Animate::EnderChest, - "sand" => Animate::Falling(0xDBD3A0), - "red_sand" => Animate::Falling(0xA95821), - "gravel" => Animate::Falling(0x807C7B), + "sand" => Animate::Falling(0xDBD3A0, true), + "red_sand" => Animate::Falling(0xA95821, true), + "gravel" => Animate::Falling(0x807C7B, false), // AnvilBlock/ConcretePowderBlock.getDustColor is the map colour; // DragonEggBlock's is black. - "anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7), - "dragon_egg" => Animate::Falling(0x000000), - _ if name.ends_with("_concrete_powder") => Animate::Falling(concrete_powder_color( - name.trim_end_matches("_concrete_powder"), - )), + "anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7, false), + "dragon_egg" => Animate::Falling(0x000000, false), + _ if name.ends_with("_concrete_powder") => Animate::Falling( + concrete_powder_color(name.trim_end_matches("_concrete_powder")), + false, + ), "beehive" | "bee_nest" if prop("honey_level").as_deref() == Some("5") => Animate::Beehive, "redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre, "redstone_wire" => { @@ -169,10 +189,42 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { waterlogged: prop("waterlogged").as_deref() == Some("true"), }, "end_portal" => Animate::EndPortal, + "lever" if powered => Animate::Lever { + facing: facing(), + // FaceAttachedHorizontalDirectionalBlock.getConnectedDirection. + connected: match prop("face").as_deref() { + Some("ceiling") => [0, -1, 0], + Some("floor") => [0, 1, 0], + _ => facing(), + }, + }, + "repeater" if powered => Animate::Repeater { + facing: facing(), + delay: prop("delay").and_then(|d| d.parse().ok()).unwrap_or(1), + }, + "pointed_dripstone" + if prop("vertical_direction").as_deref() == Some("down") + && prop("thickness").as_deref() == Some("tip") + && prop("waterlogged").as_deref() != Some("true") => + { + Animate::PointedDripstone + } + "wither_rose" => Animate::WitherRose, + "end_gateway" => Animate::EndGateway, + _ if name == "lightning_rod" || name.ends_with("_lightning_rod") => { + let [dx, dy, _] = facing(); + Animate::LightningRod(if dx != 0 { + 0 + } else if dy != 0 { + 1 + } else { + 2 + }) + } "wet_sponge" => Animate::WetSponge, // BrushableBlock has no dust colour of its own, so the dust is the map colour. - "suspicious_sand" => Animate::Falling(0xF7E9A3), - "suspicious_gravel" => Animate::Falling(0x707070), + "suspicious_sand" => Animate::Falling(0xF7E9A3, false), + "suspicious_gravel" => Animate::Falling(0x707070, false), "sculk_sensor" | "calibrated_sculk_sensor" if prop("sculk_sensor_phase").as_deref() == Some("active") => { @@ -239,10 +291,16 @@ pub struct AnimateTables { power_transmitter: Vec, /// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil). dried_ghast_sounds: Vec, + /// `#triggers_ambient_desert_sand_block_sounds` (sand, red sand). + desert_sand_sounds: Vec, + /// `#required_for_poplar_leaf_ambience` (overworld natural logs). + poplar_leaf_logs: Vec, /// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged). burnable: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). ambient: Vec>, + /// Per state: 1 for a pointed dripstone, 2 for one whose tip points down. + dripstone: Vec, } impl AnimateTables { pub fn load(root: &Path, registry: &BlockRegistry, biomes: &Biomes) -> crate::Result { @@ -308,12 +366,31 @@ impl AnimateTables { } } } + let dripstone = (0..registry.len() as u32) + .map(|id| { + registry.state(BlockStateId(id)).map_or(0, |s| { + let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name); + if name != "pointed_dripstone" { + 0 + } else if s.properties.get("vertical_direction").map(String::as_str) + == Some("down") + { + 2 + } else { + 1 + } + }) + }) + .collect(); Ok(Self { kinds, + dripstone, impermeable: by_state("minecraft:impermeable"), power_provider: by_state("minecraft:enchantment_power_provider"), power_transmitter: by_state("minecraft:enchantment_power_transmitter"), dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"), + desert_sand_sounds: by_state("minecraft:triggers_ambient_desert_sand_block_sounds"), + poplar_leaf_logs: by_state("minecraft:required_for_poplar_leaf_ambience"), burnable, ambient, }) @@ -341,6 +418,14 @@ pub struct AnimateContext<'a> { pub raining_at: &'a dyn Fn([i32; 3]) -> bool, /// Creative main-hand marker block and a resolver for each placed state's sprite. pub marker: Option<(&'a str, &'a dyn Fn(BlockStateId) -> Option)>, + /// `BlockState.getOffset` of a state at (x, z), for blocks with a random model offset. + pub model_offset: &'a dyn Fn(BlockStateId, i32, i32) -> Option<[f64; 3]>, + /// `TheEndGatewayBlockEntity.getParticleAmount` of the gateway state at a position. + pub gateway_particles: &'a dyn Fn(BlockStateId, [i32; 3]) -> usize, + /// `Level.isThundering`. + pub thundering: bool, + /// The dimension has `water_evaporates` and drips lava from dripstone (the Nether). + pub ultrawarm: bool, } /// `ClientLevel.getMarkerParticleTarget`: only the selected main-hand item counts. @@ -389,6 +474,9 @@ impl AnimateContext<'_> { ], )) } + fn offset_of(&self, state: BlockStateId, p: [i32; 3]) -> [f64; 3] { + (self.model_offset)(state, p[0], p[2]).unwrap_or([0.0; 3]) + } fn foliage(&self, p: [i32; 3]) -> u32 { let biome = self .world @@ -402,6 +490,10 @@ impl AnimateContext<'_> { fn add(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) { engine.add(&ParticleOptions::simple(ty), p, v); } +/// `Level.addAlwaysVisibleParticle`: still shown under the Minimal option now and then. +fn add_visible(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) { + engine.add_with(&ParticleOptions::simple(ty), p, v, false, true); +} fn sound(engine: &mut ParticleEngine, name: &'static str, p: [f64; 3], volume: f32, pitch: f32) { engine.sounds.push((name, p, volume, pitch)); } @@ -777,7 +869,7 @@ fn block_animate_tick( } } } - Animate::Leaves(falling, fixed_tint) => { + Animate::Leaves(falling, fixed_tint, poplar) => { let below = [pos[0], pos[1] - 1, pos[2]]; // LeavesBlock.makeDrippingWaterParticles. if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1 @@ -789,6 +881,9 @@ fn block_animate_tick( add(engine, T::DrippingWater, p, [0.0; 3]); } } + if poplar { + leaves_ambient_sound(tables, engine, ctx, state, pos); + } // FallingParticlesLeavesBlock.makeFallingLeavesParticles. if let Some((ty, chance)) = falling && engine.random().next_float() < chance @@ -961,7 +1056,7 @@ fn block_animate_tick( fy + 1.0 + f64::from(r.next_float()), fz + f64::from(r.next_float()), ]; - add(engine, T::SulfurBubbles, p, [0.0; 3]); + add_visible(engine, T::SulfurBubbles, p, [0.0; 3]); } if next_int(engine.random(), 10) == 0 { let name = "minecraft:block.potent_sulfur.noxious_gas"; @@ -1063,6 +1158,99 @@ fn block_animate_tick( let p = [fx + r.next_double(), fy + 0.8, fz + r.next_double()]; add(engine, T::Smoke, p, [0.0; 3]); } + Animate::Lever { facing, connected } => { + // LeverBlock.animateTick: a powered lever puffs red dust a quarter of the time. + if engine.random().next_float() < 0.25 { + // LeverBlock.makeParticle with scale 0.5. + let at = |base: f64, i: usize| { + base + 0.5 + 0.1 * f64::from(-facing[i]) + 0.2 * f64::from(-connected[i]) + }; + let p = [at(fx, 0), at(fy, 1), at(fz, 2)]; + engine.add(&ParticleOptions::dust([1.0, 0.0, 0.0], 0.5), p, [0.0; 3]); + } + } + Animate::Repeater { facing, delay } => { + // RepeaterBlock.animateTick: dust at one of the torches. + let r = engine.random(); + let x = fx + 0.5 + (r.next_double() - 0.5) * 0.2; + let y = fy + 0.4 + (r.next_double() - 0.5) * 0.2; + let z = fz + 0.5 + (r.next_double() - 0.5) * 0.2; + let mut offset = -5.0f32; + if r.next_boolean() { + offset = (delay * 2 - 1) as f32; + } + offset /= 16.0; + let xo = f64::from(offset * facing[0] as f32); + let zo = f64::from(offset * facing[2] as f32); + redstone(engine, [x + xo, y, z + zo]); + } + Animate::PointedDripstone => dripstone_drip(tables, engine, ctx, state, pos), + Animate::WitherRose => { + // WitherRoseBlock.animateTick: smoke puffs at the centre of the shape. + let center = ctx.shape_y(pos).map_or([0.5; 2], |s| { + [(s.2[0] + s.2[1]) / 2.0, (s.2[2] + s.2[3]) / 2.0] + }); + let offset = ctx.offset_of(state, pos); + let x = fx + center[0] + offset[0]; + let z = fz + center[1] + offset[2]; + for _ in 0..3 { + let r = engine.random(); + if r.next_boolean() { + let p = [ + x + r.next_double() / 5.0, + fy + (0.5 - r.next_double()), + z + r.next_double() / 5.0, + ]; + add(engine, T::Smoke, p, [0.0; 3]); + } + } + } + Animate::EndGateway => { + // EndGatewayBlock.animateTick: portal particles, one for each visible face. + for _ in 0..(ctx.gateway_particles)(state, pos) { + let r = engine.random(); + let mut p = [ + fx + r.next_double(), + fy + r.next_double(), + fz + r.next_double(), + ]; + let mut v = [ + (r.next_double() - 0.5) * 0.5, + (r.next_double() - 0.5) * 0.5, + (r.next_double() - 0.5) * 0.5, + ]; + let flip = next_int(r, 2) * 2 - 1; + if r.next_boolean() { + p[2] = fz + 0.5 + 0.25 * f64::from(flip); + v[2] = f64::from(r.next_float() * 2.0 * flip as f32); + } else { + p[0] = fx + 0.5 + 0.25 * f64::from(flip); + v[0] = f64::from(r.next_float() * 2.0 * flip as f32); + } + add(engine, T::Portal, p, v); + } + } + Animate::LightningRod(axis) => { + // LightningRodBlock.animateTick: in a thunderstorm, sparks along the + // topmost rod, more often as the game time within 200 ticks grows. + if ctx.thundering + && i64::from(next_int(engine.level_random(), 200)) <= ctx.world.game_time % 200 + && pos[1] + == ctx + .world + .world_surface(pos[0], pos[2], |id| ctx.facts.is_air(id)) + - 1 + { + let mut sparks = Vec::new(); + along_axis(engine.level_random(), axis, pos, (1, 2), |p, v| { + sparks.push((p, v)); + }); + let options = ParticleOptions::simple(T::ElectricSpark); + for (p, v) in sparks { + engine.add(&options, p, v); + } + } + } Animate::EnderChest => { for _ in 0..3 { let r = engine.random(); @@ -1081,7 +1269,7 @@ fn block_animate_tick( add(engine, T::Portal, p, v); } } - Animate::Falling(color) => { + Animate::Falling(color, sand) => { if next_int(engine.random(), 16) == 0 { let below = ctx.facts.get(ctx.state([pos[0], pos[1] - 1, pos[2]])); // FallingBlock.isFree: air, fire, liquids or replaceable. @@ -1098,6 +1286,14 @@ fn block_animate_tick( ); } } + // AmbientDesertBlockSoundsPlayer.playAmbientSandSounds: only for the air block. + if sand + && ctx.state([pos[0], pos[1] + 1, pos[2]]) == ctx.world.air + && next_int(engine.random(), 2100) == 0 + && sand_sound_nearby(tables, ctx, pos) + { + sound(engine, "minecraft:block.sand.idle", [fx, fy, fz], 1.0, 1.0); + } } Animate::Beehive => { // BeehiveBlock.animateTick: nextInt(1) + 1 attempts. @@ -1215,7 +1411,7 @@ fn block_animate_tick( } Animate::BubbleColumn { drag } => { if drag { - add(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]); + add_visible(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]); let r = engine.random(); if next_int(r, 200) == 0 { let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15); @@ -1228,7 +1424,7 @@ fn block_animate_tick( ); } } else { - add( + add_visible( engine, T::BubbleColumnUp, [fx + 0.5, fy, fz + 0.5], @@ -1240,7 +1436,7 @@ fn block_animate_tick( fy + f64::from(r.next_float()), fz + f64::from(r.next_float()), ]; - add(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]); + add_visible(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]); let r = engine.random(); if next_int(r, 200) == 0 { let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15); @@ -1318,6 +1514,153 @@ fn block_animate_tick( } } } +/// `AmbientLeavesBlockSoundPlayer.playAmbientLeavesSounds` for the poplar leaves: +/// one log and three leaves of the same kind around the block. +fn leaves_ambient_sound( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + state: BlockStateId, + pos: [i32; 3], +) { + if next_int(engine.random(), 300) != 0 { + return; + } + let Some(name) = ctx.registry.state(state).map(|s| &s.name) else { + return; + }; + let (mut logs, mut leaves) = (0, 0); + for d in [[0, -1], [1, 0], [0, 1], [-1, 0]] { + let neighbor = ctx.state([pos[0] + d[0], pos[1], pos[2] + d[1]]); + if tables + .poplar_leaf_logs + .get(neighbor.0 as usize) + .copied() + .unwrap_or(false) + { + logs += 1; + } + if ctx + .registry + .state(neighbor) + .is_some_and(|s| &s.name == name) + { + leaves += 1; + } + if logs == 1 && leaves == 3 { + let p = pos.map(f64::from); + sound(engine, "minecraft:block.poplar_leaves.ambient", p, 1.0, 1.0); + return; + } + } +} +/// `PointedDripstoneBlock.animateTick`: a free-hanging stalactite tip drips the +/// fluid above the root of its stalactite. +fn dripstone_drip( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + state: BlockStateId, + pos: [i32; 3], +) { + let roll = engine.random().next_float(); + if roll > 0.12 { + return; + } + // getFluidAboveStalactite: findRootBlock climbs at most ten blocks of + // stalactite and stops at the first block that is not pointed dripstone. + let mut root = None; + for step in 1..11 { + let p = [pos[0], pos[1] + step, pos[2]]; + match tables + .dripstone + .get(ctx.state(p).0 as usize) + .copied() + .unwrap_or(0) + { + 0 => { + root = Some(p); + break; + } + 2 => {} + _ => return, + } + } + let Some(root) = root else { + return; + }; + let above = ctx.facts.get(ctx.state([root[0], root[1] + 1, root[2]])); + // Mud above the root counts as a water source unless water evaporates here. + let (fluid, source) = if &*above.name == "minecraft:mud" && !ctx.ultrawarm { + (Fluid::Water, true) + } else { + (above.fluid, above.fluid_level >= 8 && !above.fluid_falling) + }; + // canFillCauldron: only a water or lava source passes below a 2% roll. + if roll >= 0.02 && !(fluid != Fluid::None && source) { + return; + } + // getDripParticle: no fluid drips what the dimension's default says. + let lava = fluid == Fluid::Lava || (fluid == Fluid::None && ctx.ultrawarm); + let ty = if lava { + T::DrippingDripstoneLava + } else { + T::DrippingDripstoneWater + }; + let offset = ctx.offset_of(state, pos); + // STALACTITE_DRIP_START_PIXEL is the tip's lowest point, 5/16. + let p = [ + f64::from(pos[0]) + 0.5 + offset[0], + f64::from(pos[1]) + 0.3125 - 0.0625, + f64::from(pos[2]) + 0.5 + offset[2], + ]; + add(engine, ty, p, [0.0; 3]); +} +/// `AmbientDesertBlockSoundsPlayer.shouldPlayAmbientSandSound`: sand in the +/// surface column eight blocks away on all four sides. +fn sand_sound_nearby(tables: &AnimateTables, ctx: &AnimateContext, pos: [i32; 3]) -> bool { + let is_sand = |p: [i32; 3]| { + tables + .desert_sand_sounds + .get(ctx.state(p).0 as usize) + .copied() + .unwrap_or(false) + }; + let (mut found, mut checked) = (0, 0); + for d in [[0, -8], [8, 0], [0, 8], [-8, 0]] { + let (x, z) = (pos[0] + d[0], pos[2] + d[1]); + // columnContainsTriggeringBlock. + let surface = ctx.world.world_surface(x, z, |s| ctx.facts.is_air(s)) - 1; + let matches = if (surface - pos[1]).abs() > 5 { + let mut y = pos[1] + 6; + let mut above_air = ctx.is_air([x, y, z]); + y -= 1; + let mut hit = false; + for _ in 0..10 { + if above_air && is_sand([x, y, z]) { + hit = true; + break; + } + above_air = ctx.is_air([x, y, z]); + y -= 1; + } + hit + } else { + ctx.is_air([x, surface + 1, z]) && is_sand([x, surface, z]) + }; + if matches { + found += 1; + if found > 3 { + return true; + } + } + checked += 1; + if 4 - checked + found < 3 { + return false; + } + } + false +} /// `AbstractCandleBlock.addParticlesAndSound`. fn candle(engine: &mut ParticleEngine, p: [f64; 3]) { let r = engine.random(); diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs index 6d8dc528b..9b46269ad 100644 --- a/crates/horizon-client/src/arrows.rs +++ b/crates/horizon-client/src/arrows.rs @@ -159,6 +159,8 @@ pub struct ArrowState { pub pickup: Pickup, /// `pickupItemStack`: what picking the arrow up gives. pub pickup_item: crate::items::ItemStack, + /// `AbstractArrow.firedFromWeapon`: the crossbow or bow it was shot from. + pub fired_from_weapon: Option, pub no_physics: bool, /// `AbstractArrow.getPierceLevel`. pub pierce: u8, @@ -208,6 +210,7 @@ impl ArrowState { last_state: None, pickup: Pickup::Disallowed, pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1), + fired_from_weapon: None, no_physics: false, pierce: 0, pierced: Vec::new(), diff --git a/crates/horizon-client/src/atlas_sources.rs b/crates/horizon-client/src/atlas_sources.rs index 1eea24666..fbed22fd2 100644 --- a/crates/horizon-client/src/atlas_sources.rs +++ b/crates/horizon-client/src/atlas_sources.rs @@ -3,8 +3,8 @@ //! `filter`, `unstitch` and `paletted_permutations` sources run in order //! against the resource tree; a later source replaces an earlier sprite of //! the same id and a filter removes the matching ones. -use crate::packs::pattern::Pattern; use horizon_assets::palette::apply_palette; +use horizon_client_core::pattern::Pattern; use serde_json::Value; use std::{ collections::BTreeMap, diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs index b899ea5d5..a86992735 100644 --- a/crates/horizon-client/src/auth.rs +++ b/crates/horizon-client/src/auth.rs @@ -179,7 +179,7 @@ fn agent() -> ureq::Agent { } /// The discovery document, fetched once per game (a failure is retried next time). -fn discovery() -> Result, JoinError> { +pub(crate) fn discovery() -> Result, JoinError> { static CACHE: Mutex>> = Mutex::new(None); if let Some(d) = CACHE.lock().unwrap().clone() { return Ok(d); diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index a312fe9f7..4bde9aeae 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -149,6 +149,8 @@ pub fn draw_part( layer: 0, color, light, + + glint_uv: [0.0, 0.0], }); } } @@ -650,6 +652,8 @@ fn draw_text(scene: &Scene, call: &TextCall, out: &mut Vec) { layer: 0, color: c, light: call.light, + + glint_uv: [0.0, 0.0], }); } } @@ -736,7 +740,7 @@ pub struct Scene<'a> { /// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer` /// profile → skin): a downloaded `skins/` slot or the profile's /// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (`DefaultPlayerSkin.getDefaultTexture`, slim steve). - pub skull: &'a dyn Fn([i32; 3]) -> Option<&'a str>, + pub skull: &'a dyn Fn([i32; 3]) -> Option, /// Font glyph cell (none for blank glyphs such as the space) and advance. pub glyph: &'a dyn Fn(char) -> (Option, f32), } @@ -934,6 +938,30 @@ impl BlockEntityRenderer { let lights = diffuse_lights(scene.nether); self.render_one(scene, pos, kind, base, packed, lights, false, false, out); } + /// `TheEndGatewayBlockEntity.shouldRenderFace` for each face of the gateway + /// at `pos`: the faces its portal is drawn on. + pub fn gateway_faces( + &self, + world: &World, + state: BlockStateId, + pos: [i32; 3], + ) -> Vec { + Direction::ALL + .into_iter() + .filter(|&d| { + let [dx, dy, dz] = d.normal(); + let neighbor = world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz); + self.visibility.as_ref().is_none_or(|v| { + v.lock() + .map(|mut v| { + v.should_render_face(state, neighbor, d, true) + .unwrap_or(true) + }) + .unwrap_or(true) + }) + }) + .collect() + } /// Whether this block state has a block-entity renderer here. pub fn renders(&self, state: u32) -> bool { !matches!(self.kind(state), Kind::None) @@ -1288,11 +1316,12 @@ impl BlockEntityRenderer { }; // SkullBlockRenderer.getRenderType: the profile's skin when it // resolves, `SKIN_BY_TYPE` (steve) otherwise. - let texture = if *kind == SkullType::Player { - (scene.skull)(pos).unwrap_or(texture) + let skin = if *kind == SkullType::Player { + (scene.skull)(pos) } else { - texture + None }; + let texture = skin.as_deref().unwrap_or(texture); let (Some(model), Some(paint)) = (self.models.get(model), paint(texture, 0xFFFFFF, packed)) else { @@ -1434,22 +1463,8 @@ impl BlockEntityRenderer { out, ); } - // AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace. - let faces: Vec = Direction::ALL - .into_iter() - .filter(|&d| { - let [dx, dy, dz] = d.normal(); - let neighbor = scene.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz); - self.visibility.as_ref().is_none_or(|v| { - v.lock() - .map(|mut v| { - v.should_render_face(BlockStateId(*state), neighbor, d, true) - .unwrap_or(true) - }) - .unwrap_or(true) - }) - }) - .collect(); + // AbstractEndPortalRenderer.extractRenderState. + let faces = self.gateway_faces(scene.world, BlockStateId(*state), pos); portal_cube(base, &faces, END_GATEWAY_LAYER, out); } Kind::Conduit => { @@ -1716,6 +1731,8 @@ impl BeamPart { layer: 6, color, light: self.wrap, + + glint_uv: [0.0, 0.0], }); } } @@ -1786,6 +1803,7 @@ fn portal_cube(m: Mat4, faces: &[Direction], layer: u32, out: &mut Vec) layer, color: 0, light: 0, + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/breaking.rs b/crates/horizon-client/src/breaking.rs index 84eedae75..df6d0f33b 100644 --- a/crates/horizon-client/src/breaking.rs +++ b/crates/horizon-client/src/breaking.rs @@ -49,6 +49,8 @@ pub fn geometry( color: 0xffff_ffff, light: stage_light(stage), normal: [0; 4], + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/brewing.rs b/crates/horizon-client/src/brewing.rs index cdd988a7a..b3cda5f90 100644 --- a/crates/horizon-client/src/brewing.rs +++ b/crates/horizon-client/src/brewing.rs @@ -7,257 +7,12 @@ use crate::{ items::{ItemStack, Items}, }; use serde_json::Value; -use std::{ - collections::{HashMap, HashSet}, - fs, - path::Path, - sync::{Arc, OnceLock}, -}; +use std::{collections::HashSet, fs, path::Path, sync::Arc}; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Category { - Beneficial, - Harmful, - Neutral, -} -/// A `MobEffect`: id (without namespace), colour, category, instantaneous. -#[derive(Clone, Copy, Debug)] -pub struct EffectDef { - pub id: &'static str, - pub color: u32, - pub category: Category, - pub instant: bool, -} -const fn fx(id: &'static str, color: u32, category: Category) -> EffectDef { - EffectDef { - id, - color, - category, - instant: false, - } -} -use Category::{Beneficial as B, Harmful as H, Neutral as N}; -/// `MobEffects` in registration order. -pub const EFFECTS: &[EffectDef] = &[ - fx("speed", 3402751, B), - fx("slowness", 9154528, H), - fx("haste", 14270531, B), - fx("mining_fatigue", 4866583, H), - fx("strength", 16762624, B), - EffectDef { - id: "instant_health", - color: 16262179, - category: B, - instant: true, - }, - EffectDef { - id: "instant_damage", - color: 11101546, - category: H, - instant: true, - }, - fx("jump_boost", 16646020, B), - fx("nausea", 5578058, H), - fx("regeneration", 13458603, B), - fx("resistance", 9520880, B), - fx("fire_resistance", 16750848, B), - fx("water_breathing", 10017472, B), - fx("invisibility", 16185078, B), - fx("blindness", 2039587, H), - fx("night_vision", 12779366, B), - fx("hunger", 5797459, H), - fx("weakness", 4738376, H), - fx("poison", 8889187, H), - fx("wither", 7561558, H), - fx("health_boost", 16284963, B), - fx("absorption", 2445989, B), - EffectDef { - id: "saturation", - color: 16262179, - category: B, - instant: true, - }, - fx("glowing", 9740385, N), - fx("levitation", 13565951, H), - fx("luck", 5882118, B), - fx("unluck", 12624973, H), - fx("slow_falling", 15978425, B), - fx("conduit_power", 1950417, B), - fx("dolphins_grace", 8954814, B), - fx("bad_omen", 745784, N), - fx("hero_of_the_village", 4521796, B), - fx("darkness", 2696993, H), - fx("trial_omen", 1484454, N), - fx("raid_omen", 14565464, N), - fx("wind_charged", 12438015, H), - fx("weaving", 7891290, H), - fx("oozing", 10092451, H), - fx("infested", 9214860, H), - fx("breath_of_the_nautilus", 65518, B), -]; -pub fn effect(id: &str) -> Option<&'static EffectDef> { - let id = id.trim_start_matches("minecraft:"); - EFFECTS.iter().find(|e| e.id == id) -} -/// Namespaced effect ids for mob effect storage. -pub fn namespaced(id: &'static str) -> &'static str { - static IDS: OnceLock> = OnceLock::new(); - IDS.get_or_init(|| { - EFFECTS - .iter() - .map(|e| { - ( - e.id, - &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()), - ) - }) - .collect() - }) - .get(id) - .copied() - .unwrap_or(id) -} -/// A `Potion`: id, name suffix (`item.minecraft.potion.effect.`) and -/// effects as (effect, duration ticks, amplifier). -#[derive(Clone, Copy, Debug)] -pub struct PotionDef { - pub id: &'static str, - pub name: &'static str, - pub effects: &'static [(&'static str, i32, i32)], -} -const fn p( - id: &'static str, - name: &'static str, - effects: &'static [(&'static str, i32, i32)], -) -> PotionDef { - PotionDef { id, name, effects } -} -/// `Potions` in registration order. -pub const POTIONS: &[PotionDef] = &[ - p("water", "water", &[]), - p("mundane", "mundane", &[]), - p("thick", "thick", &[]), - p("awkward", "awkward", &[]), - p("night_vision", "night_vision", &[("night_vision", 3600, 0)]), - p( - "long_night_vision", - "night_vision", - &[("night_vision", 9600, 0)], - ), - p("invisibility", "invisibility", &[("invisibility", 3600, 0)]), - p( - "long_invisibility", - "invisibility", - &[("invisibility", 9600, 0)], - ), - p("leaping", "leaping", &[("jump_boost", 3600, 0)]), - p("long_leaping", "leaping", &[("jump_boost", 9600, 0)]), - p("strong_leaping", "leaping", &[("jump_boost", 1800, 1)]), - p( - "fire_resistance", - "fire_resistance", - &[("fire_resistance", 3600, 0)], - ), - p( - "long_fire_resistance", - "fire_resistance", - &[("fire_resistance", 9600, 0)], - ), - p("swiftness", "swiftness", &[("speed", 3600, 0)]), - p("long_swiftness", "swiftness", &[("speed", 9600, 0)]), - p("strong_swiftness", "swiftness", &[("speed", 1800, 1)]), - p("slowness", "slowness", &[("slowness", 1800, 0)]), - p("long_slowness", "slowness", &[("slowness", 4800, 0)]), - p("strong_slowness", "slowness", &[("slowness", 400, 3)]), - p( - "turtle_master", - "turtle_master", - &[("slowness", 400, 3), ("resistance", 400, 2)], - ), - p( - "long_turtle_master", - "turtle_master", - &[("slowness", 800, 3), ("resistance", 800, 2)], - ), - p( - "strong_turtle_master", - "turtle_master", - &[("slowness", 400, 5), ("resistance", 400, 3)], - ), - p( - "water_breathing", - "water_breathing", - &[("water_breathing", 3600, 0)], - ), - p( - "long_water_breathing", - "water_breathing", - &[("water_breathing", 9600, 0)], - ), - p("healing", "healing", &[("instant_health", 1, 0)]), - p("strong_healing", "healing", &[("instant_health", 1, 1)]), - p("harming", "harming", &[("instant_damage", 1, 0)]), - p("strong_harming", "harming", &[("instant_damage", 1, 1)]), - p("poison", "poison", &[("poison", 900, 0)]), - p("long_poison", "poison", &[("poison", 1800, 0)]), - p("strong_poison", "poison", &[("poison", 432, 1)]), - p("regeneration", "regeneration", &[("regeneration", 900, 0)]), - p( - "long_regeneration", - "regeneration", - &[("regeneration", 1800, 0)], - ), - p( - "strong_regeneration", - "regeneration", - &[("regeneration", 450, 1)], - ), - p("strength", "strength", &[("strength", 3600, 0)]), - p("long_strength", "strength", &[("strength", 9600, 0)]), - p("strong_strength", "strength", &[("strength", 1800, 1)]), - p("weakness", "weakness", &[("weakness", 1800, 0)]), - p("long_weakness", "weakness", &[("weakness", 4800, 0)]), - p("luck", "luck", &[("luck", 6000, 0)]), - p("slow_falling", "slow_falling", &[("slow_falling", 1800, 0)]), - p( - "long_slow_falling", - "slow_falling", - &[("slow_falling", 4800, 0)], - ), - p("wind_charged", "wind_charged", &[("wind_charged", 3600, 0)]), - p("weaving", "weaving", &[("weaving", 3600, 0)]), - p("oozing", "oozing", &[("oozing", 3600, 0)]), - p("infested", "infested", &[("infested", 3600, 0)]), -]; -pub fn potion(id: &str) -> Option<&'static PotionDef> { - let id = id.trim_start_matches("minecraft:"); - POTIONS.iter().find(|p| p.id == id) -} -/// `PotionContents.BASE_POTION_COLOR` (ARGB -13083194) as RGB. -pub const BASE_POTION_COLOR: u32 = 0x385DC6; -/// `PotionContents.getColor`: amplifier-weighted mix of visible effect colours. -pub fn potion_color(id: Option<&str>) -> u32 { - let Some(def) = id.and_then(potion) else { - return BASE_POTION_COLOR; - }; - let (mut r, mut g, mut b, mut total) = (0u32, 0u32, 0u32, 0u32); - for (e, _, amp) in def.effects { - let Some(e) = effect(e) else { continue }; - let w = *amp as u32 + 1; - r += w * (e.color >> 16 & 255); - g += w * (e.color >> 8 & 255); - b += w * (e.color & 255); - total += w; - } - match ( - r.checked_div(total), - g.checked_div(total), - b.checked_div(total), - ) { - (Some(r), Some(g), Some(b)) => (r << 16) | (g << 8) | b, - _ => BASE_POTION_COLOR, - } -} +pub use horizon_client_core::potions::{ + BASE_POTION_COLOR, Category, EFFECTS, EffectDef, POTIONS, PotionDef, effect, namespaced, + potion, potion_color, +}; /// `MobEffectUtil.formatDuration` at 20 TPS: m:ss or h:mm:ss. pub fn format_duration(ticks: i32) -> String { let secs = ticks / 20; diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs index 948e2f4a9..49d29d5f9 100644 --- a/crates/horizon-client/src/bundle.rs +++ b/crates/horizon-client/src/bundle.rs @@ -211,6 +211,17 @@ impl Contents { self.weight.n >= self.weight.d } + /// `BundleItem.isBarVisible`, `getBarWidth` and `getBarColor`: the fullness bar + /// (width, RGB), blue until the bundle is full, then red. + pub fn bar(&self) -> Option<(i32, u32)> { + if self.weight.n <= 0 { + return None; + } + let width = (1 + self.weight.n * 12 / self.weight.d).min(13) as i32; + let color = if self.is_full() { 0xFF5454 } else { 0x7087FF }; + Some((width, color)) + } + /// `toImmutable`, written back into the bundle's component. pub fn store(self, bundle: &mut ItemStack) { let data = bundle.data_mut(); diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs index 03fb0676d..25a709e26 100644 --- a/crates/horizon-client/src/cauldron.rs +++ b/crates/horizon-client/src/cauldron.rs @@ -40,6 +40,8 @@ pub struct Interaction { /// The cauldron's new state. pub block: Option, pub sound: Option<&'static str>, + /// The custom statistic the player earns (`use_cauldron`, ...). + pub stat: Option<&'static str>, } fn state(name: &str, level: Option) -> BlockState { @@ -57,6 +59,7 @@ fn pass() -> Interaction { outcome: Outcome::Pass, block: None, sound: None, + stat: None, } } @@ -117,11 +120,12 @@ fn lowered(cauldron: &BlockState) -> BlockState { } } -fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction { +fn changed(block: BlockState, sound: Option<&'static str>, stat: &'static str) -> Interaction { Interaction { outcome: Outcome::Success, block: Some(block), sound, + stat: Some(stat), } } @@ -179,18 +183,22 @@ pub fn interact( stack.data_mut().dyed_color = None; stack.tidy(); } - return changed(lowered(cauldron), None); + return changed(lowered(cauldron), None, "clean_armor"); } let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| { if !can_fill { return pass(); } filled(player, ItemStack::new(new, 1), true); - changed(state("minecraft:cauldron", None), Some(sound)) + changed( + state("minecraft:cauldron", None), + Some(sound), + "use_cauldron", + ) }; let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| { filled(player, ItemStack::new("minecraft:bucket", 1), true); - changed(block, Some(sound)) + changed(block, Some(sound), "fill_cauldron") }; match item { "minecraft:lava_bucket" => { @@ -199,6 +207,7 @@ pub fn interact( outcome: Outcome::Consume, block: None, sound: None, + stat: None, } } else { empty_bucket( @@ -221,6 +230,7 @@ pub fn interact( outcome: Outcome::Consume, block: None, sound: None, + stat: None, } } else { empty_bucket( @@ -241,6 +251,7 @@ pub fn interact( changed( state("minecraft:water_cauldron", Some(1)), Some("minecraft:item.bottle.empty"), + "use_cauldron", ) } ("water", "minecraft:bucket") => fill_bucket( @@ -255,7 +266,11 @@ pub fn interact( ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"), true, ); - changed(lowered(cauldron), Some("minecraft:item.bottle.fill")) + changed( + lowered(cauldron), + Some("minecraft:item.bottle.fill"), + "use_cauldron", + ) } ("water", "minecraft:potion") => { if level == 3 || !water_potion { @@ -266,7 +281,7 @@ pub fn interact( // BlockState.cycle on a 1..=3 property next.properties .insert("level".into(), (level % 3 + 1).to_string()); - changed(next, Some("minecraft:item.bottle.empty")) + changed(next, Some("minecraft:item.bottle.empty"), "use_cauldron") } ("water", name) if name @@ -283,7 +298,7 @@ pub fn interact( cleaned.data_mut().banner_patterns.pop(); cleaned.tidy(); filled(player, cleaned, false); - changed(lowered(cauldron), None) + changed(lowered(cauldron), None, "clean_banner") } ("water", name) if name @@ -292,7 +307,7 @@ pub fn interact( .is_some_and(|c| COLORS.contains(&c)) => { filled(player, held.transmute("minecraft:shulker_box", 1), false); - changed(lowered(cauldron), None) + changed(lowered(cauldron), None, "clean_shulker_box") } ("lava", "minecraft:bucket") => fill_bucket( player, diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 04b9d486c..d7def2866 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -16,6 +16,9 @@ use crate::{ #[path = "chat_tests.rs"] mod tests; +/// `CommandHistory.PERSISTED_COMMANDS_FILE_NAME` and its size cap. +const COMMAND_HISTORY_FILE: &str = "command_history.txt"; +const MAX_PERSISTED_COMMAND_HISTORY: usize = 50; /// GuiMessageTag.systemSinglePlayer's indicator colour. pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0; @@ -80,6 +83,10 @@ impl ChatAbilities { ChatSource::Client => true, } } + /// `ChatAbilities.hasAnyRestrictions`: the Chat option takes something. + pub fn any_restriction(&self) -> bool { + *self != Self::new(ChatVisibility::Full) + } /// Whether the chat screen may send `input` (`hasAllowedInput`). pub fn allows(&self, input: &str) -> bool { if input.starts_with('/') { @@ -185,6 +192,10 @@ pub struct Chat { lines: Vec, /// Sent messages and commands (ChatComponent.recentChat). pub recent: Vec, + /// `CommandHistory`: the last commands, kept in `command_history.txt` + /// in the game folder once `load_history` has set it. + commands: Vec, + history_file: Option, scroll: usize, new_since_scroll: bool, pub options: ChatOptions, @@ -310,6 +321,17 @@ impl Chat { self.lines.clear(); self.scroll = 0; } + /// `new CommandHistory(gameFolder)`: the commands kept from earlier runs + /// start the chat's history (`ChatComponent`'s constructor). + pub fn load_history(&mut self, game_folder: &std::path::Path) { + let file = game_folder.join(COMMAND_HISTORY_FILE); + if let Ok(text) = std::fs::read_to_string(&file) { + self.commands = text.lines().map(str::to_owned).collect(); + self.recent.extend(self.commands.iter().cloned()); + } + self.history_file = Some(file); + } + /// `ChatComponent.addRecentChat`: a command also goes to the saved history. pub fn add_recent(&mut self, message: &str) { if self.recent.last().map(String::as_str) != Some(message) { if self.recent.len() >= 100 { @@ -317,6 +339,21 @@ impl Chat { } self.recent.push(message.to_owned()); } + if message.starts_with('/') && self.commands.last().map(String::as_str) != Some(message) { + if self.commands.len() >= MAX_PERSISTED_COMMAND_HISTORY { + self.commands.remove(0); + } + self.commands.push(message.to_owned()); + if let Some(file) = &self.history_file { + let mut text = self.commands.join("\n"); + text.push('\n'); + if let Err(e) = std::fs::write(file, text) { + log::error!( + "Failed to write {COMMAND_HISTORY_FILE}, command history will be missing: {e}" + ); + } + } + } } pub fn reset_scroll(&mut self) { self.scroll = 0; @@ -438,10 +475,71 @@ impl Chat { out.push(GuiDraw::Pop); out } - /// Draws [`Chat::layout`] into the HUD batch. + /// Draws [`Chat::layout`] into the HUD batch, and with the chat screen + /// open the restricted prompt above the lines. pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) { let draws = self.layout(batch.height as i32, ticks, focused); hud_layout::paint(batch, atlas, &draws); + if focused && self.abilities.any_restriction() { + let prompt = self.restricted_prompt(&atlas.font, batch.height as i32); + hud_layout::paint(batch, atlas, &prompt); + } + } + /// `ChatComponent.extractRenderState` for `FOREGROUND_RESTRICTED`: a + /// background row and the red, underlined "Chat is restricted" line in + /// the row above the messages, clipped to the chat's width. + fn restricted_prompt(&self, font: &crate::font::Font, height: i32) -> Vec { + let o = &self.options; + let scale = o.scale as f32; + let max_width = hud_layout::ceil(o.width_px() as f32 / scale); + let chat_bottom = hud_layout::floor((height - 40) as f32 / scale); + let entry_height = o.line_height(); + let bottom_to_text = + (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing + 0.5).floor() as i32; + let shown = self + .lines + .len() + .saturating_sub(self.scroll) + .min(self.lines_per_page(true)); + let top = chat_bottom - (shown as i32 + 1) * entry_height; + let mut prompt = Text::translate("chat_screen.restricted", &[]).with_style(&Style { + color: Some(text::RED), + underlined: Some(true), + ..Style::default() + }); + // ComponentRenderUtils.clipText. + let mut width = 0.0; + let fits = prompt + .chars() + .take_while(|(c, style)| { + width += font.advance(*c, style); + width <= max_width as f32 + }) + .count(); + if fits < prompt.chars().count() { + prompt = prompt.slice(0, fits); + } + vec![ + GuiDraw::Push(vec![ + PoseOp::Scale(scale, scale), + PoseOp::Translate(4.0, 0.0), + ]), + hud_layout::fill( + -2, + top, + max_width + 4 + 4, + top + entry_height, + hud_layout::as8(o.background_opacity as f32) << 24, + ), + GuiDraw::Text { + text: prompt, + x: 0, + y: top + entry_height - bottom_to_text - 1, + color: hud_layout::white(o.opacity as f32 * 0.9 + 0.1), + shadow: true, + }, + GuiDraw::Pop, + ] } /// The click action under a GUI-space cursor while chat is focused. pub fn click_at( diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index 7cd375343..b0dd377c7 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -2,6 +2,7 @@ //! threads can mesh and light immutable snapshots while the game thread edits //! (copy-on-write through `Arc::make_mut`). use horizon_core::paletted::{PalettedContainer, Strategy}; +use horizon_world::nbt::{Compound, Tag}; use horizon_world::registry::BlockStateId; use std::sync::{Arc, OnceLock}; @@ -155,7 +156,7 @@ pub struct Chunk { /// positions, applied once by LevelChunk.postProcessGeneration. pub postprocess: Vec<[i32; 3]>, /// Saved data Horizon keeps but does not simulate (save.rs). - pub saved: Option>, + pub saved: Option>, /// Entities read from a save (vanilla entity NBT), spawned on arrival. pub entities: Vec, /// Structure starts reaching into this chunk (`structures.References`): @@ -309,6 +310,76 @@ impl Chunk { } } +/// A proto chunk saved before it became final. Decoration writes into a +/// chunk's neighbours, and decorated chunks wait for theirs, so the chunks +/// past the finished ones hold writes that generating them again would lose +/// (whole structure pieces, trees, ores). Vanilla saves its proto chunks too. +pub struct SavedProto { + /// Blocks, scheduled ticks (in `saved`) and post-processing marks. + pub column: Chunk, + /// Decorated itself (`features`), not only written to by its neighbours + /// (`terrain`). + pub decorated: bool, + /// Block entity data in placement order, with `x`, `y` and `z`. + pub block_entities: Vec, + /// Entities placed by structures, with absolute `Pos`. + pub entities: Vec, +} + +/// A container's loot table and what Horizon rolled from it. Vanilla keeps +/// `LootTable` and `LootTableSeed` until the container is first opened; +/// Horizon rolls when it generates or loads the chunk, and saves the table +/// again while the container still holds exactly the rolled items. +#[derive(Clone, Debug, PartialEq)] +pub struct RolledLoot { + pub pos: (i32, i32, i32), + pub table: String, + /// The saved `LootTableSeed`, written back unless 0 (trySaveLootTable). + pub seed: Option, + /// The rolled `Items`. + pub items: Tag, +} +impl RolledLoot { + /// Puts the loot table back in place of `Items` while they are still the + /// roll; false once the container holds anything else. + pub fn restore(&self, map: &mut Compound) -> bool { + if map.get(&"Items".into()) != Some(&self.items) { + return false; + } + map.remove(&"Items".into()); + map.insert("LootTable".into(), Tag::String(self.table.as_str().into())); + if let Some(seed) = self.seed.filter(|s| *s != 0) { + map.insert("LootTableSeed".into(), Tag::Long(seed)); + } + true + } +} + +/// Save data loaded with a chunk that Horizon keeps but does not simulate. +#[derive(Clone, Debug, Default)] +pub struct ChunkExtras { + /// Chunk root keys written back as loaded (structures, PostProcessing, + /// InhabitedTime, blending data, ...). + pub root: Compound, + /// Block entities Horizon does not model. + pub block_entities: Vec, + /// The NBT of the modelled block entities as loaded, to restore the fields and + /// detail Horizon does not model when it saves them (`block_entity_nbt::overlay`). + pub block_entity_sources: Vec<((i32, i32, i32), Tag)>, + /// Every saved block entity's position in the order of the save's list, + /// the order `SerializableChunkData` puts them in the chunk's maps. + pub block_entity_order: Vec<(i32, i32, i32)>, + /// Scheduled ticks (`block_ticks`/`fluid_ticks`): delays relative to the + /// save time. Registered with the level's tick scheduler on arrival and + /// replaced with the scheduler's pending ticks when saving. + pub block_ticks: Vec, + pub fluid_ticks: Vec, + /// Game time written as `LastUpdate`. + pub last_update: i64, + /// Containers still holding their loot table's roll. + pub rolled_loot: Vec, +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/clouds.rs b/crates/horizon-client/src/clouds.rs index 70f29c132..5e9bb731a 100644 --- a/crates/horizon-client/src/clouds.rs +++ b/crates/horizon-client/src/clouds.rs @@ -179,6 +179,8 @@ impl Mesh { layer: 4, color: u32::MAX, light: shade, + + glint_uv: [0.0, 0.0], }); } }; diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 7c32bd829..d35a1adfa 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -54,6 +54,27 @@ fn strider_liquid_shape() -> VoxelShape { VoxelShape::from_cube([1, 2, 1], &[true, false]).expect("a valid half-block column") } +// Vanilla scopes this direction to Entity.move while a piston pushes it. +thread_local! { + static PISTON_NOCLIP: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Suppress the moving part of pistons moving in this direction during a push. +pub fn with_piston_noclip( + direction: horizon_core::geometry::Direction, + f: impl FnOnce() -> T, +) -> T { + struct Reset(Option); + impl Drop for Reset { + fn drop(&mut self) { + PISTON_NOCLIP.with(|value| value.set(self.0)); + } + } + let previous = PISTON_NOCLIP.with(|value| value.replace(Some(direction))); + let _reset = Reset(previous); + f() +} + pub struct SceneCollisions<'w, 'r> { pub world: &'w World, pub binding: &'w BlockCollisionRegistry<'r>, @@ -140,8 +161,21 @@ impl> EntityMovementWorld for EntityCo border.collision_shape().map(Some).map_err(io::Error::other) } } -impl EntityCollisions<'_, SceneCollisions<'_, '_>> { - /// `SceneCollisions::resolve` that also stops at the entity boxes. +impl<'a, W> EntityCollisions<'a, W> +where + W: BlockCollisionWorld + EntityMovementWorld, +{ + /// `EntityCollisions` for a body the world border also stops: the border + /// and the body's own x and z (`WorldBorder.isInsideCloseToBorder`). + pub fn with_border(blocks: W, border: &'a BorderGeometry, at: [f64; 2]) -> Self { + Self { + blocks, + entities: &[], + border: Some((border, at)), + } + } + /// `SceneCollisions::resolve` that also stops at the entity boxes and, + /// with a border, at the world border's walls. pub fn resolve( &mut self, bounds: Aabb, @@ -149,12 +183,11 @@ impl EntityCollisions<'_, SceneCollisions<'_, '_>> { max_step: f32, on_ground: bool, ) -> Result { - let context = self.blocks.context(bounds); Ok(resolve_world_movement( self, MovementRequest { entity: EntityIdentity(0), - context, + context: CollisionContext::position(bounds.min_position().y), bounds, movement, max_step, @@ -324,7 +357,7 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> { return Ok(None); }; pistons - .collision_shape(self, p, piston, None) + .collision_shape(self, p, piston, PISTON_NOCLIP.with(|value| value.get())) .map(Some) .map_err(io::Error::other) } @@ -388,6 +421,42 @@ impl PowderSnowWorld for SceneCollisions<'_, '_> { } } +/// A collision world without blocks: no chunk is resident, so only the +/// world border stops a body. +pub struct EmptyCollisions; + +impl BlockCollisionWorld for EmptyCollisions { + type Error = io::Error; + type Chunk = ChunkPos; + fn collision_chunk(&mut self, _: ChunkPos) -> io::Result> { + Ok(None) + } + fn collision_block(&mut self, _: ChunkPos, _: BlockPos) -> io::Result { + Err(io::Error::other("no chunk is resident")) + } + fn is_suffocating(&mut self, _: ChunkPos, _: CollisionBlock, _: BlockPos) -> io::Result { + Ok(false) + } + fn context_shape( + &mut self, + _: CollisionBlock, + _: BlockPos, + _: &CollisionContext<'_>, + ) -> io::Result { + Ok(VoxelShape::empty()) + } +} + +impl EntityMovementWorld for EmptyCollisions { + type Error = io::Error; + fn entity_collisions(&mut self, _: EntityIdentity, _: Aabb) -> io::Result> { + Ok(Vec::new()) + } + fn movement_border(&mut self, _: EntityIdentity, _: Aabb) -> io::Result> { + Ok(None) + } +} + /// Collision queries over any block lookup (test worlds without chunks): /// every chunk is present, nothing is suffocating, no entities collide. pub struct LookupCollisions<'w, 'r> { @@ -475,3 +544,70 @@ impl PowderSnowWorld for LookupCollisions<'_, '_> { Ok(false) } } + +#[cfg(test)] +mod piston_noclip_tests { + use super::*; + use horizon_core::geometry::Direction; + + #[test] + fn piston_noclip_is_scoped_and_restored_after_unwind() { + assert_eq!(PISTON_NOCLIP.with(|value| value.get()), None); + with_piston_noclip(Direction::East, || { + assert_eq!( + PISTON_NOCLIP.with(|value| value.get()), + Some(Direction::East) + ); + let _ = + std::panic::catch_unwind(|| with_piston_noclip(Direction::West, || panic!("test"))); + assert_eq!( + PISTON_NOCLIP.with(|value| value.get()), + Some(Direction::East) + ); + }); + assert_eq!(PISTON_NOCLIP.with(|value| value.get()), None); + } +} + +#[cfg(test)] +mod border_movement_tests { + use super::*; + + /// A border 10 wide around the origin: its wall's inner face is at x = 5. + fn border() -> BorderGeometry { + BorderGeometry::new([0.0, 0.0], 10.0, 29_999_984).expect("a border") + } + + /// `WorldBorder.isInsideCloseToBorder` and `WorldBorder.getCollisionShape`: + /// a body inside close to the border collides with the border's walls. + #[test] + fn a_body_next_to_the_border_stops_at_its_wall() { + // A body 0.6 wide, 0.4 blocks short of the wall, moved east into it. + let bounds = Aabb::new(Vec3::new(4.0, 0.0, 0.0), Vec3::new(4.6, 1.8, 0.6)); + let border = border(); + let mut collisions = EntityCollisions::with_border(EmptyCollisions, &border, [4.3, 0.3]); + let moved = collisions + .resolve(bounds, Vec3::new(0.51, 0.0, 0.0), 0.0, false) + .expect("the movement resolves"); + // The wall stops the body 0.4 blocks short of the whole move. + assert!( + (moved.x - 0.4).abs() < 1.0e-9, + "the body was not stopped by the border: {moved:?}" + ); + } + + /// Away from the border, the same body moves the whole way. + #[test] + fn a_body_away_from_the_border_moves_whole() { + let bounds = Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.6, 1.8, 0.6)); + let border = border(); + let mut collisions = EntityCollisions::with_border(EmptyCollisions, &border, [0.3, 0.3]); + let moved = collisions + .resolve(bounds, Vec3::new(0.51, 0.0, 0.0), 0.0, false) + .expect("the movement resolves"); + assert!( + (moved.x - 0.51).abs() < 1.0e-9, + "the body did not move the whole way: {moved:?}" + ); + } +} diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 8ca9af0ad..af867903f 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -98,9 +98,34 @@ pub enum BlockEntity { Campfire(Box), /// `SkullBlockEntity` of every skull and head block. Skull(Skull), + /// `TheEndGatewayBlockEntity`: its age and configured destination. + EndGateway(EndGateway), /// `DaylightDetectorBlockEntity`: no data, only the ticker /// (`DaylightDetectorBlock.tickEntity`). DaylightDetector, + /// `ChiseledBookShelfBlockEntity`: a `Container` of six one-book slots. + ChiseledBookshelf(Box), +} +/// `ChiseledBookShelfBlockEntity`: six slots and `lastInteractedSlot`. +#[derive(Clone, Debug, PartialEq)] +pub struct ChiseledBookshelf { + pub items: [Option; 6], + pub last_slot: i32, +} +impl Default for ChiseledBookshelf { + fn default() -> Self { + Self { + items: Default::default(), + last_slot: -1, + } + } +} +/// `TheEndGatewayBlockEntity`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EndGateway { + pub age: i64, + pub exit_portal: Option<[i32; 3]>, + pub exact_teleport: bool, } /// `CampfireBlockEntity`: four cooking slots, each with its /// `cookingProgress` and `cookingTime` (the recipe's). @@ -190,6 +215,9 @@ impl Skull { #[derive(Clone, Debug)] pub struct SkullSkin { pub download: Option<(String, String)>, + /// `ResolvableProfile.nameOrId` when the profile is `Dynamic` (a name or + /// an id only): the key `skins::Resolver` resolves it by. + pub dynamic: Option, pub fallback: &'static str, } impl SkullSkin { @@ -198,10 +226,21 @@ impl SkullSkin { let location = crate::skins::skin_location(&crate::skins::texture_hash(&url)?); Some((url, location)) }); + // A `Dynamic` profile (a name or id only) resolves through the + // services when the skull is drawn. + let dynamic = crate::skins::dynamic_nbt(profile); // DefaultPlayerSkin.get(id), or getDefaultSkin (slim steve) without an id. let fallback = crate::skins::profile_uuid_nbt(profile) + .or_else(|| { + crate::skins::nbt_text(profile.get("name")) + .map(|name| horizon_protocol::crypto::offline_uuid(&name)) + }) .map_or("entity/player/slim/steve", crate::tab_list::default_skin); - Self { download, fallback } + Self { + download, + dynamic, + fallback, + } } } /// The skull and head blocks (`SkullBlock`, `WallSkullBlock`): every @@ -366,6 +405,9 @@ impl BlockEntity { if is_skull(name) { return Some(Self::Skull(Skull::default())); } + if name == "minecraft:end_gateway" { + return Some(Self::EndGateway(EndGateway::default())); + } if name == "minecraft:daylight_detector" { return Some(Self::DaylightDetector); } @@ -381,6 +423,9 @@ impl BlockEntity { if name == "minecraft:campfire" || name == "minecraft:soul_campfire" { return Some(Self::Campfire(Box::default())); } + if name == "minecraft:chiseled_bookshelf" { + return Some(Self::ChiseledBookshelf(Box::default())); + } let size = match name { "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27, n if n.ends_with("copper_chest") => 27, @@ -418,8 +463,10 @@ impl BlockEntity { Self::Beehive(_) => "minecraft:beehive", Self::CommandBlock(_) => "minecraft:command_block", Self::Skull(_) => "minecraft:skull", + Self::EndGateway(_) => "minecraft:end_gateway", Self::DaylightDetector => "minecraft:daylight_detector", Self::Campfire(_) => "minecraft:campfire", + Self::ChiseledBookshelf(_) => "minecraft:chiseled_bookshelf", } } pub fn contents(&self) -> Vec { @@ -436,6 +483,7 @@ impl BlockEntity { | Self::Vault(_) | Self::Beehive(_) | Self::CommandBlock(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), @@ -443,6 +491,7 @@ impl BlockEntity { Self::Banner(_) => Vec::new(), Self::Crafter(c) => c.items.iter().flatten().cloned().collect(), Self::Campfire(c) => c.items.iter().flatten().cloned().collect(), + Self::ChiseledBookshelf(b) => b.items.iter().flatten().cloned().collect(), } } pub fn slots(&self) -> &[Option] { @@ -456,9 +505,11 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => &[], Self::Crafter(c) => &c.items, + Self::ChiseledBookshelf(b) => &b.items, Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) @@ -480,9 +531,11 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => &mut [], Self::Crafter(c) => &mut c.items, + Self::ChiseledBookshelf(b) => &mut b.items, Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) @@ -728,6 +781,18 @@ impl Furnace { .recipes_used .entry(recipe_used_key(&recipe.id)) .or_insert(0) += 1; + // AbstractFurnaceBlockEntity.burn: drying a wet sponge fills + // the bucket in the fuel slot. + if self.items[0] + .as_ref() + .is_some_and(|i| &*i.item == "minecraft:wet_sponge") + && self.items[1] + .as_ref() + .is_some_and(|f| &*f.item == "minecraft:bucket") + { + self.items[1] = + Some(ItemStack::new("minecraft:water_bucket", 1)); + } if let Some(i) = self.items[0].as_mut() { i.count -= 1; if i.count == 0 { diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs index e147bfb4c..5490808a1 100644 --- a/crates/horizon-client/src/crash.rs +++ b/crates/horizon-client/src/crash.rs @@ -105,9 +105,13 @@ impl Report { } } -/// The release this binary is (`v0.2.3`); for a release from before 0.2, its tag and the client's -/// crate version; for a build from source, that version alone. +/// The release this binary is (`v0.2.3`); a nightly's label (`Nightly 2026-10-28 · 0c02067`); for a +/// release from before 0.2, its tag and the client's crate version; for a build from source, that +/// version alone. pub fn version() -> String { + if let Some(label) = horizon_core::release::nightly_label() { + return label; + } let version = env!("CARGO_PKG_VERSION"); match (horizon_core::release::RELEASE, release_tag()) { (Some(_), Some(tag)) => tag, @@ -117,8 +121,12 @@ pub fn version() -> String { } /// The release this binary came with: the version release.yml built in (docs/versioning.md), else -/// the folder the launcher installed it in, named after the tag (releases from before 0.2). +/// the folder the launcher installed it in, named after the tag (releases from before 0.2). A +/// nightly is its version as the launcher installs it (`nightly-2026-10-28-0c02067`). pub fn release_tag() -> Option { + if let Some(nightly) = horizon_core::release::nightly_version() { + return Some(nightly); + } if let Some(version) = horizon_core::release::RELEASE { return Some(format!("v{version}")); } @@ -525,6 +533,11 @@ mod tests { #[test] fn a_release_reports_its_built_in_version() { // release.yml builds with HORIZON_VERSION (docs/versioning.md): `v0.2.3`, wherever it is installed. + if let Some(label) = horizon_core::release::nightly_label() { + assert_eq!(super::version(), label); + assert_eq!(release_tag(), horizon_core::release::nightly_version()); + return; + } match horizon_core::release::RELEASE { Some(version) => { assert_eq!(release_tag(), Some(format!("v{version}"))); diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 16a7a273a..9511fd112 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -2,7 +2,7 @@ //! add/update with hidden effects, per-tick application of the periodic //! effects (regeneration, poison, wither, hunger, saturation, instant //! effects), and the derived flags the movement and damage code read. -use crate::brewing; +use horizon_client_core::potions; #[derive(Clone, Debug, PartialEq)] pub struct EffectInstance { @@ -183,7 +183,7 @@ impl PlayerEffects { pub fn from_saved(saved: &[(String, i32, i32, bool, bool)]) -> Self { let mut effects = Self::default(); for (id, duration, amplifier, ambient, particles) in saved { - if let Some(def) = brewing::effect(id) { + if let Some(def) = potions::effect(id) { let mut e = EffectInstance::new(def.id, *duration, *amplifier); e.ambient = *ambient; e.visible = *particles; @@ -214,8 +214,9 @@ impl PlayerEffects { } /// `LivingEntity.tickEffects` (server part) with the omens' effect ticks: /// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect` - /// (on its last tick). Returns the actions to apply, in order, and - /// whether Raid Omen was newly added. + /// (on its last tick); `absorption_empty` is `AbsorptionMobEffect`'s + /// answer: the effect ends once the absorption is used up. Returns the + /// actions to apply, in order, and whether Raid Omen was newly added. /// /// Bad Omen turning into a new Raid Omen adds an entry to the map being /// iterated: vanilla's iterator then throws a @@ -225,6 +226,7 @@ impl PlayerEffects { pub fn tick_with( &mut self, omen: &mut dyn FnMut(&EffectInstance) -> OmenTick, + absorption_empty: bool, ) -> (Vec, bool) { self.tick_count = self.tick_count.wrapping_add(1); let mut actions = Vec::new(); @@ -247,6 +249,7 @@ impl PlayerEffects { let answer = match e.id { "bad_omen" => omen(e), "raid_omen" if t == 1 => omen(e), + "absorption" if absorption_empty => OmenTick::Remove, _ => OmenTick::Continue, }; match answer { @@ -303,10 +306,10 @@ impl PlayerEffects { ) -> (Vec, Vec) { let mut lasting = Vec::new(); let mut now = Vec::new(); - if let Some(def) = potion.and_then(brewing::potion) { + if let Some(def) = potion.and_then(potions::potion) { for (id, duration, amp) in def.effects { - let id = brewing::effect(id).map_or("speed", |e| e.id); - if brewing::effect(id).is_some_and(|e| e.instant) { + let id = potions::effect(id).map_or("speed", |e| e.id); + if potions::effect(id).is_some_and(|e| e.instant) { now.extend(instant(id, *amp, 1.0)); } else { // withScaledDuration: max(floor(d * scale), 1). @@ -466,13 +469,13 @@ mod tests { }; // The first tick adds Raid Omen and stops there (the iterator's // ConcurrentModificationException): Bad Omen and Speed stay as they were. - let (_, added) = fx.tick_with(&mut convert); + let (_, added) = fx.tick_with(&mut convert, false); assert!(added); assert_eq!(fx.get("bad_omen").unwrap().duration, 100); assert_eq!(fx.get("speed").unwrap().duration, 50); assert_eq!(fx.get("raid_omen").unwrap().duration, 600); // The second refreshes Raid Omen and drops Bad Omen. - let (_, added) = fx.tick_with(&mut convert); + let (_, added) = fx.tick_with(&mut convert, false); assert!(!added); assert!(fx.get("bad_omen").is_none()); assert_eq!(fx.get("speed").unwrap().duration, 49); @@ -487,9 +490,9 @@ mod tests { seen.push(e.duration); OmenTick::Remove }; - fx.tick_with(&mut watch); + fx.tick_with(&mut watch, false); assert!(fx.get("raid_omen").is_some()); - fx.tick_with(&mut watch); + fx.tick_with(&mut watch, false); assert!(fx.get("raid_omen").is_none()); assert_eq!(seen, vec![1]); } diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 14cd946c2..3039e1611 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -771,9 +771,24 @@ pub struct ArmorStand { pub name_visible: bool, /// Game time of the last hit (the wobble and the second-hit window). pub last_hit: i64, + /// `DATA_HEAD_POSE` to `DATA_RIGHT_LEG_POSE`: head, body, left arm, right + /// arm, left leg, right leg, in degrees (`POSE_KEYS` order). + pub pose: [[f32; 3]; 6], } impl ArmorStand { pub const SLOTS: [&'static str; 6] = ["mainhand", "offhand", "feet", "legs", "chest", "head"]; + /// The `Pose` compound's keys. + pub const POSE_KEYS: [&'static str; 6] = + ["Head", "Body", "LeftArm", "RightArm", "LeftLeg", "RightLeg"]; + /// `ArmorStand.DEFAULT_*_POSE`. + pub const DEFAULT_POSE: [[f32; 3]; 6] = [ + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [-10.0, 0.0, -10.0], + [-15.0, 0.0, 10.0], + [-1.0, 0.0, -1.0], + [1.0, 0.0, 1.0], + ]; pub fn new(id: u32, position: Vec3, yaw: f32) -> Self { Self { fire_ticks: 0, @@ -792,6 +807,7 @@ impl ArmorStand { custom_name: None, name_visible: false, last_hit: i64::MIN / 2, + pose: Self::DEFAULT_POSE, } } pub fn environment_tick( diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2541a4b35..e90b9dd66 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -14,7 +14,8 @@ struct Globals { // Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: array, 2>, // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000) - // y: Nether cardinal lighting, z: how many dynamic_lights are set. + // y: Nether cardinal lighting, z: how many dynamic_lights are set, + // w: the glint scroll clock (`Glint::scroll_ticks`). time: vec4, crumbling_sprite: vec4, // Selection outline parameters (read by terrain.wgsl). @@ -27,6 +28,12 @@ struct Globals { @group(0) @binding(2) var atlas_sampler: sampler; @group(0) @binding(3) var lightmap: texture_2d; @group(0) @binding(4) var lightmap_sampler: sampler; +// enchanted_glint_item on its own repeating texture (vanilla's GlintSampler). +@group(0) @binding(5) var glint_tex: texture_2d; +@group(0) @binding(6) var glint_sampler: sampler; +// The armour layers' GlintSampler: vanilla samples enchanted_glint_armor with +// the same repeating, linearly filtered sampler as the item glint. +@group(0) @binding(7) var glint_armor_tex: texture_2d; struct Out { @builtin(position) clip: vec4, @location(0) uv: vec2, @@ -44,6 +51,9 @@ struct Out { // entity.vsh's lightMapColor, multiplied in after the overlay. @location(9) light_color: vec4, @location(10) @interpolate(flat) weather_rect: vec4, + // The `GLINT_TEXTURING` sample for overlay 7 (item foil), or the model UV + // `ARMOR_ENTITY_GLINT_TEXTURING` scrolls for overlay 13 (armour). + @location(11) glint_uv: vec2, } // Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed. fn entity_light(normal: vec3, nether: bool) -> f32 { @@ -103,18 +113,23 @@ fn entity_vertex(position: vec3, uv: vec2, out.spherical = select(length(position), 0.0, overlay >= 2u && overlay <= 4u); out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u && overlay <= 4u); out.overlay = overlay; + out.glint_uv = vec2(0.0); if overlay == 4u { out.spherical = length(position); } return out; } @vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, - @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out { - return entity_vertex(position, uv, overlay, color, light, normal); + @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, + @location(5) normal: vec4, @location(6) glint_uv: vec2) -> Out { + var out = entity_vertex(position, uv, overlay, color, light, normal); + out.glint_uv = glint_uv; + return out; } // Retained bolt-local geometry, translated using the same f64 camera // subtraction as the former CPU path before adding each local f32 position. +// The bolt offset is instance attribute 7: 6 is the entity vertex's glint UV. @vertex fn vs_lightning(@location(0) position: vec3, @location(1) uv: vec2, @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4, - @location(6) offset: vec3) -> Out { + @location(7) offset: vec3) -> Out { return entity_vertex(offset + position, uv, overlay, color, light, normal); } struct CloudInfo { @@ -166,6 +181,27 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { if d >= end { return 1.0; } return (d - start) / (end - start); } +// TextureTransform.setupGlintTexturing(0.16), ARMOR_ENTITY_GLINT_TEXTURING. +// globals.time.w is (Util.getMillis() * glintSpeed * 8) modulo 330000, the +// common period of both offsets. +fn armor_glint_uv(model: vec2) -> vec2 { + let ticks = globals.time.w; + let offset0 = (ticks % 110000.0) / 110000.0; + let offset1 = (ticks % 30000.0) / 30000.0; + let angle = 0.17453292; + let c = cos(angle); + let s = sin(angle); + let scaled = model * 0.16; + return vec2(scaled.x * c - scaled.y * s - offset0, + scaled.x * s + scaled.y * c + offset1); +} +// RenderPipelines.GLINT: the source colour is scaled by itself, so `GlintAlpha` +// is squared along with the sample. +fn glint_over(color: vec4, glint: vec4) -> vec4 { + let alpha = globals.fog_ends.w; + let g = alpha * glint; + return vec4(color.rgb + g.rgb * g.rgb, max(color.a, alpha)); +} // CRUMBLING_UV_BEGIN fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, dimensions: vec2) -> vec2 { let size = vec2(dimensions); @@ -204,21 +240,29 @@ fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, color = vec4(mix(in.overlay_color.rgb, color.rgb, in.overlay_color.a), color.a); color *= in.light_color; if in.overlay == 7u || in.overlay == 8u || in.overlay == 33u { - // Enchantment glint (overlay 7, 8 with the hurt tint): the purple - // enchanted_glint sheen drifting diagonally over the item's shape. - let px = in.uv * vec2(textureDimensions(atlas)); - let t = globals.misc.y * 0.05; - let band = sin((px.x + px.y) * 0.9 - t * 6.0) * 0.5 + 0.5; - let band2 = sin((px.x - px.y) * 0.6 + t * 4.0) * 0.5 + 0.5; - let shimmer = pow(band * 0.6 + band2 * 0.4, 2.0); - let glint = vec3(0.50, 0.25, 0.80) * (0.25 + 0.75 * shimmer); - color = vec4(min(color.rgb + glint * 0.6, vec3(1.0)), color.a); + // 33: a translucent item with the glint. + // Enchantment glint: item.fsh's GLINT path, sampled from + // enchanted_glint_item at the `GLINT_TEXTURING` UV. + color = glint_over(color, textureSample(glint_tex, glint_sampler, in.glint_uv)); + } else if in.overlay == 13u { + // Enchanted armour: enchanted_glint_armor at the scrolling model UV. + color = glint_over( + color, + textureSample(glint_armor_tex, glint_sampler, armor_glint_uv(in.glint_uv)), + ); } let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)); return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); } +// rendertype_outline.fsh: the vertex colour (the team colour; outline vertices carry no +// normal, so no cardinal light) wherever the texture is not fully clear. +@fragment fn fs_outline(in: Out) -> @location(0) vec4 { + if textureSample(atlas, atlas_sampler, in.uv).a == 0.0 { discard; } + return vec4(in.color.rgb, 1.0); +} + fn celestial_color(in: Out) -> vec4 { return textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; } @@ -237,6 +281,20 @@ fn celestial_color(in: Out) -> vec4 { return vec4(added, smoothstep(0.1, 0.3, max(added.r, max(added.g, added.b)))); } +// RenderPipelines.ENERGY_SWIRL (entity.fsh with EMISSIVE and NO_OVERLAY): the sprite, scrolled by +// the UV and repeated within itself, times the layer colour 0xFF808080, unlit; the pipeline adds +// it to the frame. The light bytes carry the sprite's origin and the colour bytes its size, both +// as breaking::stage_light packs them. +@fragment fn fs_energy_swirl(in: Out) -> @location(0) vec4 { + let bytes = round(in.color * 255.0); + let size = vec2(bytes.x + bytes.y * 256.0, bytes.z + bytes.w * 256.0) / 65535.0; + let color = textureSample(atlas, atlas_sampler, crumbling_uv(in.uv, in.wrap, size, textureDimensions(atlas))); + if color.a < 0.1 { discard; } + let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), + linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)); + return vec4(mix(color.rgb * (128.0 / 255.0), globals.fog_color.rgb, f * globals.fog_color.a), color.a); +} + // RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off). @fragment fn fs_water_mask() -> @location(0) vec4 { return vec4(0.0); diff --git a/crates/horizon-client/src/entity_culling.rs b/crates/horizon-client/src/entity_culling.rs index 16de17465..0c309041a 100644 --- a/crates/horizon-client/src/entity_culling.rs +++ b/crates/horizon-client/src/entity_culling.rs @@ -186,6 +186,8 @@ mod tests { color: u32::MAX, light: 0, normal: [0; 4], + + glint_uv: [0.0, 0.0], }; let prior = vertex([0.0; 3]); let body = [vertex([8.0, -1.0, -1.0]), vertex([10.0, 1.0, 1.0])]; diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index c65f35f5b..0fee9feca 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -339,6 +339,18 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8)); } + "minecraft:panda" => { + use crate::mobs::panda::GENES; + for (key, gene) in [ + ("MainGene", m.extra.variant), + ("HiddenGene", m.extra.variant2), + ] { + map.insert( + key.into(), + string(GENES[usize::from(gene).min(GENES.len() - 1)]), + ); + } + } "minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => { // Only Piglin.addAdditionalSaveData writes CannotHunt. if id == "minecraft:piglin_brute" { @@ -498,10 +510,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { Tag::Int(i32::from(m.extra.variant.min(4))), ); } - // Rabbit.addAdditionalSaveData (the legacy id; 99 is the killer bunny). - "minecraft:rabbit" => { - map.insert("RabbitType".into(), Tag::Int(i32::from(m.extra.variant))); - } "minecraft:parrot" => { map.insert( "Variant".into(), @@ -581,6 +589,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.insert("anger".into(), Tag::compound(Vec::<(&str, Tag)>::new())); } } + // Armadillo.addAdditionalSaveData: the time left to the next scute. + "minecraft:armadillo" => { + map.insert("scute_time".into(), Tag::Int(m.extra.egg_time)); + } "minecraft:ravager" => { map.insert("AttackTick".into(), Tag::Int(m.extra.counter)); map.insert("StunTick".into(), Tag::Int(m.extra.counter2)); @@ -1094,6 +1106,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); } + if m.species() == crate::mobs::Species::Panda { + let gene = |key| text(tag.get(key)).map_or(0, |n| crate::mobs::panda::gene_from_name(&n)); + m.extra.variant = gene("MainGene"); + m.extra.variant2 = gene("HiddenGene"); + } if m.species() == crate::mobs::Species::Wolf { let health = m.health; m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner")); @@ -1202,6 +1219,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - st.vibration = crate::sculk::Data::from_nbt(listener); } } + // Armadillo.readAdditionalSaveData: keeps the constructor's time when absent. + if m.species() == crate::mobs::Species::Armadillo + && let Some(t) = number(tag.get("scute_time")) + { + m.extra.egg_time = t as i32; + } if m.species() == crate::mobs::Species::Ravager { m.extra.counter = number(tag.get("AttackTick")).unwrap_or(0) as i32; m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32; @@ -1826,6 +1849,15 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) -> } put(&mut tag, "Health", Tag::Float(a.health.to_bits())); put(&mut tag, "Fire", Tag::Short(a.fire_ticks as i16)); + // ArmorStand.addAdditionalSaveData: the `Pose` parts that are not default. + let pose: Vec<(&str, Tag)> = ArmorStand::POSE_KEYS + .into_iter() + .zip(a.pose) + .zip(ArmorStand::DEFAULT_POSE) + .filter(|((_, rotation), default)| rotation != default) + .map(|((key, rotation), _)| (key, floats(&rotation))) + .collect(); + put(&mut tag, "Pose", Tag::compound(pose)); // LivingEntity.addAdditionalSaveData and ArmorStand's own fields. if let Tag::Compound(map) = &mut tag { for (key, value) in [ @@ -1865,6 +1897,19 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { a.invisible = flag(tag, "Invisible"); a.marker = flag(tag, "Marker"); a.on_ground = flag(tag, "OnGround"); + // ArmorStand.readAdditionalSaveData: each part of `Pose` that is a list of + // three numbers, the others staying at their defaults. + if let Some(pose) = tag.get("Pose") { + for (rotation, key) in a.pose.iter_mut().zip(ArmorStand::POSE_KEYS) { + if let Some(Tag::List(values)) = pose.get(key) + && values.len() == 3 + { + for (r, v) in rotation.iter_mut().zip(values) { + *r = float(Some(v)).unwrap_or(0.0) as f32; + } + } + } + } Some(a) } /// A boat entity (`minecraft:_boat`, `minecraft:bamboo_chest_raft`...): diff --git a/crates/horizon-client/src/fire_render.rs b/crates/horizon-client/src/fire_render.rs index c3a9f6a92..98eff6f9d 100644 --- a/crates/horizon-client/src/fire_render.rs +++ b/crates/horizon-client/src/fire_render.rs @@ -48,6 +48,8 @@ pub fn flames( color: 0xffff_ffff, light: 0xf000 | (u32::from(scene_light >> 4) * 16), normal: [0; 4], + + glint_uv: [0.0, 0.0], }); } remaining -= 0.45; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0719878eb..aa1b03669 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -22,7 +22,9 @@ mod bundles; mod campfire; mod campfire_douse; mod cartography; +mod cat_spawner; mod chat; +mod chiseled_bookshelf; mod client_ambient; mod clipboard; mod combat; @@ -34,6 +36,7 @@ mod consume; mod control; mod copper_golems; mod creaking; +mod creative_hotbar; mod creatures; mod crossbow; pub(crate) mod cushions; @@ -65,6 +68,7 @@ mod functions; mod game_mode; mod gamemode_switcher; mod ghasts; +mod glowing; mod golems; mod growth; mod hand; @@ -127,11 +131,14 @@ mod packs; mod pad; mod pad_menu; mod paintings; +mod pandas; mod passengers; mod persist; mod perspective; +mod pick_entity; mod pickups; mod piglins; +mod piston_push; mod player_equip; mod postprocess; mod potions; @@ -570,6 +577,8 @@ struct GameLevel<'w> { player_collision: Option, /// Minecart boxes (detector rails). cart_boxes: Vec<([f64; 3], [f64; 3])>, + /// Each minecart's kind and comparator signal, in `cart_boxes` order. + cart_signals: Vec<(minecarts::CartKind, i32)>, /// Arrow and thrown trident boxes (wooden buttons). arrow_boxes: Vec<([f64; 3], [f64; 3])>, /// The other entities that keep blocks from being placed into them. @@ -648,6 +657,37 @@ impl EntityObstructionWorld for BuildingObstruction { } } impl GameLevel<'_> { + /// `DetectorRailBlock.getAnalogOutputSignal`: a powered rail reads the + /// minecart on it, a command block cart first (its success count, which + /// is 0 here), else the first container cart's fullness. + fn detector_rail_signal(&self, pos: BlockPos, powered: bool) -> i32 { + if !powered { + return 0; + } + let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z)); + let area = Aabb::new( + Vec3::new(x + 0.2, y, z + 0.2), + Vec3::new(x + 0.8, y + 0.8, z + 0.8), + ); + let mut container = None; + for ((lo, hi), &(kind, signal)) in self.cart_boxes.iter().zip(&self.cart_signals) { + let cart = Aabb::new( + Vec3::new(lo[0], lo[1], lo[2]), + Vec3::new(hi[0], hi[1], hi[2]), + ); + if !area.intersects(cart) { + continue; + } + match kind { + minecarts::CartKind::CommandBlock => return 0, + minecarts::CartKind::Chest | minecarts::CartKind::Hopper => { + container = container.or(Some(signal)); + } + _ => {} + } + } + container.unwrap_or(0) + } /// Every entity box that blocks building: the players who aren't /// spectators, the minecarts and the `Blockers` (a removed mob or a marker /// armor stand, whose box is empty, doesn't). @@ -706,8 +746,16 @@ impl LevelAccess for GameLevel<'_> { &self, pos: BlockPos, state: BlockStateId, - _direction: Direction, + direction: Direction, ) -> i32 { + if let Some(s) = self.registry.state(state) + && s.name == "minecraft:detector_rail" + { + return self.detector_rail_signal( + pos, + s.properties.get("powered").is_some_and(|v| v == "true"), + ); + } if let Some(signal) = command_blocks::analog_signal(self.world, (pos.x, pos.y, pos.z)) { return signal; } @@ -731,6 +779,11 @@ impl LevelAccess for GameLevel<'_> { if let Some(signal) = books::lectern_signal(self.world, pos) { return signal; } + if let Some(signal) = + machines::shelf_signal(self.world, self.registry, state, pos, direction) + { + return signal; + } machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos) } fn block_entity_signal( @@ -1240,6 +1293,8 @@ struct Game<'a> { pending_pack_reload: bool, /// A server's resource packs (game/server_packs.rs). server_packs: server_packs::ServerPackState, + /// The link a chat click asks to open (`ConfirmLinkScreen`). + link_prompt: Option, dialogs: dialogs::DialogState, world_renderer_ready: bool, collision: &'a BlockCollisionRegistry<'a>, @@ -1347,6 +1402,8 @@ struct Game<'a> { /// Runs of `entity_vertices` by entity, for a shader pack's per-entity draws; recorded only /// while `pack_ids` is set (game/shader_packs.rs). entity_spans: std::cell::RefCell>, + /// The glowing entities' silhouettes this frame (game/glowing.rs). + glowing_vertices: std::cell::RefCell>, /// The shader pack's entity and block entity ids, while one draws entities. pack_ids: Option, started: Instant, @@ -1437,6 +1494,9 @@ struct Game<'a> { armor: [Option; 4], /// The off hand (Inventory slot 40, saved as slot 150; menu slot 504 here). offhand: Option, + /// `ItemStack.popTime` of the nine hotbar stacks, then the off hand: set to 5 + /// when a slot gains items, counted down each tick. + hotbar_pop: [u8; 10], /// The hand an item use acts with (`InteractionHand`): the off hand only /// for its turn in `use_item` and while its item is being used. hand: Hand, @@ -1482,6 +1542,8 @@ struct Game<'a> { /// `ClientAvatarState`: walked distance and view bob. avatar: horizon_client::camera::AvatarBob, flash: u32, + /// `ClientLevel.rainSoundTime`: ticks of rain since the last rain sound. + rain_sound_time: i32, /// Bolts that struck here and sky flashes they made, in total (`status`). lightning_seen: [u32; 2], /// The head of the bed while sleeping; the visual timer also survives waking. @@ -1489,6 +1551,8 @@ struct Game<'a> { sleep_timer: u32, dim: Dim, world_root: PathBuf, + /// The world is superflat (`ServerLevel.isFlat`, for every dimension). + world_flat: bool, /// A player carried through a portal, re-placed once the destination loads. travelling: Option<(PlayerMotion, Vec3)>, /// A server's players on their way to another level, each waiting for @@ -1564,10 +1628,19 @@ struct Game<'a> { /// Map textures waiting for the next HUD batch to upload them. map_patches: Vec, text_displays: std::collections::HashMap, + /// The fence knots a server tracks to this client, by entity id, at their + /// block (`LeashFenceKnotEntity`). + remote_knots: HashMap, + /// The entity ids a hosted server gives the knots its mobs hang on, by + /// block, while a lead is tied there. + knot_ids: HashMap<[i32; 3], u32>, text_display_vertices: usize, /// Player skin downloads, and which skin each atlas skin slot holds /// (least recently shown first). skin_downloads: RefCell, + /// `ProfileResolver.Cached`: `Dynamic` profiles (name- or id-only heads + /// and mannequins) resolve through the services in the background. + skin_profiles: RefCell, skin_slots: Vec<(String, usize)>, /// Atlas trim slots in use: (sprite name, slot), least recently drawn first. trim_slots: Vec<(String, usize)>, @@ -2469,6 +2542,15 @@ impl Game<'_> { no_physics, &self.res.motion().fluids, ); + // Entity.applyEffectsFromBlocks: bubble columns lift or drag the item. + horizon_client::motion::bubble_column_push( + &self.world, + self.pack.assets.registry, + self.res.facts(), + self.collision, + item.bounds(), + &mut item.velocity, + ); cells.moved(i, item.previous, item.position); // ItemEntity.tick: merge every 2 ticks while moving between // blocks, every 40 otherwise, before the lifetime check. @@ -2577,8 +2659,14 @@ impl Game<'_> { pickups::Taken::Item(Box::new(item.clone())), pickups::Collector::Player, ); + // handleTakeItemEntity: the random pitch of a full pickup. + let pitch = ((self.world.random.next_float() + - self.world.random.next_float()) + * 0.7 + + 1.0) + * 2.0; self.audio - .play("minecraft:entity.item.pickup", Some(feet), 0.2, 1.0); + .play("minecraft:entity.item.pickup", Some(feet), 0.2, pitch); } item.stack = rest; } @@ -2635,6 +2723,7 @@ impl Game<'_> { ) }) .collect(); + let cart_signals = self.cart_signals(); let arrow_boxes = self .creatures .projectiles @@ -2677,6 +2766,7 @@ impl Game<'_> { }; let mut level = GameLevel { cart_boxes, + cart_signals, arrow_boxes, blockers, world: &mut self.world, @@ -2731,9 +2821,13 @@ impl Game<'_> { self.process_level_events() } fn attack_block(&mut self, pos: [i32; 3]) -> Result<()> { - self.with_level(|b, level, ticks| { - b.attack_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2])); + let note = self.with_level(|b, level, ticks| { + b.attack_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2])) }); + // NoteBlock.attack awards the statistic. + if note { + self.stats.custom("play_noteblock", 1); + } self.process_level_events() } /// Track which chunks are ticking (Ticks needs chunk load/unload). @@ -2929,20 +3023,29 @@ impl Game<'_> { b.run_block_events(level, ticks); b.tick_block_entities(level, ticks); }); + // `PistonMovingBlockEntity.tick` pushes what its block just ran into, + // with the progress it is about to take. + let pushes = std::mem::take(&mut self.block_ticks.piston_pushes); + self.push_piston_entities(pushes); + self.process_level_events()?; self.sync_moving_pistons(); - self.process_level_events() + Ok(()) } /// Copies the moving-piston block entities into the world, where the /// collision queries and the renderer read them. fn sync_moving_pistons(&mut self) { - let pistons = &mut self.world.moving_pistons; - pistons.clear(); - pistons.extend( - self.block_ticks - .moving_pistons - .iter() - .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())), - ); + let previous = std::mem::take(&mut self.world.moving_pistons); + let current: Vec<_> = self + .block_ticks + .moving_pistons + .iter() + .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())) + .collect(); + self.world.moving_piston_fallback = previous + .into_iter() + .filter(|(pos, _)| !current.iter().any(|(next, _)| next == pos)) + .collect(); + self.world.moving_pistons = current; } /// `ServerLevel.tick`'s scheduled block then fluid ticks, one at a time: /// the side effects of each (a shrieker summoning a warden, drops, game @@ -3044,6 +3147,11 @@ impl Game<'_> { pos, data, } => self.consume_teleport_particles([pos.x, pos.y, pos.z], data), + LevelEvent::LevelEvent { + id: 2018, + pos, + data, + } => self.enderman_teleport_particles([pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id: 2003, pos, .. } => { self.eye_break_particles([pos.x, pos.y, pos.z]); } @@ -3073,6 +3181,34 @@ impl Game<'_> { pos, data, } => self.composter_fill_event(pos, data == 1), + // LevelEventHandler 1504: the stalactite's drip particle. + LevelEvent::LevelEvent { id: 1504, pos, .. } => self.dripstone_drip_particle(pos), + // LevelEventHandler 2006: the dragon fireball's burst. + LevelEvent::LevelEvent { + id: 2006, + pos, + data, + } => self.dragon_fireball_burst(pos, data), + // LevelEventHandler 2009: a wet sponge drying. + LevelEvent::LevelEvent { id: 2009, pos, .. } => { + self.puffs_above_block(pos, horizon_client::particles::ParticleType::Cloud) + } + // LevelEventHandler 2012: a turtle egg laid. + LevelEvent::LevelEvent { + id: 2012, + pos, + data, + } => self.turtle_egg_particles(pos, data), + // LevelEventHandler 2014: a straw bed destroyed, with no sound. + LevelEvent::LevelEvent { + id: 2014, + pos, + data, + } => self.destroy_particles([pos.x, pos.y, pos.z], BlockStateId(data as u32)), + // LevelEventHandler 3009: a sniffer egg cracking. + LevelEvent::LevelEvent { id: 3009, pos, .. } => { + self.sniffer_egg_crack_particles(pos) + } LevelEvent::LevelEvent { id: id @ 3011..=3021, pos, @@ -3088,6 +3224,16 @@ 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)), + 1033 => Some(("minecraft:block.chorus_flower.grow", 1.0)), + 1034 => Some(("minecraft:block.chorus_flower.death", 1.0)), + 1046 => Some(( + "minecraft:block.pointed_dripstone.drip_lava_into_cauldron", + 2.0, + )), + 1047 => Some(( + "minecraft:block.pointed_dripstone.drip_water_into_cauldron", + 2.0, + )), // LevelEvent.SOUND_ZOMBIE_WOODEN_DOOR (attack, break). 1019 => Some(("minecraft:entity.zombie.attack_wooden_door", 2.0)), 1021 => Some(("minecraft:entity.zombie.break_wooden_door", 2.0)), @@ -3109,6 +3255,13 @@ impl Game<'_> { - self.world.random.next_float()) * 0.8 } + // LevelEventHandler draws these from the client + // level's random, before 1501's and 1502's smoke. + 1501 | 1502 => { + let r = self.particles.level_random(); + 2.6 + (r.next_float() - r.next_float()) * 0.8 + } + 1046 | 1047 => self.particles.level_random().next_float() * 0.1 + 0.9, 1029 | 1030 | 1042 | 1043 | 1044 | 1053 | 1054 => { self.world.random.next_float() * 0.1 + 0.9 } @@ -3127,6 +3280,15 @@ impl Game<'_> { self.audio.play(name, c, volume, pitch); } } + // LevelEventHandler 1501 and 1502 draw their smoke after the sound. + match id { + 1501 => self.puffs_above_block( + pos, + horizon_client::particles::ParticleType::LargeSmoke, + ), + 1502 => self.torch_burnout_smoke(pos), + _ => {} + } } LevelEvent::Sound { pos, @@ -3193,6 +3355,8 @@ impl Game<'_> { // Popped as the behaviour emits it (GameLevel::emit). PlayerEffect::DropItem(_) => {} PlayerEffect::EatCake => { + // CakeBlock.eat + self.stats.custom("eat_cake_slice", 1); if let Some(p) = self.player.as_mut() { let food = &mut p.health.food; food.food = (food.food + 2).min(20); @@ -3326,20 +3490,21 @@ impl Game<'_> { self.open_command_block(key); return; } + // SignBlock.useWithoutItem: the text editor, not a container. + if horizon_client::signs::sign_kind(&name).is_some() { + self.use_sign_empty_hand(pos); + return; + } if &*name == "minecraft:crafting_table" { self.craft_size = 3; self.craft_table = Some(pos); } else if &*name == "minecraft:ender_chest" { self.open_ender_chest(key); - self.container_opener_event(key, true); - let at = [ - f64::from(key.0) + 0.5, - f64::from(key.1) + 0.5, - f64::from(key.2) + 0.5, - ]; - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio - .play("minecraft:block.ender_chest.open", Some(at), 0.5, pitch); + // EnderChestBlock.useWithoutItem + self.stats.custom("open_enderchest", 1); + if self.container_opener_event(key, true) { + self.container_edge_sound(key, true); + } } else if &*name == "minecraft:beacon" && self.open_station(pos, &name) { self.world.block_entities.get_or_insert_with(key, || { BlockEntity::for_block(&name).unwrap_or(BlockEntity::Chest(Vec::new())) @@ -3355,7 +3520,7 @@ impl Game<'_> { ]; self.resolve_container_maps(key, centre); self.container = Some(key); - self.container_opener_event(key, true); + let first = self.container_opener_event(key, true); self.post_block_game_event( "minecraft:container_open", [key.0, key.1, key.2], @@ -3379,26 +3544,8 @@ impl Game<'_> { if self.guarded_by_piglins(&name) { self.anger_piglins(true); } - let sound = if storage::is_shulker_box(&name) { - Some("minecraft:block.shulker_box.open") - } else if name.contains("chest") { - Some("minecraft:block.chest.open") - } else if &*name == "minecraft:barrel" { - Some("minecraft:block.barrel.open") - } else { - None - }; - if let Some(sound) = sound { - self.audio.play( - sound, - Some([ - f64::from(key.0) + 0.5, - f64::from(key.1) + 0.5, - f64::from(key.2) + 0.5, - ]), - 0.5, - 1.0, - ); + if first { + self.container_edge_sound(key, true); } } else if self.open_station(pos, &name) { // Workstation menus: game/stations.rs. @@ -3722,6 +3869,21 @@ impl Game<'_> { { self.hive_broken_by_player(pos, hive, honey, facing); } + // InfestedBlock.spawnAfterBreak: its silverfish comes out unless the + // tool has silk touch (#prevents_infested_spawns) or blocks don't drop. + if facts.name.starts_with("minecraft:infested_") + && !silk + && self.ui.rules.bool("block_drops") + { + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + if let Some(id) = self.spawn_mob("minecraft:silverfish", at, false) { + self.mob_poof(id); + } + } // SpawnerBlock.spawnAfterBreak pops its experience whatever the tool. let xp = if silk && &*facts.name != "minecraft:spawner" { 0 @@ -3739,6 +3901,20 @@ impl Game<'_> { ); } } + // IceBlock.playerDestroy: the ice melts back into water (the + // #prevents_ice_melting tool tag holds only silk touch). + let prevents_melting = held + .as_ref() + .is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0); + self.with_level(|b, level, ticks| { + b.ice_destroyed_by_player( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + broken, + prevents_melting, + ); + }); } self.pending.clear(pos); self.process_level_events()?; @@ -3843,10 +4019,24 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_sign_applicator(hit.pos, held.as_ref()) { + self.swing_arm(); + return Ok(true); + } + if self.use_golem_statue(hit.pos, held.as_ref()) { + self.swing_arm(); + return Ok(true); + } if self.use_jukebox(hit.pos, held.as_ref()) { self.swing_arm(); return Ok(true); } + if let Some(swings) = self.use_chiseled_bookshelf(hit, held.as_ref()) { + if swings { + self.swing_arm(); + } + return Ok(true); + } if self.use_composter(hit.pos, held.as_ref()) { self.swing_arm(); return Ok(true); @@ -3863,6 +4053,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_beehive(hit.pos, held.as_ref())? { + self.swing_arm(); + return Ok(true); + } if self.use_campfire_douse(hit.pos, held.as_ref())? { self.swing_arm(); return Ok(true); @@ -3902,6 +4096,20 @@ impl Game<'_> { ) }); self.process_level_events()?; + // NoteBlock.useWithoutItem (tuned) and BellBlock.onHit (rung). + if result == horizon_world::level::InteractionResult::Success { + let name = self + .res + .facts() + .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])) + .name + .clone(); + match &*name { + "minecraft:note_block" => self.stats.custom("tune_noteblock", 1), + "minecraft:bell" => self.stats.custom("bell_ring", 1), + _ => {} + } + } if result.consumes_action() { self.swing_arm(); return Ok(true); @@ -3991,6 +4199,7 @@ impl Game<'_> { || self.place_minecart(hit, &stack) || self.place_painting(hit, &stack) || self.place_item_frame(hit, &stack) + || self.use_lodestone_compass(hit, &stack) || self.place_armor_stand(hit, &stack) || self.place_cushion(hit, &stack) || self.place_end_crystal(hit, &stack)) @@ -4041,6 +4250,7 @@ impl Game<'_> { return Ok(true); }; let target = [pos.x, pos.y, pos.z]; + let state = self.apply_item_block_state(target, state, &stack)?; self.mod_block_event(target, state, true); if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { let key = (target[0], target[1], target[2]); @@ -4205,6 +4415,8 @@ impl Game<'_> { self.release_used_item(&stack, ticks, hand_changed); return; } + // ServerPlayer.updateUsingItem: USING_ITEM every tick of the use. + self.trigger_using_item(&stack); let Some(info) = self.res.items().get(&stack.item).cloned() else { self.using = None; return; @@ -4723,15 +4935,13 @@ impl Game<'_> { for event in events { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet), - MotionEvent::Emission { - state, in_water, .. - } => { + MotionEvent::Emission { state, muffled, .. } => { let sounds = self.res.facts().get(state).sounds.clone(); // Entity.playStepSound: the block's step sound at 0.15 volume, // muffled under the swim sound in water. Whether it plays is // Player.getMovementEmission's call (shift on the ground), // not the pose: a forced crouch still steps. - let (volume, pitch) = if in_water { + let (volume, pitch) = if muffled { (sounds.volume * 0.05, sounds.pitch * 0.8) } else { (sounds.volume * 0.15, sounds.pitch) @@ -4792,6 +5002,10 @@ impl Game<'_> { }; self.audio.play(name, Some(feet), volume, pitch); } + // Player.causeFallDamage: a fall of 2 blocks or more counts. + MotionEvent::Fall(horizon_client::landing::FallEvent::Statistic(cm)) => { + self.stats.custom("fall_one_cm", cm) + } // LivingEntity.checkFallDamage: the block's crumbs where the fall landed. MotionEvent::Fall(horizon_client::landing::FallEvent::Particles { state, @@ -4901,9 +5115,14 @@ impl Game<'_> { if let Some(host) = &self.lan { host.hub.entity_event(host.host_entity, 3, feet); } - self.screen = Screen::Dead; - self.capture(false); - self.ui.death_time = 0; + if self.ui.rules.bool("immediate_respawn") { + // Gui.setScreen: without the death screen the player respawns at once. + self.respawn_player()?; + } else { + self.screen = Screen::Dead; + self.capture(false); + self.ui.death_time = 0; + } } else if dead { // LivingEntity.tickDeath: 20 ticks after dying the player is // removed, and Player.remove's inventoryMenu.removed drops what @@ -4950,6 +5169,7 @@ impl Game<'_> { horizon_client::spans::time("tick_thunder", || self.tick_thunder()); horizon_client::spans::time("tick_lecterns", || self.tick_lecterns()); horizon_client::spans::time("tick_maps", || self.tick_maps()); + self.tick_lodestone_compasses(); horizon_client::spans::time("tick_bolts", || self.tick_bolts()); horizon_client::spans::time("tick_fishing", || self.tick_fishing()); horizon_client::spans::time("tick_tridents", || self.tick_tridents()); @@ -5348,7 +5568,10 @@ impl Game<'_> { let decorations = hud_overlays::ItemDecorations { count: stack.count, count_text, - bar: hud_overlays::damage_bar(stack.damage as i32, max_damage), + // BundleItem overrides the bar with its fullness. + bar: horizon_client::bundle::Contents::of(self.res.items(), stack) + .map(|c| c.bar()) + .unwrap_or_else(|| hud_overlays::damage_bar(stack.damage as i32, max_damage)), cooldown: self.cooldowns.percent(&cooldown, partial), }; let mut draws = vec![hud_layout::GuiDraw::Push(vec![ @@ -5375,6 +5598,7 @@ impl Game<'_> { }; self.draw_dialog(&mut batch); self.draw_pack_prompt(&mut batch); + self.draw_link_prompt(&mut batch); // Gui.extractRenderState: the debug overlay comes after the screen // and the toasts, so it is over everything, menus included. self.draw_debug_overlay(&mut batch, size); @@ -5414,12 +5638,12 @@ impl Game<'_> { // The ToastManager draws over every screen: a server's packs // download while the connection screen shows. if self.remote_overlay(&mut batch) { - self.draw_pack_toasts(&mut batch); + self.draw_pack_toasts(&mut batch, false); return batch; } if let Some(reason) = self.loading_reason() { self.draw_level_loading(&mut batch, reason); - self.draw_pack_toasts(&mut batch); + self.draw_pack_toasts(&mut batch, false); return batch; } // Hud.extractRenderState: F1 (keyToggleGui) hides camera overlays, the @@ -5428,6 +5652,9 @@ impl Game<'_> { let spectator = self.spectator(); let (wi, hi) = (w as i32, h as i32); let show_hud = !self.ui.hide_gui; + // max(Hud.leftHeight, Hud.rightHeight) after the bars: the item name and + // the action bar sit above it. + let mut bar_height = 39; if show_hud { self.draw_spyglass(&mut batch); // Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth / @@ -5436,7 +5663,11 @@ impl Game<'_> { let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed()); let strength = self.hand_strength.scale(0.0, self.main_hand_attack_speed()); // The 3D crosshair (F3) takes the 2D one's place. - if self.camera_type.first_person() && !spectator && !self.debug_crosshair() { + // Hud.extractCrosshair: a spectator only sees it over something to open. + if self.camera_type.first_person() + && (!spectator || self.spectator_crosshair()) + && !self.debug_crosshair() + { let attack = (indicator == 1).then_some(strength); let full = attack.is_some_and(|a| { hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) @@ -5445,12 +5676,17 @@ impl Game<'_> { hud_layout::paint(&mut batch, &self.gui.atlas, &draws); } if !spectator { + let partial = self.clock.fraction() as f32; let inputs = hud_layout::HotbarInputs { selected: self.selected as i32, right_handed: !self.settings.main_hand_left, offhand: self.offhand.is_some(), - slots: std::array::from_fn(|i| self.inventory[i].as_ref().map(|_| 0.0)), - offhand_pop: 0.0, + slots: std::array::from_fn(|i| { + self.inventory[i] + .as_ref() + .map(|_| (f32::from(self.hotbar_pop[i]) - partial).max(0.0)) + }), + offhand_pop: (f32::from(self.hotbar_pop[9]) - partial).max(0.0), attack: (indicator == 2).then_some(strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); @@ -5497,6 +5733,8 @@ impl Game<'_> { contextual == ContextualBar::JumpableVehicle, ) }; + // Without the survival bars only the mount's hearts raise it. + bar_height = 39 + 10 * ((vehicle_hearts + 9) / 10); if contextual == ContextualBar::Locator { let (sprite, [x, y, w, h]) = horizon_client::locator_bar::background(wi, hi); horizon_client::ui::nine_slice( @@ -5535,17 +5773,9 @@ impl Game<'_> { } else { hud_layout::HeartKind::Normal }; - let eye = p.position.y + f64::from(p.dimensions.eye_height); - let under_water = self - .res - .facts() - .get(self.world.block( - p.position.x.floor() as i32, - eye.floor() as i32, - p.position.z.floor() as i32, - )) - .fluid - == horizon_client::blocks::Fluid::Water; + // Hud.extractAirBubbles: `isEyeInFluidMatching`, so the eyes are below + // the surface, not merely in the water block. + let under_water = p.is_eye_in_fluid(horizon_client::motion::WATER); let inputs = hud_layout::HealthInputs { tick: self.ticks as i32, millis: self.started.elapsed().as_millis() as i64, @@ -5570,20 +5800,24 @@ impl Game<'_> { }; let draws = self.health_hud.layout(&inputs, wi, hi); hud_layout::paint(&mut batch, atlas, &draws); + bar_height = self + .health_hud + .left_height + .max(self.health_hud.right_height); } if contextual == ContextualBar::Locator { let draws = self.locator_bar_draws(wi, hi); hud_layout::paint(&mut batch, &self.gui.atlas, &draws); } if !spectator { - self.draw_selected_name(&mut batch, !self.creative); + self.draw_selected_name(&mut batch, bar_height, !self.creative); } } // Hud.extractSleepOverlay: over all health/food bars, under titles and chat. let draws = hud_overlays::sleep_overlay(wi, hi, self.sleep_timer as i32); hud_layout::paint(&mut batch, &self.gui.atlas, &draws); if show_hud { - self.draw_titles(&mut batch); + self.draw_titles(&mut batch, bar_height); self.draw_scoreboard(&mut batch); self.draw_subtitles(&mut batch); } @@ -5637,8 +5871,9 @@ impl Game<'_> { Screen::Playing | Screen::Options | Screen::Win => {} } self.draw_saving_indicator(&mut batch); - self.draw_toasts(&mut batch); - self.draw_pack_toasts(&mut batch); + // ToastManager.extractRenderState: F1 hides the toasts too. + self.draw_toasts(&mut batch, !show_hud); + self.draw_pack_toasts(&mut batch, !show_hud); self.remote_hud(&mut batch); self.draw_sign_editor(&mut batch); self.draw_book(&mut batch); @@ -5693,9 +5928,11 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector - | BlockEntity::Campfire(_), + | BlockEntity::Campfire(_) + | BlockEntity::ChiseledBookshelf(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -5965,9 +6202,11 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector - | BlockEntity::Campfire(_), + | BlockEntity::Campfire(_) + | BlockEntity::ChiseledBookshelf(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { @@ -6046,41 +6285,15 @@ impl Game<'_> { if let Some(key) = self.container.take() { // A cart's or chest boat's items go back to it. self.close_cart_container(key); - self.container_opener_event(key, false); + let last = self.container_opener_event(key, false); self.post_block_game_event( "minecraft:container_close", [key.0, key.1, key.2], Some(horizon_client::mobs::Who::Player), None, ); - let name = self - .res - .facts() - .get(self.world.block(key.0, key.1, key.2)) - .name - .clone(); - let sound = if storage::is_shulker_box(&name) { - Some("minecraft:block.shulker_box.close") - } else if &*name == "minecraft:ender_chest" { - Some("minecraft:block.ender_chest.close") - } else if name.contains("chest") { - Some("minecraft:block.chest.close") - } else if &*name == "minecraft:barrel" { - Some("minecraft:block.barrel.close") - } else { - None - }; - if let Some(sound) = sound { - self.audio.play( - sound, - Some([ - f64::from(key.0) + 0.5, - f64::from(key.1) + 0.5, - f64::from(key.2) + 0.5, - ]), - 0.5, - 1.0, - ); + if last { + self.container_edge_sound(key, false); } self.world.modified.insert((key.0 >> 4, key.2 >> 4)); } @@ -6600,6 +6813,7 @@ impl Game<'_> { self.player_menu_sound(sound); } let crafted = std::mem::take(&mut menu.crafted); + let brewed = std::mem::take(&mut menu.brewed); let equipped = std::mem::take(&mut menu.equipped); for (i, stack) in after.into_iter().enumerate() { if let Some(g) = game_of[i] { @@ -6615,6 +6829,9 @@ impl Game<'_> { self.player_drop(stack); } self.award_crafted(&crafted); + for stack in &brewed { + self.trigger_brewed_potion(stack); + } if furnace_before > furnace_after && self.remote.is_none() && let (Some(pos), Some(p)) = (self.container, self.player.as_ref()) @@ -7653,6 +7870,8 @@ impl Game<'_> { layer: 0, color, light: packed, + + glint_uv: [0.0, 0.0], }); } } @@ -7934,13 +8153,15 @@ impl Game<'_> { } /// The visual and sound part of `Player.doSweepAttack` after a successful hit. pub(super) fn sweep_attack(&mut self, at: [f64; 3], from: Option<[f64; 3]>) { - self.particles.add( - &horizon_client::particles::ParticleOptions::simple( - horizon_client::particles::ParticleType::SweepAttack, - ), - at, - [0.0; 3], + let sweep = horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::SweepAttack, ); + self.particles.add(&sweep, at, [0.0; 3]); + // Player.sweepAttack's `sendParticles(SWEEP_ATTACK, ..., 0, dx, 0, dz, 0)`: + // the offset is the one from the player to the particle. + let origin = from.unwrap_or(at); + let spread = [at[0] - origin[0], 0.0, at[2] - origin[2]]; + self.lan_send_particles(&sweep, at, spread, 0.0, 0); self.audio .play("minecraft:entity.player.attack.sweep", from, 1.0, 1.0); } @@ -8095,11 +8316,6 @@ impl Game<'_> { let sweep = self.sweep_attack_position(scale, crit); let (knockback, knockback_attack) = self.extra_knockback(&target_kind, scale); self.attack_ticks = 0; - if let Some(p) = self.player.as_mut() - && !self.creative - { - p.cause_food_exhaustion(0.1); - } let player = self.player.as_ref(); let from = player.map(|p| [p.position.x, p.position.y, p.position.z]); if knockback_attack { @@ -8114,6 +8330,15 @@ impl Game<'_> { None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic), }; let landed = self.hurt_by_player(index, amount, source); + if landed { + let victim = self.mob_entity(&self.mobs[index]); + self.player_hit( + &victim, + creatures::damage_type(source.kind, true), + None, + amount, + ); + } if let Some(p) = self.player.as_mut() { if p.attack_log.len() >= 64 { p.attack_log.remove(0); @@ -8179,6 +8404,14 @@ impl Game<'_> { 0.2, (actual * 0.5) as u32, ); + // The players a server serves are sent them too. + self.lan_send_particles( + &indicator, + [feet[0], feet[1] + height * 0.5, feet[2]], + [0.1, 0.0, 0.1], + 0.2, + (actual * 0.5) as u32, + ); } self.last_hurt_by_player .insert(self.mobs[index].id, self.lan_acting); @@ -8199,16 +8432,32 @@ impl Game<'_> { // The hurt or death sound the mob raised (getHurtSound / getDeathSound, // its voice pitch from its own random). let queued = std::mem::take(&mut self.mobs[index].outbox); + let mut infested = false; for event in queued { - 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); + match event { + horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) => { + self.audio + .play(&format!("minecraft:{s}"), Some(at), volume, pitch); + } + horizon_client::mobs::MobEvent::Infested { .. } => infested = true, + other => { + // Left for the end of the tick. + self.mobs[index].outbox.push(other); + } } } + if infested { + let id = self.mobs[index].id; + self.mob_infested(id); + } self.weapon_hit(index); + // Player.attack: causeFoodExhaustion(0.1F) only when the hit hurt + // (inside `if (wasHurt)`), after damageStatsAndHearts. + if let Some(p) = self.player.as_mut() + && !self.creative + { + p.cause_food_exhaustion(0.1); + } } else { self.audio .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); @@ -8261,24 +8510,34 @@ impl Game<'_> { } /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. /// Returns the sun and moon quads, and the stars' frame and brightness - /// (the renderer keeps their geometry, built once). + /// (the renderer keeps their geometry, built once). The bodies fade with + /// the rain (`rainBrightness = 1 - rainLevel`, their colour's alpha). fn celestial_geometry( &self, sky: &horizon_client::environment::Sky, + rain: f32, ) -> (Vec, Option<(glam::Mat4, f32)>) { + let body_color = + 0x00FF_FFFF | (((1.0 - rain).clamp(0.0, 1.0) * 255.0).round() as u32) << 24; let mut out = Vec::new(); let atlas = &self.gui.atlas; let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) }; - let mut body = |name: &str, angle: f32, size: f32, color: u32| { + let mut body = |name: &str, angle: f32, size: f32, moon: bool| { let Some(r) = atlas.sprites.get(name).copied() else { return; }; let m = frame(angle); let corners = [(-size, -size), (size, -size), (size, size), (-size, size)]; - let uv = [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]]; + // buildCelestialQuad (sun) vs buildMoonPhases: the moon's UVs run + // the other way round. + let uv = if moon { + [[r.u1, r.v1], [r.u0, r.v1], [r.u0, r.v0], [r.u1, r.v0]] + } else { + [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]] + }; for ((x, z), uv) in corners.iter().zip(uv) { let p = m.transform_point3(glam::Vec3::new(*x, 100.0, *z)); out.push(Vertex { @@ -8286,17 +8545,14 @@ impl Game<'_> { pos: p.to_array(), uv, layer: 2, - color, + color: body_color, light: 0, + + glint_uv: [0.0, 0.0], }); } }; - body( - "environment/celestial/sun", - sky.sun_angle, - 30.0, - 0xFFFF_FFFF, - ); + body("environment/celestial/sun", sky.sun_angle, 30.0, false); let phases = [ "full_moon", "waning_gibbous", @@ -8312,7 +8568,7 @@ impl Game<'_> { &format!("environment/celestial/moon/{phase}"), sky.moon_angle, 20.0, - 0xFFFF_FFFF, + true, ); // SkyRenderer.renderStars: the static star buffer on the same frame. let stars = @@ -8469,6 +8725,7 @@ impl Game<'_> { book.to_be_displayed.retain(|r| index.contains(r)); self.dim = dim; self.world_root = save_root.clone(); + self.world_flat = horizon_client::save::WorldGen::read(&save_root).is_some_and(|w| w.flat); self.block_ticks = Ticks::new(self.level.seed as i32); self.tick_chunks.clear(); self.clear_entities(); @@ -8487,6 +8744,7 @@ impl Game<'_> { self.spawn_spiral = Default::default(); self.player_spawn = None; self.creatures.reset_trader(); + self.creatures.cat_tick = 0; self.portals = Default::default(); self.experience = Experience { level: self.level.xp_level, @@ -8772,6 +9030,10 @@ impl Game<'_> { } self.lan_close(false); self.save_game()?; + if let Some(mut remote) = self.remote.take() { + // Minecraft.disconnect closes the connection, so the host sees a clean leave. + remote.session.disconnect(); + } self.saved_for_exit = true; Ok(()) } @@ -9053,6 +9315,9 @@ impl Game<'_> { if result.outcome == Outcome::Pass { return Ok(false); } + if let Some(stat) = result.stat { + self.stats.custom(stat, 1); + } if let Some(block) = result.block && let Ok(new) = registry.resolve(&block) { @@ -9162,6 +9427,8 @@ impl Game<'_> { else { return Ok(false); }; + // BlockTransformer.transformBlock: ITEM_USED_ON_BLOCK before the swap. + self.trigger_block("minecraft:item_used_on_block", pos, stack); self.level_set(pos, new)?; // BlockTransformer.TransformParticle.send. self.transform_particle(&particle, pos); @@ -9434,6 +9701,8 @@ impl Game<'_> { if let Some(waxed) = old.and_then(|old| self.res.transformers().waxed(registry, &old)) && let Ok(state) = registry.resolve(&waxed) { + // HoneycombItem.useOn: ITEM_USED_ON_BLOCK before the swap. + self.trigger_block("minecraft:item_used_on_block", hit.pos, stack); self.level_set(hit.pos, state)?; self.level_event_at(3003, hit.pos, 0); self.audio.play( @@ -10152,40 +10421,7 @@ impl Game<'_> { if self.flash > 0 { self.flash -= 1; } - let (rain, _) = self.world.weather.levels(1.0); - let Some(eye) = self.eye_position() else { - return; - }; - // WeatherEffectRenderer.tickRainParticles: occasional rain sounds. - if rain > 0.0 && self.world.random.next_int_bound(3).unwrap_or(1) < (rain * 3.0) as i32 { - let r = &mut self.world.random; - let (dx, dz) = ( - r.next_int_bound(21).unwrap_or(10) - 10, - r.next_int_bound(21).unwrap_or(10) - 10, - ); - let (x, z) = (eye[0].floor() as i32 + dx, eye[2].floor() as i32 + dz); - let top = self.rain_height(x, z); - if self.precipitation(x, top, z) == Some(false) - && (top - eye[1] as i32).abs() < 10 - && self.world.random.next_int_bound(5).unwrap_or(1) == 0 - { - let above = f64::from(top) > eye[1] + 1.0; - let (name, volume, pitch) = if above { - ("minecraft:weather.rain.above", 0.1, 0.5) - } else { - ("minecraft:weather.rain", 0.2, 1.0) - }; - // The Horizon Weather option off silences the rain too. - if self.settings.horizon.weather { - self.audio.play( - name, - Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]), - volume, - pitch, - ); - } - } - } + // The rain sounds come with the rain splashes (`tick_particles`). } /// WeatherEffectRenderer: rain and snow columns within the weather radius. fn weather_geometry( @@ -10267,11 +10503,29 @@ impl Game<'_> { rain.extend(snow_vertices); rain } + /// A translated message for the player the game acts for: `overlay` is + /// `sendOverlayMessage` (the action bar), else `sendSystemMessage` (chat). + /// A guest gets a packet, so its own client translates it. + fn tell_sleeper(&mut self, key: &str, fallback: &str, overlay: bool) { + if self.lan_acting.is_some() { + self.guest_packets + .push(horizon_protocol::packets::play::Clientbound::SystemChat( + horizon_protocol::packets::play::SystemChat { + content: horizon_protocol::text::translatable(key, &[]), + overlay, + }, + )); + } else if overlay { + self.message = Some((self.translate(key, fallback), Instant::now())); + } else { + self.system_message(horizon_client::text::Text::translate(key, &[])); + } + } /// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder, /// and (outside creative) no monsters within 8 blocks; the bed becomes the /// respawn point either way. fn try_sleep(&mut self, pos: [i32; 3]) { - let Some(p) = self.player.as_ref() else { + let Some((position, yaw)) = self.player.as_ref().map(|p| (p.position, p.yaw)) else { return; }; let time = self.world.day_time.rem_euclid(24000); @@ -10294,15 +10548,16 @@ impl Game<'_> { // ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks // sideways and 2 vertically of the head or the foot. let reachable = |bed: [i32; 3]| { - (p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0 - && (p.position.y - f64::from(bed[1])).abs() <= 2.0 - && (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0 + (position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0 + && (position.y - f64::from(bed[1])).abs() <= 2.0 + && (position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0 }; if !reachable(head) && !reachable(foot) { - self.message = Some(( - "You may not rest now; the bed is too far away".into(), - Instant::now(), - )); + self.tell_sleeper( + "block.minecraft.bed.too_far_away", + "You may not rest now; the bed is too far away", + true, + ); return; } // ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the @@ -10315,7 +10570,11 @@ impl Game<'_> { f.full_collision && f.solid_render }); if blocked { - self.message = Some(("This bed is obstructed".into(), Instant::now())); + self.tell_sleeper( + "block.minecraft.bed.obstructed", + "This bed is obstructed", + true, + ); return; } // In reach (bedInRange), day or night: setRespawnPosition( @@ -10324,9 +10583,16 @@ impl Game<'_> { // and finds where to stand up (findRespawnAndUseSpawnBlock). // Straw beds never set it (`straw_bed_rule`). if self.bed_sets_spawn(state) { - self.respawn_config = Some(respawn_anchor::RespawnConfig::wrapped( - self.dim, head, p.yaw, false, - )); + let config = respawn_anchor::RespawnConfig::wrapped(self.dim, head, yaw, false); + // ServerPlayer.setRespawnPosition: the chat message only when the + // point moved (`isSamePosition`). + let moved = self + .respawn_config + .is_none_or(|c| (c.dim, c.pos) != (config.dim, config.pos)); + self.respawn_config = Some(config); + if moved { + self.tell_sleeper("block.minecraft.set_spawn", "Respawn point set", false); + } // The fallback becomes the world spawn: a guest's is none of its // own, so it follows `setworldspawn`. self.spawn = if self.lan_acting.is_some() { @@ -10341,10 +10607,11 @@ impl Game<'_> { }; } if !night { - self.message = Some(( - "You can sleep only at night or during thunderstorms".into(), - Instant::now(), - )); + self.tell_sleeper( + "block.minecraft.bed.no_sleep", + "You can sleep only at night or during thunderstorms", + true, + ); return; } // Creative players skip the monster check (`!this.isCreative()`). @@ -10352,18 +10619,26 @@ impl Game<'_> { && self.mobs.iter().any(|m| { m.hostile() && m.alive() - && (m.position.x - p.position.x).abs() < 8.0 - && (m.position.y - p.position.y).abs() < 5.0 - && (m.position.z - p.position.z).abs() < 8.0 + && (m.position.x - position.x).abs() < 8.0 + && (m.position.y - position.y).abs() < 5.0 + && (m.position.z - position.z).abs() < 8.0 }); if monsters { - self.message = Some(( - "You may not rest now; there are monsters nearby".into(), - Instant::now(), - )); + self.tell_sleeper( + "block.minecraft.bed.not_safe", + "You may not rest now; there are monsters nearby", + true, + ); return; } - self.message = Some(("Respawn point set".into(), Instant::now())); + // ServerPlayer.startSleepInBed: a percentage above 100 cannot skip the night. + if self.ui.rules.int("players_sleeping_percentage") > 100 { + self.tell_sleeper( + "sleep.not_possible", + "No amount of rest can pass this night", + true, + ); + } self.stop_mining(); self.left = false; self.right = false; @@ -10386,7 +10661,9 @@ impl Game<'_> { fn tick_sleep(&mut self) { self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); if let Some(head) = self.sleeping { - if self.keys.contains(&KeyCode::ShiftLeft) + // Vanilla has no Shift wake-up: the chat screen's capitals must + // not get the sleeper up. + if (self.screen != Screen::Chat && self.keys.contains(&KeyCode::ShiftLeft)) || self .player .as_ref() @@ -10884,6 +11161,21 @@ impl Game<'_> { } return Ok(false); } + // A server pack's reload covers the frame with its progress + // (`LoadingOverlay`) until `tick_server_packs` applies it. + if let Some(reload) = &self.server_packs.reload { + if let Some(renderer) = &mut self.renderer { + let mut hud = HudBatch::new([renderer.config.width, renderer.config.height]); + horizon_client::level_loading::draw_progress( + &mut hud, + &self.gui.atlas, + reload.progress.line(), + reload.progress.fraction(), + ); + return renderer.render(&loading_frame(&hud)); + } + return Ok(false); + } let Some(size) = self .renderer .as_ref() @@ -10978,8 +11270,11 @@ impl Game<'_> { horizon_client::environment::apply_weather(&mut sky, rain, thunder); self.end_flash_sky(&mut sky, alpha); if self.flash > 0 && !self.settings.file.bool("hideLightningFlashes") { - // Lightning flash brightens the sky (LevelRenderer skyFlashTime). - sky.sky_color = [0.9, 0.9, 1.0]; + // ClientLevel's flash layer while skyFlashTime > 0: the sky colour + // moves 22% of the way to (0.8, 0.8, 1.0). + let flash = [0.8, 0.8, 1.0]; + sky.sky_color = + std::array::from_fn(|i| sky.sky_color[i] + (flash[i] - sky.sky_color[i]) * 0.22); sky.sky_light_factor = 1.0; } // FishingHookRenderer's line, then DebugRenderer: chunk borders and @@ -11093,6 +11388,7 @@ impl Game<'_> { let mut entities = std::mem::take(&mut self.entity_vertices); entities.clear(); self.see_through_vertices.clear(); + self.glowing_vertices.get_mut().clear(); if !title { entities = horizon_client::spans::time("entity_geometry", || { self.entity_geometry(camera, alpha, entities) @@ -11117,7 +11413,7 @@ impl Game<'_> { && self.potions.effects.get("blindness").is_none() { // Camera.doesMobEffectBlockSky: no sun, moon or stars. - self.celestial_geometry(&sky) + self.celestial_geometry(&sky, rain) } else if self.dim == Dim::End && self.settings.horizon.sky { (self.end_flash_geometry(), None) } else { @@ -11160,6 +11456,7 @@ impl Game<'_> { // map_patches any earlier leaves them a frame behind. hud.patches.append(&mut self.map_patches); let entity_spans = std::mem::take(self.entity_spans.get_mut()); + let glowing = std::mem::take(self.glowing_vertices.get_mut()); let frame = Frame { weather: &weather, weather_time: horizon_client::weather::Time::new(self.world.game_time, alpha as f32), @@ -11209,6 +11506,8 @@ impl Game<'_> { debug_lines_on_top: &debug_lines_on_top, debug_crosshair: &debug_crosshair, hud: &hud, + glint_alpha: self.settings.file.double("glintStrength") as f32, + glint_ticks: self.glint_ticks(), clouds: (!title && self.dim == Dim::Overworld && horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3])) @@ -11226,6 +11525,7 @@ impl Game<'_> { }), entities: &entities, entity_spans: &entity_spans, + glowing: &glowing, dynamic_lights: &self.dynamic_lights, lightning: horizon_client::gfx::lightning::Input { bolts: &bolts, @@ -11281,6 +11581,7 @@ impl Game<'_> { // Restore storage even when rendering fails (for example, a lost surface). self.entity_vertices = entities; *self.entity_spans.get_mut() = entity_spans; + *self.glowing_vertices.get_mut() = glowing; self.see_through_vertices = see_through; result } @@ -11538,7 +11839,7 @@ impl Game<'_> { | KeyCode::Digit9 if self.screen == Screen::Playing => { - self.selected = match key { + let slot = match key { KeyCode::Digit1 => 0, KeyCode::Digit2 => 1, KeyCode::Digit3 => 2, @@ -11549,6 +11850,15 @@ impl Game<'_> { KeyCode::Digit8 => 7, _ => 8, }; + // Minecraft.handleKeybinds: a creative player holding the load + // or save toolbar key loads or saves a toolbar instead (load + // first when both are held). + let load = self.mapped_key_down("key.loadToolbarActivator"); + if self.creative && (load || self.mapped_key_down("key.saveToolbarActivator")) { + self.hotbar_load_or_save(slot, load); + } else { + self.selected = slot; + } } _ => {} } @@ -11591,7 +11901,18 @@ impl Game<'_> { // Minecraft.pickBlockOrEntity -> the server's handlePickItemFromBlock: // the block's clone item, with its block entity's data on Ctrl in // creative, picked from the inventory (`pick_item`). - if let Some(hit) = self.pick() { + if let Some(entity) = self.pick_entity_hit() { + // handlePickItemFromEntity: the entity's pick result. + if let Some(stack) = entity.and_then(|id| self.entity_pick_result(id)) { + let infinite = self.creative; + horizon_client::pick_item::pick( + &mut self.inventory[..36], + &mut self.selected, + &stack, + infinite, + ); + } + } else if let Some(hit) = self.pick() { let include_data = self.creative && self.has_control_down(); if let Some(stack) = self.picked_stack(hit.pos, include_data) { let infinite = self.creative; @@ -11971,6 +12292,19 @@ impl ApplicationHandler for Game<'_> { { return; } + // The pack reload's progress overlay takes no input + // (`LoadingOverlay`): `start_pack_reload` released what was held. + if self.server_packs.reload.is_some() + && !matches!( + &event, + WindowEvent::CloseRequested + | WindowEvent::Focused(_) + | WindowEvent::Resized(_) + | WindowEvent::RedrawRequested + ) + { + return; + } if self.pending_save.is_some() { match event { WindowEvent::CloseRequested => { @@ -12145,6 +12479,11 @@ impl ApplicationHandler for Game<'_> { self.advancements_scroll(scaled(raw_x) as f32, d); } } + WindowEvent::MouseInput { state, button, .. } if self.link_prompt.is_some() => { + if state == ElementState::Pressed && button == MouseButton::Left { + self.link_prompt_click(); + } + } WindowEvent::MouseInput { state, button, .. } if self.server_packs.prompt.is_some() => { @@ -12374,6 +12713,13 @@ impl ApplicationHandler for Game<'_> { } } // ConfirmScreen.keyPressed: Escape answers no. + WindowEvent::KeyboardInput { event, .. } if self.link_prompt.is_some() => { + if event.state == ElementState::Pressed + && event.physical_key == PhysicalKey::Code(KeyCode::Escape) + { + self.answer_link_prompt(false); + } + } WindowEvent::KeyboardInput { event, .. } if self.server_packs.prompt.is_some() => { if event.state == ElementState::Pressed && event.physical_key == PhysicalKey::Code(KeyCode::Escape) @@ -12773,6 +13119,16 @@ impl ApplicationHandler for Game<'_> { } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if horizon_threads::stop_requests() > 0 + && self.pending_save.as_ref().is_none_or(|save| !save.quit) + { + // SIGTERM, SIGINT or SIGHUP: the shutdown hook's server halt, as a window close. + if let Err(error) = self.begin_closing_save(true) { + self.error = Some(error); + event_loop.exit(); + return; + } + } if self.pending_save.is_some() { match self.poll_closing_save() { Ok(true) => event_loop.exit(), @@ -12897,6 +13253,7 @@ impl<'a> Game<'a> { world_loader: None, pending_pack_reload: false, server_packs: Default::default(), + link_prompt: None, dialogs: Default::default(), world_renderer_ready: false, collision: res.collision(), @@ -12973,6 +13330,7 @@ impl<'a> Game<'a> { luminance: None, see_through_vertices: Vec::new(), entity_spans: Default::default(), + glowing_vertices: Default::default(), pack_ids: None, health_hud: hud_layout::HealthHud::default(), started: now, @@ -13037,6 +13395,7 @@ impl<'a> Game<'a> { title: None, armor: [None, None, None, None], offhand: None, + hotbar_pop: [0; 10], hand: Hand::Main, shield_cooldown: 0, cooldowns: Default::default(), @@ -13063,11 +13422,13 @@ impl<'a> Game<'a> { dragging: false, avatar: Default::default(), flash: 0, + rain_sound_time: 0, lightning_seen: [0; 2], sleeping: None, sleep_timer: 0, dim: Dim::Overworld, world_root: PathBuf::new(), + world_flat: false, travelling: None, server_trips: Vec::new(), level_teleports: Vec::new(), @@ -13117,12 +13478,15 @@ impl<'a> Game<'a> { dragon_model: prepared.dragon_model, map_patches: Vec::new(), text_displays: Default::default(), + remote_knots: Default::default(), + knot_ids: Default::default(), text_display_vertices: 0, skin_downloads: RefCell::new(horizon_client::skins::Downloader::new( std::env::current_dir() .unwrap_or_default() .join("assets/skins"), )), + skin_profiles: RefCell::new(horizon_client::skins::Resolver::new()), skin_slots: Vec::new(), trim_slots: Vec::new(), cart_models: prepared.cart_models, @@ -13205,7 +13569,7 @@ impl<'a> Game<'a> { admin_feedback: Vec::new(), console_broadcast: None, cmds: Default::default(), - ui: Default::default(), + ui: chat::UiState::new(), combat: Default::default(), guest_combat: Default::default(), mount: Default::default(), @@ -13468,7 +13832,6 @@ const NUMERIC_KEYS: [KeyCode; 11] = [ KeyCode::Numpad9, ]; -const STAGES: u32 = 10; const STAGE_LINES: [&str; 10] = [ "Loading menu", "Loading assets", @@ -13484,19 +13847,28 @@ const STAGE_LINES: [&str; 10] = [ /// The background loader's checkpoint, read by the loading screen each frame. #[derive(Clone)] -struct Progress(Arc); +struct Progress { + value: Arc, + lines: &'static [&'static str], +} impl Progress { fn new() -> Self { - Self(Arc::new(AtomicU32::new(0))) + Self::with(&STAGE_LINES) + } + fn with(lines: &'static [&'static str]) -> Self { + Self { + value: Arc::new(AtomicU32::new(0)), + lines, + } } fn set(&self, stage: u32) { - self.0.store(stage, Ordering::Relaxed); + self.value.store(stage, Ordering::Relaxed); } fn fraction(&self) -> f32 { - self.0.load(Ordering::Relaxed) as f32 / (STAGES - 1) as f32 + self.value.load(Ordering::Relaxed) as f32 / (self.lines.len() - 1) as f32 } fn line(&self) -> &'static str { - STAGE_LINES[(self.0.load(Ordering::Relaxed) as usize).min(STAGE_LINES.len() - 1)] + self.lines[(self.value.load(Ordering::Relaxed) as usize).min(self.lines.len() - 1)] } } @@ -13856,6 +14228,12 @@ fn build_renderer( &assets.sprite_mips, &assets.animations, (&atlas.pixels, atlas.width, atlas.height), + (&atlas.glint.0, atlas.glint.1, atlas.glint.2), + ( + &atlas.glint_armor.0, + atlas.glint_armor.1, + atlas.glint_armor.2, + ), (&pack.forcefield.2, pack.forcefield.0), &gui.panorama, prepared, @@ -13882,6 +14260,7 @@ fn loading_renderer( ) -> Result { static FORCEFIELD: [u8; 4] = [0; 4]; static EMPTY_HUD: [u8; 4] = [0, 0, 0, 255]; + static EMPTY_GLINT: [u8; 4] = [0; 4]; let empty_panorama = horizon_client::gfx::panorama::Faces { size: 1, pixels: [0u8; 4].repeat(6), @@ -13892,6 +14271,10 @@ fn loading_renderer( Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height), None => (EMPTY_HUD.as_slice(), 1, 1), }; + let (glint_pixels, glint_width, glint_height) = match atlas { + Some(atlas) => (atlas.glint.0.as_slice(), atlas.glint.1, atlas.glint.2), + None => (EMPTY_GLINT.as_slice(), 1, 1), + }; // A glyph rasterized into an earlier texture is not in these pixels; the // new texture gets it again when the character is drawn (see // `build_renderer`). @@ -13908,6 +14291,8 @@ fn loading_renderer( &[], &[], (pixels, width, height), + (glint_pixels, glint_width, glint_height), + (glint_pixels, glint_width, glint_height), (&FORCEFIELD[..], 1), panorama, None, @@ -13955,9 +14340,12 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { debug_lines_on_top: &[], debug_crosshair: &[], hud, + glint_alpha: 0.75, + glint_ticks: 0.0, nether_lighting: false, entities: &[], entity_spans: &[], + glowing: &[], dynamic_lights: &[], clouds: None, lightning: Default::default(), @@ -14263,6 +14651,11 @@ impl Loading { } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if horizon_threads::stop_requests() > 0 { + // No world is open yet: nothing to save. + event_loop.exit(); + return; + } if let Err(error) = self.poll_menu_resources() { self.error = Some(error); event_loop.exit(); @@ -14540,6 +14933,9 @@ pub fn run() -> Result<()> { { horizon_client::heartbeat::start(); } + if options.execution_role.is_client() { + horizon_threads::catch_stop_signals(); + } let started = Instant::now(); horizon_client::spans::enable(options.spikes.is_some()); let vanilla_root = options.resources.clone(); diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 0f76d0ca9..b3a8977a1 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -9,6 +9,7 @@ use horizon_client::{ text::{self, Style, Text}, toasts::Slide, }; +use horizon_core::geometry::Vec3; use serde_json::Value; use std::{ collections::{BTreeMap, BTreeSet, VecDeque}, @@ -21,6 +22,9 @@ pub(super) struct Toast { frame: Frame, title: Text, slide: Slide, + /// `ToastInstance.firstSlotIndex`: the 32-pixel slot it stacks in once it + /// leaves the queue. + slot: Option, /// A `RecipeToast`: the crafting station and result of each display /// unlocked while it lasts (`recipeItems`); empty for an advancement. recipes: Vec<(String, ItemStack)>, @@ -36,6 +40,7 @@ impl Toast { frame: Frame::Task, title: Text::literal(""), slide: Slide::default(), + slot: None, recipes: items, changed: true, last_changed: 0, @@ -82,6 +87,8 @@ pub(super) struct AdvState { pub(super) quiet: bool, /// The inventory last seen by `inventory_changed`. pub(super) last_inventory: u64, + /// `ServerPlayer.levitationStartPos` and `levitationStartTime`. + pub(super) levitation: Option<([f64; 3], u64)>, /// While the game acts for a network player (`as_guest`): the /// advancements whose progress changed (`progressChanged`), the recipes /// unlocked and the announcements, for their client and everyone's. @@ -180,6 +187,14 @@ impl adv::World for View<'_, '_> { "block" => items.block_tags.get(tag).is_some_and(|t| t.contains(id)), "entity_type" => self.0.res.mob_data().entity_has(tag, id), "worldgen/biome" => self.0.res.mob_data().biome_has(tag, id), + "damage_type" => self + .0 + .res + .stations() + .enchantments + .damage_tags + .get(tag) + .is_some_and(|t| t.contains(id)), _ => false, } } @@ -524,6 +539,7 @@ impl Game<'_> { frame: d.frame, title: text_of(&d.title), slide: Slide::default(), + slot: None, recipes: Vec::new(), changed: false, last_changed: 0, @@ -647,6 +663,28 @@ impl Game<'_> { }; adv::conditions(&c["player"], &ctx, w) }); + // ServerPlayer.onEffectAdded and onEffectsRemoved keep the start of a + // levitation; tick fires LEVITATION while there is one. + let levitating = self + .potions + .effects + .list + .iter() + .any(|e| e.id == "levitation"); + match (levitating, self.adv.levitation) { + (true, None) => { + let at = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + self.adv.levitation = at.map(|at| (at, self.ticks)); + } + (false, Some(_)) => self.adv.levitation = None, + _ => {} + } + if let Some((start, since)) = self.adv.levitation { + self.trigger_levitation(start, (self.ticks - since) as i64); + } if self.ticks.is_multiple_of(20) { let me = self.player_entity(); self.trigger("minecraft:location", |c, w| { @@ -681,6 +719,136 @@ impl Game<'_> { adv::conditions(&c["player"], &pctx, w) && adv::conditions(&c[&key], &ectx, w) }); } + /// `KilledByArrowTrigger`: what the arrow killed and the weapon it came from. + pub(super) fn trigger_killed_by_arrow( + &mut self, + victims: &[EntityView], + weapon: Option<&ItemStack>, + ) { + let me = self.player_entity(); + let victims = victims.to_vec(); + let weapon = weapon.map(item_view); + self.trigger("minecraft:killed_by_arrow", move |c, w| { + adv::killed_by_arrow(c, &me, &victims, weapon.as_ref(), w) + }); + } + /// `LevitationTrigger`: how far the player rose from where it started + /// levitating, and for how long. + fn trigger_levitation(&mut self, start: [f64; 3], duration: i64) { + let me = self.player_entity(); + self.trigger("minecraft:levitation", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) + && (c["distance"].is_null() || adv::distance(&c["distance"], start, me.position)) + && adv::range_i(&c["duration"], duration) + }); + } + /// `ServerPlayer.updateUsingItem`: USING_ITEM for the item in use, with + /// what the player looks at (`PlayerPredicate.lookingAt`). + pub(super) fn trigger_using_item(&mut self, stack: &ItemStack) { + if self.remote.is_some() || self.no_player_here() { + return; + } + let mut me = self.player_entity(); + me.looking_at = self.looking_at_entity().map(Box::new); + let it = item_view(stack); + self.trigger("minecraft:using_item", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) && adv::item(&c["item"], &it, w) + }); + } + /// The mob a 100 block ray from the eyes meets first, if no block is in + /// the way (`ProjectileUtil.getEntityHitResult` and `hasLineOfSight`). + fn looking_at_entity(&self) -> Option { + let eye = self.eye_position()?; + let dir = super::view_vector(self.yaw, self.pitch); + let (m, _) = self + .mobs + .iter() + .filter(|m| m.alive()) + .filter_map(|m| Some((m, super::ray_box(eye, dir, 100.0, m.bounds())?))) + .min_by(|a, b| a.1.total_cmp(&b.1))?; + // `LivingEntity.hasLineOfSight`: eye to the target's eye height, + // `ClipContext.Block.COLLIDER`, no fluids, within 128 blocks. + let from = Vec3::new(eye[0], eye[1], eye[2]); + let to = Vec3::new(m.position.x, m.eye_y(), m.position.z); + let world = self.mob_world_base(&[]); + let clear = to.distance(from) <= 128.0 && world.clear_between(from, to, false); + clear.then(|| self.mob_entity(m)) + } + /// `PlayerHurtEntityTrigger`: the player, the damage and the victim. + pub(super) fn trigger_player_hurt_entity( + &mut self, + victim: &EntityView, + damage: &adv::DamageView, + ) { + let me = self.player_entity(); + let (victim, damage) = (victim.clone(), damage.clone()); + self.trigger("minecraft:player_hurt_entity", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + let vctx = adv::Entities { + this: Some(&victim), + ..pctx + }; + adv::conditions(&c["player"], &pctx, w) + && adv::damage(&c["damage"], &damage, w, me.position) + && adv::conditions(&c["entity"], &vctx, w) + }); + } + /// The player's hit on `victim` as `LivingEntity.hurtServer` reports it: + /// `kind` damage of `amount` from `direct` (the player's own hand when + /// `None`), nothing blocked. + pub(super) fn player_hit( + &mut self, + victim: &EntityView, + kind: &str, + direct: Option, + amount: f32, + ) { + let me = self.player_entity(); + self.trigger_player_hurt_entity( + victim, + &adv::DamageView { + kind: kind.to_owned(), + is_direct: direct.is_none(), + direct: direct.or_else(|| Some(me.clone())), + source: Some(me), + original: amount, + actual: amount, + blocked: false, + }, + ); + } + /// `EntityHurtPlayerTrigger`: the player and the damage it took. + pub(super) fn trigger_entity_hurt_player(&mut self, damage: &adv::DamageView) { + let me = self.player_entity(); + let damage = damage.clone(); + self.trigger("minecraft:entity_hurt_player", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) + && adv::damage(&c["damage"], &damage, w, me.position) + }); + } /// A player condition plus one item (`item` key). pub(super) fn trigger_item(&mut self, name: &str, stack: &ItemStack) { let me = self.player_entity(); @@ -708,6 +876,88 @@ impl Game<'_> { let it = item_view(stack); self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w)); } + /// `EnchantedItemTrigger`: the enchanted item and the levels it cost. + pub(super) fn trigger_enchanted_item(&mut self, stack: &ItemStack, levels: i32) { + let me = self.player_entity(); + let it = item_view(stack); + self.trigger("minecraft:enchanted_item", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) + && adv::item(&c["item"], &it, w) + && adv::range_i(&c["levels"], i64::from(levels)) + }); + } + /// `BrewedPotionTrigger`: the potion contents of a stack taken from a + /// brewing stand. + pub(super) fn trigger_brewed_potion(&mut self, stack: &ItemStack) { + let me = self.player_entity(); + let potion = stack.potion().map(str::to_owned); + self.trigger("minecraft:brewed_potion", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) + && adv::potions(&c["potion"], potion.as_deref(), w) + }); + } + /// `TradeTrigger`: the villager and the item the trade gave. + pub(super) fn trigger_trade(&mut self, villager: &EntityView, stack: &ItemStack) { + let me = self.player_entity(); + let villager = villager.clone(); + let it = item_view(stack); + self.trigger("minecraft:villager_trade", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + let vctx = adv::Entities { + this: Some(&villager), + ..pctx + }; + adv::conditions(&c["player"], &pctx, w) + && adv::conditions(&c["villager"], &vctx, w) + && adv::item(&c["item"], &it, w) + }); + } + /// `FishingRodHookedTrigger`: the rod, what the hook is in (or the hook) + /// and the items it caught. + pub(super) fn trigger_fishing_rod_hooked( + &mut self, + rod: &ItemStack, + hooked: &EntityView, + items: &[ItemStack], + ) { + let me = self.player_entity(); + let rod = item_view(rod); + let hooked = hooked.clone(); + let items: Vec = items.iter().map(item_view).collect(); + self.trigger("minecraft:fishing_rod_hooked", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + let ectx = adv::Entities { + this: Some(&hooked), + ..pctx + }; + adv::conditions(&c["player"], &pctx, w) + && adv::item(&c["rod"], &rod, w) + && adv::conditions(&c["entity"], &ectx, w) + && (c["item"].is_null() || items.iter().any(|i| adv::item(&c["item"], i, w))) + }); + } /// `EnterBlockTrigger`: the block, its state properties and the player. pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) { let Some(definition) = self.pack.assets.registry.state(state).cloned() else { @@ -806,58 +1056,105 @@ impl Game<'_> { c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to) }); } - /// `ToastManager` with the `AdvancementToast` and the `RecipeToast`, - /// one at a time. - pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) { + /// `ToastManager.SLOT_COUNT`. + pub(super) const TOAST_SLOTS: usize = 5; + /// `ToastManager.update` and `extractRenderState` for the `AdvancementToast`s and + /// `RecipeToast`s: up to five stack in 32-pixel slots, the rest queue. `hidden` (F1) + /// keeps them timing out without drawing them. + pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch, hidden: bool) { let multiplier = f64::from(self.settings.notification_display_time); - let Some(t) = self.adv.toasts.front_mut() else { - return; - }; - let first = t.slide.origin.is_none(); - let origin = *t.slide.origin.get_or_insert_with(Instant::now); - let now = origin.elapsed().as_millis() as i64; - let mut slide = std::mem::take(&mut t.slide); - let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier)); - t.slide = slide; - if finished { - self.adv.toasts.pop_front(); + let mut sound_played = false; + let mut i = 0; + while i < self.adv.toasts.len() { + let t = &mut self.adv.toasts[i]; + if t.slot.is_none() { + i += 1; + continue; + } + let origin = *t.slide.origin.get_or_insert_with(Instant::now); + let now = origin.elapsed().as_millis() as i64; + let mut slide = std::mem::take(&mut t.slide); + let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier)); + t.slide = slide; + if finished { + self.adv.toasts.remove(i); + continue; + } + // Only the first visibility change of an update plays its sound. + if let Some(show) = sound + && !std::mem::replace(&mut sound_played, true) + { + let event = if show { "ui.toast.in" } else { "ui.toast.out" }; + self.audio + .play(&format!("minecraft:{event}"), None, 1.0, 1.0); + } + i += 1; + } + // The queued toasts take the free slots in order; a challenge's own sound + // plays once as it leaves the queue. + let mut used = self.toast_slots_used(); + let mut challenge_sound = false; + for t in &mut self.adv.toasts { + if t.slot.is_some() { + continue; + } + let Some(slot) = (0..Self::TOAST_SLOTS).find(|s| used & (1 << s) == 0) else { + break; + }; + used |= 1 << slot; + t.slot = Some(slot); + challenge_sound |= !t.is_recipe() && t.frame == Frame::Challenge; + } + if challenge_sound { + self.audio + .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); + } + if hidden { return; } + for i in 0..self.adv.toasts.len() { + if let Some(slot) = self.adv.toasts[i].slot { + self.draw_toast(batch, i, 32.0 * slot as f32, multiplier); + } + } + } + /// The slots held by shown advancement, recipe and pack toasts, as bits. + pub(super) fn toast_slots_used(&self) -> u32 { + let packs = self.server_packs.toast_slots(); + self.adv + .toasts + .iter() + .filter_map(|t| t.slot) + .chain(packs) + .fold(0, |used, slot| used | 1 << slot) + } + /// The `AdvancementToast` or `RecipeToast` at `index` in its slot at `y`. + fn draw_toast(&mut self, batch: &mut HudBatch, index: usize, y: f32, multiplier: f64) { + let t = &self.adv.toasts[index]; let x = batch.width - 160.0 * t.slide.portion; let fully_for = t.slide.fully_for; let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone()); let recipe = t .is_recipe() .then(|| t.recipes[t.displayed_recipe(fully_for, multiplier)].clone()); - // ToastManager.update: the sound of the new visibility, and a - // challenge's own sound as it leaves the queue. - if let Some(show) = sound { - let event = if show { "ui.toast.in" } else { "ui.toast.out" }; - self.audio - .play(&format!("minecraft:{event}"), None, 1.0, 1.0); - } - if first && recipe.is_none() && frame == Frame::Challenge { - self.audio - .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); - } if let Some((station, item)) = recipe { // RecipeToast: black description under a purple title, the // station at 0.6 scale in the corner over the cycling result. let atlas = &self.gui.atlas; - batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0); + batch.sprite(atlas, "gui/sprites/toast/recipe", x, y); let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!"); let description = self.translate("recipe.toast.description", "Check your recipe book"); let atlas = &self.gui.atlas; - batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); - batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); + batch.text(atlas, &title, x + 30.0, y + 7.0, 0xFF50_0050, false); + batch.text(atlas, &description, x + 30.0, y + 18.0, 0xFF00_0000, false); let start = batch.vertices.len(); - self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, 3.0); - batch.scale_since(start, x, 0.0, 0.6, 0.6); - self.draw_item_model(batch, &item, x + 8.0, 8.0); + self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, y + 3.0); + batch.scale_since(start, x, y, 0.6, 0.6); + self.draw_item_model(batch, &item, x + 8.0, y + 8.0); return; } let atlas = &self.gui.atlas; - batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); + batch.sprite(atlas, "gui/sprites/toast/advancement", x, y); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), Frame::Goal => ("advancements.toast.goal", 0xFF00_FFFF), @@ -867,12 +1164,12 @@ impl Game<'_> { atlas, &Text::translate(key, &[]), x + 30.0, - 7.0, + y + 7.0, color, false, ); - batch.text_styled(atlas, &title, x + 30.0, 18.0, u32::MAX, false); - self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0); + batch.text_styled(atlas, &title, x + 30.0, y + 18.0, u32::MAX, false); + self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, y + 8.0); } } /// `Advancement.name`: the bracketed title in the frame's colour, with the @@ -1053,6 +1350,7 @@ impl Game<'_> { frame: d.frame, title: text_of(&d.title), slide: Slide::default(), + slot: None, recipes: Vec::new(), changed: false, last_changed: 0, diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index d99f32f24..4ab0a5189 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -568,6 +568,22 @@ impl Game<'_> { "generate_structures": options.structures, "bonus_chest": options.bonus_chest(), }), + Mode::CreateFlat { + name, + seed, + options, + flat, + .. + } => json!({ + "mode": "customize-flat", + "fields": { "name": name, "seed": seed }, + "superflat": options.flat, + "biome": flat.settings().biome, + "layers": flat.settings().layers.iter().map(|layer| json!({ + "block": layer.block, + "height": layer.height, + })).collect::>(), + }), Mode::Edit { world, name, diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index bed835663..ce9410ba5 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -131,7 +131,8 @@ impl Game<'_> { let m = &mut self.mobs[i]; m.extra.ints[1] -= 1; m.extra.ints[3] = 60; - self.spawn_item(ItemStack::new(&item, 1), from, v, 40); + // ItemEntity.setDefaultPickUpDelay. + self.spawn_item(ItemStack::new(&item, 1), from, v, 10); if self.world.game_time % 7 == 0 && self.world.random.next_double() < 0.9 { const PITCHES: [f32; 16] = [ 0.5625, 0.625, 0.75, 0.9375, 1.0, 1.0, 1.125, 1.25, 1.5, 1.875, 2.0, 2.25, 2.5, @@ -160,7 +161,7 @@ impl Game<'_> { } // Allay.duplicateAllay: entity event 18, three spawnHeartParticle. let id = self.mobs[index].id; - self.particles_around_mob(id, "heart", horizon_client::particles::Burst::ALLAY); + self.mob_event_particles(id, 18); self.audio .play("minecraft:block.amethyst_block.chime", Some(at), 2.0, 1.0); self.consume_held(); diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 9a8c846c5..4c0bd32e3 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -627,21 +627,8 @@ impl Game<'_> { * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)) * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0)); let mut poses = Poses::new(model); - // ArmorStand.DEFAULT_*_POSE and ArmorStandModel part visibility. - let deg = |v: f32| v.to_radians(); - for (name, rot) in [ - ("left_arm", [-10.0, 0.0, -10.0]), - ("right_arm", [-15.0, 0.0, 10.0]), - ("left_leg", [-1.0, 0.0, -1.0]), - ("right_leg", [1.0, 0.0, 1.0]), - ] { - if poses.has(name) { - let pose = poses.get(name); - pose[3] = deg(rot[0]); - pose[4] = deg(rot[1]); - pose[5] = deg(rot[2]); - } - } + // ArmorStandModel.setupAnim: the stand's pose and part visibility. + apply_pose(&mut poses, &a.pose); // Item layers pose from the hidden arms too (`visible` only skips drawing). let posed = poses.clone(); let mut hide = |name: &str| { @@ -711,7 +698,23 @@ impl Game<'_> { let color = undyed.map_or(0xFFFF_FFFF, |c| { 0xFF00_0000 | (c & 0xFF) << 16 | (c & 0xFF00) | (c >> 16) & 0xFF }); - let layer_poses = Poses::new(part); + // ArmorStandRenderer's HumanoidArmorLayer: the armour glint + // when `stack.hasFoil()`, as on a living entity. + let item_glint = self + .res + .items() + .enchantments + .props + .get(&stack.item) + .is_some_and(|p| p.glint); + let overlay = if stack.has_foil(item_glint) { + horizon_client::mobs::render::ARMOR_GLINT + } else { + 0 + }; + // ArmorStandArmorModel.setupAnim: the same pose as the stand. + let mut layer_poses = Poses::new(part); + apply_pose(&mut layer_poses, &a.pose); horizon_client::mobs::render::draw( part, base, @@ -719,7 +722,7 @@ impl Game<'_> { uv, color, packed, - 0, + overlay, out, ); // EquipmentLayerRenderer: the trim layer over the armour. @@ -734,7 +737,7 @@ impl Game<'_> { trim, 0xFFFF_FFFF, packed, - 0, + overlay, out, ); } @@ -743,6 +746,33 @@ impl Game<'_> { } } } +/// The `Pose` rotations on the parts of an armor stand model or its armor +/// (`ArmorStandArmorModel.setupAnim`); the body also turns the sticks. +fn apply_pose(poses: &mut Poses, pose: &[[f32; 3]; 6]) { + let parts: [&[&str]; 6] = [ + &["head"], + &[ + "body", + "right_body_stick", + "left_body_stick", + "shoulder_stick", + ], + &["left_arm"], + &["right_arm"], + &["left_leg"], + &["right_leg"], + ]; + for (names, rotation) in parts.into_iter().zip(pose) { + for name in names { + if poses.has(name) { + let part = poses.get(name); + part[3] = rotation[0].to_radians(); + part[4] = rotation[1].to_radians(); + part[5] = rotation[2].to_radians(); + } + } + } +} fn overlaps(a: Aabb, b: Aabb) -> bool { let (a0, a1, b0, b1) = ( a.min_position(), @@ -877,6 +907,7 @@ impl Game<'_> { lights: Some(horizon_client::block_entity_render::diffuse_lights( self.dim == super::Dim::Nether, )), + glint: self.glint(), }; let profile = stack .extra diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index b7f7efb1a..e17a8f6a3 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -3,8 +3,10 @@ //! player breaks the hive or fire reaches it. use super::Game; use horizon_client::{ + Result, beehive::{self, Beehive, HiveHost, Release}, containers::BlockEntity, + items::ItemStack, mobs::{Mob, Who, bee}, }; use horizon_core::{ @@ -194,19 +196,139 @@ impl Game<'_> { } self.anger_nearby_bees(at); } + /// `BeehiveBlock.useItemOn` with `held` in the acting hand: shears take + /// the honeycombs and a glass bottle a honey bottle from a full hive + /// (honey level 5), then the honey level resets and, unless a campfire + /// smokes the hive, the bees come out angry. True when it took the click. + pub(super) fn use_beehive(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> Result { + let Some(held) = held else { return Ok(false) }; + let shears = &*held.item == "minecraft:shears"; + if !shears && &*held.item != "minecraft:glass_bottle" { + return Ok(false); + } + let state = self.world.block(pos[0], pos[1], pos[2]); + if !matches!( + &*self.res.facts().get(state).name, + "minecraft:beehive" | "minecraft:bee_nest" + ) { + return Ok(false); + } + let prop = |key: &str| { + self.pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get(key).cloned()) + }; + if prop("honey_level").and_then(|v| v.parse::().ok()) != Some(5) { + return Ok(false); + } + let facing = beehive::facing_step(prop("facing").as_deref()); + let at = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + if shears { + // dropHoneycomb (harvest/beehive), the shear sound, hurtAndBreak. + for stack in self.sequence_loot( + "minecraft:harvest/beehive", + "minecraft:harvest/beehive", + Some(held), + ) { + self.pop_resource(pos, stack); + } + self.audio + .play("minecraft:block.beehive.shear", at, 1.0, 1.0); + self.damage_held(1); + self.post_block_game_event("minecraft:shear", pos, self.sculk_actor(), None); + } else { + // shrink(1), then the honey bottle in the hand, the inventory or + // on the ground. + self.audio.play("minecraft:item.bottle.fill", at, 1.0, 1.0); + let cell = self.held_mut(); + if let Some(s) = cell.as_mut() { + s.count -= 1; + if s.count == 0 { + *cell = None; + } + } + let bottle = ItemStack::new("minecraft:honey_bottle", 1); + if self.held().is_none() { + *self.held_mut() = Some(bottle); + } else if let Some(rest) = self.give(bottle) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + } + self.post_block_game_event("minecraft:fluid_pickup", pos, self.sculk_actor(), None); + } + self.stats.add("used", &held.item, 1); + let smokey = beehive::smokey(&self.mob_world_base(&[]), pos); + let key = (pos[0], pos[1], pos[2]); + if !smokey + && matches!(self.world.block_entities.get(&key), Some(BlockEntity::Beehive(h)) if !h.bees.is_empty()) + { + self.anger_nearby_bees(pos); + } + // resetHoneyLevel. + if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { + self.level_set(pos, reset)?; + } + if !smokey + && let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) + { + // emptyAllLivingFromHive: the bees within 4 blocks of the player + // go for them. + let released = hive.release_all( + pos, + facing, + None, + Release::Emergency, + &mut GameHive { game: self }, + ); + self.world + .block_entities + .put(key, BlockEntity::Beehive(hive)); + if let Some(p) = self.player_view().map(|p| p.position) { + for m in self.mobs.iter_mut().filter(|m| released.contains(&m.id)) { + if m.distance_sqr(p) <= 16.0 { + m.ai.target = Some(Who::Player); + } + } + } + } + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, held); + Ok(true) + } /// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down) - /// without a target go for a player in the same box. - fn anger_nearby_bees(&mut self, at: [i32; 3]) { + /// without a target go for a random player in the same box, the window's + /// own or a guest (`None` is the window's player). + pub(super) fn anger_nearby_bees(&mut self, at: [i32; 3]) { let min = Vec3::new( f64::from(at[0]) - 8.0, f64::from(at[1]) - 6.0, f64::from(at[2]) - 8.0, ); let area = Aabb::new(min, Vec3::new(min.x + 17.0, min.y + 13.0, min.z + 17.0)); - if !self + let mut players: Vec> = Vec::new(); + if self .player_view() .is_some_and(|p| p.bounds.intersects(area)) { + players.push(None); + } + if let Some(host) = self.lan.as_ref() { + players.extend( + host.hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .filter(|g| super::lan_mobs::guest_bounds(g).intersects(area)) + .map(|g| Some(g.conn)), + ); + } + if players.is_empty() { return; } let mut bees: Vec = (0..self.mobs.len()) @@ -219,9 +341,20 @@ impl Game<'_> { .collect(); bees.retain(|&i| self.mobs[i].ai.target.is_none()); for i in bees { - // Util.getRandom over the one player. - let _ = self.world.random.next_int_bound(1); + // Util.getRandom over the players. + let pick = self + .world + .random + .next_int_bound(players.len() as i32) + .unwrap_or(0) as usize; self.mobs[i].ai.target = Some(Who::Player); + // The player a mob sees is its guest binding, else the window's. + if let Some(host) = self.lan.as_mut() { + match players[pick] { + Some(conn) => host.mob_players.insert(self.mobs[i].id, conn), + None => host.mob_players.remove(&self.mobs[i].id), + }; + } } } } diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 7790a48f3..2705d8388 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -76,23 +76,24 @@ impl Game<'_> { /// A player opened (`open`) or closed the container at `key`: the opener /// count block event (`ContainerOpenersCounter` / `ShulkerBoxBlockEntity` /// `startOpen`/`stopOpen`) for chests, ender chests and shulker boxes, - /// on both halves of a double chest (`CompoundContainer`). - pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) { + /// on both halves of a double chest (`CompoundContainer`). True when the + /// count went from 0 to 1 or back to 0: the only moments the container + /// plays its open or close sound. + pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) -> bool { // Spectators never count as openers. - if !self.spectator() { - self.container_openers_changed(key, open); - } + !self.spectator() && self.container_openers_changed(key, open) } /// `container_opener_event` for a player who is not a spectator (a guest). - pub(super) fn container_openers_changed(&mut self, key: (i32, i32, i32), open: bool) { + pub(super) fn container_openers_changed(&mut self, key: (i32, i32, i32), open: bool) -> bool { let pos = [key.0, key.1, key.2]; let state = self.world.block(pos[0], pos[1], pos[2]).0; match self.be_anims.ticker(state) { Some(Ticker::Lid) => { - self.lid_openers_changed(key, open); + let edge = self.lid_openers_changed(key, open); if let Some(other) = self.chest_other_half(key) { self.lid_openers_changed(other, open); } + edge } _ if self .res @@ -102,26 +103,27 @@ impl Game<'_> { .as_ref() == "minecraft:barrel" => { - self.barrel_openers_changed(key, open); + self.barrel_openers_changed(key, open) } Some(Ticker::Shulker { .. }) => { let shulker = self.be_anims.shulkers.entry(pos).or_default(); - let (count, _) = if open { + let (count, edge) = if open { shulker.start_open() } else { shulker.stop_open() }; self.block_entity_event(pos, 1, count); self.lan_block_event(pos, 1, count); + edge } - _ => {} + _ => false, } } /// `ContainerOpenersCounter.incrementOpeners` / `decrementOpeners` of the /// chest at `key` (the host and the guests are counted), then /// `ChestBlockEntity.signalOpenCount`: block event 1 with the count, here - /// and for the guests. - fn lid_openers_changed(&mut self, key: (i32, i32, i32), open: bool) { + /// and for the guests. True when the count crossed zero. + fn lid_openers_changed(&mut self, key: (i32, i32, i32), open: bool) -> bool { let (before, count) = self.count_opener(key, open); let pos = [key.0, key.1, key.2]; self.block_entity_event(pos, 1, count); @@ -139,12 +141,15 @@ impl Game<'_> { b.update_neighbors_at(level, ticks, p.offset(0, -1, 0), block); }); } + (before == 0) != (count == 0) } /// `BarrelBlockEntity.openersCounter`: the first opener opens the barrel /// (`open=true`), the last one to leave closes it (`updateBlockState`). - fn barrel_openers_changed(&mut self, key: (i32, i32, i32), open: bool) { + /// True when the count crossed zero. + fn barrel_openers_changed(&mut self, key: (i32, i32, i32), open: bool) -> bool { let (before, count) = self.count_opener(key, open); - if (before == 0) != (count == 0) { + let edge = (before == 0) != (count == 0); + if edge { self.set_bool_prop( key, "open", @@ -152,6 +157,7 @@ impl Game<'_> { horizon_world::level::flags::UPDATE_ALL, ); } + edge } /// One opener more (`open`) or less at `key`: the count before and after /// (`ContainerOpenersCounter.incrementOpeners` / `decrementOpeners`). @@ -725,21 +731,38 @@ impl Game<'_> { /// the player head at `pos`. The skin download is started here; while it /// is in flight (or when it cannot be got) the profile's default skin /// stands in. A head with no profile answers None: `SKIN_BY_TYPE`. - pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<&str> { + pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option { let Some(BlockEntity::Skull(skull)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) else { return None; }; let skin = skull.skin.as_ref()?; - if let Some((url, location)) = &skin.download { - self.skin_downloads - .borrow_mut() - .state(skins::Kind::Skin, url); - if self.gui.atlas.sprites.contains_key(location) { + // The texture a packed or resolved `textures` property fetches: the + // download of a static profile, or the one the services answer for a + // `Dynamic` (name- or id-only) profile. + let download = skin.download.clone().or_else(|| { + let key = skin.dynamic.as_ref()?; + let skins::Resolve::Done(Some(profile)) = self.skin_profiles.borrow_mut().state(key) + else { + return None; + }; + let (value, signature) = profile.textures()?; + let url = skins::unpack(&value, signature, &skins::TEXTURE_URIS).skin?; + let location = skins::skin_location(&skins::texture_hash(&url)?); + Some((url, location)) + }); + if let Some((url, location)) = download { + let mut downloads = self.skin_downloads.borrow_mut(); + if self.gui.atlas.sprites.contains_key(&location) { + let _ = downloads.state(skins::Kind::Skin, &url); return Some(location); } + // Its slot was evicted: offer the image again. + if downloads.state(skins::Kind::Skin, &url) == skins::Download::Ready { + downloads.again(&location); + } } - Some(skin.fallback) + Some(skin.fallback.to_owned()) } } diff --git a/crates/horizon-client/src/game/block_items.rs b/crates/horizon-client/src/game/block_items.rs index 199c39a78..d18715041 100644 --- a/crates/horizon-client/src/game/block_items.rs +++ b/crates/horizon-client/src/game/block_items.rs @@ -4,9 +4,13 @@ //! placed item gives its block entity. use super::Game; use horizon_client::{ - block_entity_item, block_entity_nbt, containers::BlockEntity, item_data, items::ItemStack, save, + Result, block_entity_item, block_entity_nbt, containers::BlockEntity, item_data, + items::ItemStack, save, +}; +use horizon_world::{ + nbt::{Compound, Tag}, + registry::BlockStateId, }; -use horizon_world::nbt::{Compound, Tag}; /// The component patch of `stack`. fn components(stack: &ItemStack) -> Compound { @@ -77,6 +81,42 @@ impl Game<'_> { Some(stack) } + /// `BlockItem.updateBlockStateFromTag`: the properties of the item's + /// `block_state` component (a hive's honey level, a statue's pose) set on + /// the block just placed at `pos`. Returns the state it has now. + pub(super) fn apply_item_block_state( + &mut self, + pos: [i32; 3], + state: BlockStateId, + stack: &ItemStack, + ) -> Result { + let Some(Tag::Compound(saved)) = + stack.data().and_then(|d| d.other("minecraft:block_state")) + else { + return Ok(state); + }; + let Some(current) = self.pack.assets.registry.state(state) else { + return Ok(state); + }; + // Only the properties the block has. + let props: Vec<(String, String)> = saved + .iter() + .filter_map(|(k, v)| match v { + Tag::String(v) => Some((k.to_string_lossy(), v.to_string_lossy())), + _ => None, + }) + .filter(|(k, v)| current.properties.get(k).is_some_and(|old| old != v)) + .collect(); + let props: Vec<(&str, &str)> = props.iter().map(|(k, v)| (&**k, &**v)).collect(); + match self.with_props(state, &props) { + Some(new) if !props.is_empty() && new != state => { + self.level_set(pos, new)?; + Ok(new) + } + _ => Ok(state), + } + } + /// `BlockItem.updateCustomBlockEntityTag` and `updateBlockEntityComponents` /// for the block entity just placed at `pos` from `stack`; `game_master`: /// the placer can use game master blocks (a dispenser can't). diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index b09803e49..07d65c5a4 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -8,7 +8,7 @@ use horizon_client::{ containers::{BlockEntity, Lectern}, first_person::Hand, hud::{HudBatch, rgba}, - item_data::WrittenBook, + item_data::{StackData, WrittenBook}, items::ItemStack, menu::{Kind, Menu}, text::Text, @@ -59,14 +59,86 @@ pub(super) enum BookScreen { page_edit: ui::EditBox, }, View { - pages: Vec, + pages: Vec, page: usize, lectern: Option<(i32, i32, i32)>, }, } +/// The pages a book screen reads: a written book's components (so their +/// click events stay), else a writable book's text. +fn view_pages(data: Option<&StackData>) -> Vec { + let Some(data) = data else { return Vec::new() }; + let Some(w) = &data.written else { + return data.writable_pages.iter().map(Text::literal).collect(); + }; + let tagged = w.page_tags.len() == w.pages.len(); + w.pages + .iter() + .enumerate() + .map(|(i, page)| match tagged.then(|| &w.page_tags[i]) { + Some(tag @ horizon_world::nbt::Tag::Compound(_)) => { + horizon_client::entity_nbt::name_text(tag) + } + _ => Text::literal(page), + }) + .collect() +} impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { - self.gui.atlas.font.split(&Text::literal(page), 114.0) + self.page_lines(&Text::literal(page)) + } + fn page_lines(&self, page: &Text) -> Vec { + self.gui.atlas.font.split(page, 114.0) + } + /// `BookViewScreen.mouseClicked`: the click event of the text under the + /// cursor on the page. + fn book_link_at(&self, page: &Text, left: f32) -> Option { + let (mx, my) = self.cursor; + let row = ((my - 32.0) / 9.0).floor(); + if row < 0.0 || row >= LINES as f32 { + return None; + } + let lines = self.page_lines(page); + let line = lines.get(row as usize)?.resolve_legacy(); + let mut x = mx - (left + 36.0); + if x < 0.0 { + return None; + } + for (c, style) in line.chars() { + x -= self.gui.atlas.font.advance(c, style); + if x < 0.0 { + return style.click.clone(); + } + } + None + } + /// `BookViewScreen.handleClickEvent`: a page link turns to its page + /// (`forcePage`), a web link goes through the confirm-link flow. + fn book_follow_link( + &mut self, + link: horizon_client::text::ClickEvent, + count: usize, + lectern: Option<(i32, i32, i32)>, + ) { + use horizon_client::text::ClickEvent; + match link { + ClickEvent::ChangePage(target) => { + let target = (target - 1).clamp(0, count.saturating_sub(1) as i32); + let Some(BookScreen::View { page, .. }) = self.book.as_mut() else { + return; + }; + if let Some(key) = lectern { + // LecternScreen.forcePage: the menu's button 100 + page. + if target != *page as i32 { + self.lectern_button(key, 100 + target); + } + } else if target != *page as i32 { + *page = target as usize; + } + } + ClickEvent::OpenUrl(url) => self.click_url(url), + _ => {} + } } /// `WritableBookItem.use` / `WrittenBookItem.use` (`Player.openItemGui`). /// A server's player writes in its own client's editor @@ -115,11 +187,7 @@ impl Game<'_> { } } "minecraft:written_book" => BookScreen::View { - pages: stack - .data() - .and_then(|d| d.written.as_ref()) - .map(|w| w.pages.clone()) - .unwrap_or_default(), + pages: view_pages(stack.data()), page: 0, lectern: None, }, @@ -215,6 +283,7 @@ impl Game<'_> { author, generation: 0, pages, + page_tags: Vec::new(), }); *stack = written; } else { @@ -685,11 +754,7 @@ impl Game<'_> { return false; }; let Some(book) = &l.book else { return false }; - let data = book.data(); - let pages = data - .and_then(|d| d.written.as_ref().map(|w| w.pages.clone())) - .or_else(|| data.map(|d| d.writable_pages.clone())) - .unwrap_or_default(); + let pages = view_pages(book.data()); let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1)); self.stats.custom("interact_with_lectern", 1); self.open_book(BookScreen::View { @@ -811,11 +876,7 @@ impl Game<'_> { page, }) = self.book.as_mut() { - let data = book.as_ref().and_then(ItemStack::data); - *pages = data - .and_then(|d| d.written.as_ref().map(|w| w.pages.clone())) - .or_else(|| data.map(|d| d.writable_pages.clone())) - .unwrap_or_default(); + *pages = view_pages(book.as_ref().and_then(ItemStack::data)); *page = (*page).min(pages.len().saturating_sub(1)); } } @@ -955,7 +1016,10 @@ impl Game<'_> { lectern, }) => { let (page, count, lectern) = (*page, pages.len(), *lectern); - if page + 1 < count && inside(left + 116.0, 159.0, 23.0, 13.0) { + // The text's click event first, then the buttons. + if let Some(link) = pages.get(page).and_then(|t| self.book_link_at(t, left)) { + self.book_follow_link(link, count, lectern); + } else if page + 1 < count && inside(left + 116.0, 159.0, 23.0, 13.0) { self.turn_page(true); } else if page > 0 && inside(left + 43.0, 159.0, 23.0, 13.0) { self.turn_page(false); @@ -1080,7 +1144,12 @@ impl Game<'_> { BLACK, ); } - let by = tr("book.byAuthor", "by %1$s").replace("%1$s", super::chat::PLAYER_NAME); + // BookSignScreen: `owner.getName()`, the account's name on a server. + let owner = self + .remote + .as_ref() + .map_or(super::chat::PLAYER_NAME, |r| r.profile_name.as_str()); + let by = tr("book.byAuthor", "by %1$s").replace("%1$s", owner); let tw = HudBatch::text_width(atlas, &by); batch.text( atlas, @@ -1198,7 +1267,7 @@ impl Game<'_> { } => { indicator(batch, *page, pages.len()); if let Some(text) = pages.get(*page) { - for (i, line) in self.book_lines(text).iter().take(LINES).enumerate() { + for (i, line) in self.page_lines(text).iter().take(LINES).enumerate() { batch.text_styled( atlas, line, diff --git a/crates/horizon-client/src/game/cat_spawner.rs b/crates/horizon-client/src/game/cat_spawner.rs new file mode 100644 index 000000000..539aae726 --- /dev/null +++ b/crates/horizon-client/src/game/cat_spawner.rs @@ -0,0 +1,138 @@ +//! `CatSpawner`: every 1200 ticks a cat may appear near a random player, +//! in a village with enough occupied beds or inside a swamp hut. +use super::{ + Dim, Game, + raids::{section, sections_to_village}, +}; +use horizon_client::mobs::{Species, spawn_rules}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +const TICK_DELAY: i32 = 1200; + +impl Game<'_> { + /// `CatSpawner.tick` (the overworld's custom spawner). + pub(super) fn tick_cat_spawner(&mut self) { + if self.dim != Dim::Overworld { + return; + } + self.creatures.cat_tick -= 1; + if self.creatures.cat_tick > 0 { + return; + } + self.creatures.cat_tick = TICK_DELAY; + // ServerLevel.getRandomPlayer: one of the living players. + let alive: Vec = self + .level_players() + .into_iter() + .filter(|p| p.alive) + .map(|p| p.position) + .collect(); + if alive.is_empty() { + return; + } + let pick = self + .world + .random + .next_int_bound(alive.len() as i32) + .unwrap_or(0); + let p = alive[pick as usize]; + let mut offset = || { + let n = 8 + self.world.random.next_int_bound(24).unwrap_or(0); + if self.world.random.next_boolean() { + -n + } else { + n + } + }; + let x = offset(); + let z = offset(); + let pos = [ + p.x.floor() as i32 + x, + p.y.floor() as i32, + p.z.floor() as i32 + z, + ]; + // hasChunksAt(pos +- 10) + let loaded = ((pos[0] - 10) >> 4..=(pos[0] + 10) >> 4).all(|cx| { + ((pos[2] - 10) >> 4..=(pos[2] + 10) >> 4) + .all(|cz| self.world.chunks.contains_key(&(cx, cz))) + }); + if !loaded { + return; + } + let ok = spawn_rules::is_spawn_position_ok( + Species::Cat, + &self.mob_world_base(&[]), + pos[0], + pos[1], + pos[2], + ); + if !ok { + return; + } + if sections_to_village(&self.village_centers(), section(pos)) <= 2 { + self.spawn_cat_in_village(pos); + } else { + let hut = self.structure_tag("minecraft:cats_spawn_in"); + if self.structures_at(pos).iter().any(|s| hut.contains(s)) { + self.spawn_cat_in_hut(pos); + } + } + } + /// `spawnInVillage`: more than four occupied beds within 48 blocks and + /// fewer than five cats around. + fn spawn_cat_in_village(&mut self, pos: [i32; 3]) { + // PoiManager.getCountInRange(HOME, IS_OCCUPIED): beds villagers have claimed. + let mut beds: Vec<[i32; 3]> = self + .mobs + .iter() + .filter(|m| m.species() == Species::Villager && m.alive()) + .filter_map(|m| m.extra.bed) + .filter(|b| { + let d = |i: usize| i64::from(b[i] - pos[i]); + d(0).abs() <= 48 + && d(2).abs() <= 48 + && d(0).pow(2) + d(1).pow(2) + d(2).pow(2) <= 48 * 48 + }) + .collect(); + beds.sort_unstable(); + beds.dedup(); + if beds.len() > 4 && self.cats_near(pos, 48.0) < 5 { + self.spawn_cat(pos, false); + } + } + /// `spawnInHut`: no cat within 16 blocks; the cat stays. + fn spawn_cat_in_hut(&mut self, pos: [i32; 3]) { + if self.cats_near(pos, 16.0) == 0 { + self.spawn_cat(pos, true); + } + } + /// Cats in `AABB(pos).inflate(radius, 8, radius)`. + fn cats_near(&self, pos: [i32; 3], radius: f64) -> usize { + let [x, y, z] = pos.map(f64::from); + let min = Vec3::new(x - radius, y - 8.0, z - radius); + let max = Vec3::new(x + 1.0 + radius, y + 9.0, z + 1.0 + radius); + self.mobs + .iter() + .filter(|m| { + m.species() == Species::Cat && m.alive() && m.bounds().intersects_corners(min, max) + }) + .count() + } + /// `spawnCat`: finalized for a natural spawn, black inside + /// `#cats_spawn_as_black` structures (`Cat.finalizeSpawn`). + fn spawn_cat(&mut self, pos: [i32; 3], persistent: bool) { + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + let Some(id) = self.spawn_mob("minecraft:cat", at, persistent) else { + return; + }; + let black = self.structure_tag("minecraft:cats_spawn_as_black"); + let in_black = self.structures_at(pos).iter().any(|s| black.contains(s)); + if in_black && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.extra.variant = 10; + } + } +} diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 94f7661b7..9fbc5cd88 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -81,6 +81,8 @@ pub struct UiState { pub chat_screen: Option, /// When the chat screen opened (its input took the focus: the cursor blink). pub chat_opened: Option, + /// The chat screen is `InBedChatScreen`: the sleeper's, with a Leave Bed button. + pub in_bed_chat: bool, pub registries: Registries, pub rules: GameRules, pub clock: WorldClock, @@ -106,6 +108,18 @@ pub struct UiState { pub death_time: u32, } +impl UiState { + /// The state a window starts with: the chat remembers the commands kept + /// in the game folder (`ChatComponent`'s constructor). + pub fn new() -> Self { + let mut ui = Self::default(); + if let Ok(dir) = std::env::current_dir() { + ui.chat.load_history(&dir); + } + ui + } +} + impl Game<'_> { /// `PlayerList.isOp` for the single-player owner: the world's Allow Commands. pub(super) fn allow_commands(&self) -> bool { @@ -440,6 +454,12 @@ impl Game<'_> { self.capture(false); } pub(super) fn close_chat(&mut self) { + // InBedChatScreen.onClose: leaving the screen means getting up; the + // screen goes once the player has woken (`tick_in_bed_chat`). + if self.ui.in_bed_chat && self.sleeping.is_some() { + self.wake_up(); + return; + } self.ui.chat_screen = None; self.ui.chat.reset_scroll(); if self.screen == Screen::Chat { @@ -447,6 +467,35 @@ impl Game<'_> { self.capture(true); } } + /// `Gui.tick`: a sleeper gets `InBedChatScreen`; when the player has + /// woken (`onPlayerWokeUp`) it closes, or turns into the plain chat + /// screen if something was typed. + pub(super) fn tick_in_bed_chat(&mut self) { + if self.screen != Screen::Chat { + self.ui.in_bed_chat = false; + } + if self.ui.in_bed_chat { + if self.sleeping.is_none() { + self.ui.in_bed_chat = false; + let text = self + .ui + .chat_screen + .as_ref() + .map_or_else(String::new, |s| s.value().to_owned()); + self.close_chat(); + if !text.is_empty() { + self.open_chat(&text); + } + } + } else if self.sleeping.is_some() && self.screen == Screen::Playing { + self.open_chat(""); + self.ui.in_bed_chat = self.screen == Screen::Chat; + } + } + /// The Leave Bed button of `InBedChatScreen`: its bounds. + fn leave_bed_button(width: f32, height: f32) -> (i32, i32, i32, i32) { + (width as i32 / 2 - 100, height as i32 - 40, 200, 20) + } /// `Minecraft.computeChatAbilities` from the Chat option. pub(super) fn chat_abilities(&self) -> ChatAbilities { ChatAbilities::new(ChatVisibility::from_option(self.settings.chat_visibility)) @@ -559,7 +608,15 @@ impl Game<'_> { match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) { ChatAction::Close => self.close_chat(), ChatAction::Submit(message) => { - self.close_chat(); + // InBedChatScreen sends without closing (`closeOnSubmit` is + // false): the box empties and the screen stays. + if self.ui.in_bed_chat && self.sleeping.is_some() { + screen.suggest_command(&m, &c, ""); + self.ui.chat.reset_scroll(); + self.ui.chat_screen = Some(screen); + } else { + self.close_chat(); + } if !message.is_empty() { self.handle_chat_input(&message); } @@ -661,7 +718,8 @@ impl Game<'_> { { return; } - let shift = self.keys.contains(&KeyCode::ShiftLeft); + // ChatScreen.mouseScrolled: `hasShiftDown`, either Shift key. + let shift = self.has_shift_down(); let amount = amount.clamp(-1.0, 1.0) * if shift { 1.0 } else { 7.0 }; self.ui.chat.scroll_by(amount as i32, true); } @@ -675,6 +733,16 @@ impl Game<'_> { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; + if self.ui.in_bed_chat && self.sleeping.is_some() { + let width = self.renderer.as_ref().map_or(1280.0, |r| { + HudBatch::new([r.config.width, r.config.height]).width + }); + let (x, y, w, h) = Self::leave_bed_button(width, height); + if horizon_client::screen_draw::inside((cursor.0 as i32, cursor.1 as i32), x, y, w, h) { + self.wake_up(); + return; + } + } if let Some(screen) = self.ui.chat_screen.as_mut() { if screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64) { return; @@ -695,12 +763,78 @@ impl Game<'_> { Some(ClickEvent::OpenFile(path)) => { super::packs::open_folder(std::path::Path::new(&path)); } + Some(ClickEvent::OpenUrl(url)) => self.click_url(url), Some(ClickEvent::SuggestCommand(command)) => { if let Some(screen) = self.ui.chat_screen.as_mut() { screen.suggest_command(&m, &c, &command); } } - None => {} + // Screen.defaultHandleClickEvent: a page link means nothing in chat. + Some(ClickEvent::ChangePage(_)) | None => {} + } + } + /// `Screen.clickUrlAction`: nothing with Web Links off, else the link + /// opens, after the confirmation unless Prompt on Links is off. + pub(super) fn click_url(&mut self, url: String) { + if !self.settings.chat_links { + return; + } + if self.settings.file.bool("chatLinksPrompt") { + self.link_prompt = Some(url); + } else { + super::packs::open_uri(&url); + } + } + /// `ConfirmLinkScreen` (untrusted): the link and its warning over the + /// chat, answered yes to open it. + fn link_prompt_layout( + &self, + url: &str, + size: (f32, f32), + ) -> horizon_client::confirm_screen::Confirm { + let warning = Text::translate("chat.link.warning", &[]).with_color(0xFF_CCCC); + let message = Text::literal(url) + .append(Text::literal("\n")) + .append(warning); + horizon_client::confirm_screen::Confirm::new( + &self.gui.atlas.font, + size, + &Text::translate("chat.link.confirm", &[]), + &message, + ) + } + pub(super) fn draw_link_prompt(&self, batch: &mut HudBatch) { + let Some(url) = &self.link_prompt else { + return; + }; + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + horizon_client::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let (yes, no) = ( + Text::translate("gui.yes", &[]), + Text::translate("gui.no", &[]), + ); + self.link_prompt_layout(url, (w, h)) + .draw(batch, atlas, self.cursor, [&yes, &no]); + } + /// The prompt's answer: the link opens on yes; either way the chat is back. + pub(super) fn answer_link_prompt(&mut self, yes: bool) { + if let Some(url) = self.link_prompt.take() + && yes + { + super::packs::open_uri(&url); + } + } + pub(super) fn link_prompt_click(&mut self) { + let Some(url) = &self.link_prompt else { + return; + }; + let answer = self + .link_prompt_layout(url, self.gui_size()) + .answer_at(self.cursor); + if let Some(yes) = answer { + self.audio.play_button_click(); + self.answer_link_prompt(yes); } } /// Chat lines over the HUD (focused while the chat screen is open). @@ -737,6 +871,26 @@ impl Game<'_> { let draws = screen.draw(&m, mouse, blink, background); horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); + if self.ui.in_bed_chat && self.sleeping.is_some() { + let (x, y, w, h) = Self::leave_bed_button(batch.width, batch.height); + let label = Text::literal(horizon_client::lang::get_or( + "multiplayer.stopSleeping", + "Leave Bed", + )); + let mut button = Vec::new(); + horizon_client::screen_draw::button( + &mut button, + &m, + &label, + x, + y, + w, + h, + true, + horizon_client::screen_draw::inside(mouse, x, y, w, h), + ); + horizon_client::screen_draw::paint(batch, &self.gui.atlas, &button); + } // The hovered message part's tooltip, one row per line of its text. if let Some(hover) = self.ui.chat.hover_at( &self.gui.atlas.font, @@ -789,6 +943,11 @@ impl Game<'_> { pub(super) fn sync_rules(&mut self) { self.world.health_rules.natural_regeneration = self.ui.rules.bool("natural_health_regeneration"); + // Player.isInvulnerableTo: the damage-type rules. + self.world.health_rules.drowning_damage = self.ui.rules.bool("drowning_damage"); + self.world.health_rules.fall_damage = self.ui.rules.bool("fall_damage"); + self.world.health_rules.fire_damage = self.ui.rules.bool("fire_damage"); + self.world.health_rules.freeze_damage = self.ui.rules.bool("freeze_damage"); use horizon_world::food::Difficulty; self.world.health_rules.difficulty = match self.ui.difficulty { 0 => Difficulty::Peaceful, diff --git a/crates/horizon-client/src/game/chiseled_bookshelf.rs b/crates/horizon-client/src/game/chiseled_bookshelf.rs new file mode 100644 index 000000000..5d383b4ea --- /dev/null +++ b/crates/horizon-client/src/game/chiseled_bookshelf.rs @@ -0,0 +1,178 @@ +//! Chiseled bookshelves: `ChiseledBookShelfBlock.useItemOn` / `useWithoutItem` +//! (a book into the slot under the crosshair, or out of it) and +//! `ChiseledBookShelfBlockEntity.updateState`, which also follows the books a +//! hopper or dropper moved (`machines::container_changed`). The slots' books +//! show through the block state's `slot_N_occupied`, which reaches a server's +//! clients with the block update. +use super::{Game, Hit, machines::dir_from_name}; +use horizon_client::{containers::BlockEntity, items::ItemStack, mobs::Who}; +use horizon_core::{ + geometry::{Direction, Vec3}, + position::BlockPos, +}; +use horizon_world::level::{flags, hit_slot}; + +const BLOCK: &str = "minecraft:chiseled_bookshelf"; + +impl Game<'_> { + /// `useItemOn` with `held` in the acting hand, then `useWithoutItem` on + /// the main hand's turn: None when the block passes the click, else + /// whether the use succeeded and the arm swings (a click on an empty slot + /// without a book only consumes it). + pub(super) fn use_chiseled_bookshelf( + &mut self, + hit: &Hit, + held: Option<&ItemStack>, + ) -> Option { + let pos = hit.pos; + let state = self.world.block(pos[0], pos[1], pos[2]); + let info = self + .pack + .assets + .registry + .state(state) + .filter(|s| s.name == BLOCK)?; + let facing = info + .properties + .get("facing") + .and_then(|f| dir_from_name(f))?; + let face = Direction::ALL + .into_iter() + .find(|d| d.normal() == hit.face)?; + let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); + let slot = hit_slot( + facing, + face, + BlockPos::new(pos[0], pos[1], pos[2]), + at, + 2, + 3, + )?; + let occupied = info + .properties + .get(&format!("slot_{slot}_occupied")) + .map(String::as_str) + == Some("true"); + let book = held.filter(|s| { + self.res + .items() + .item_tags + .get("minecraft:bookshelf_books") + .is_some_and(|m| m.contains(&*s.item)) + }); + let centre = pos.map(|v| f64::from(v) + 0.5); + if let Some(book) = book + && !occupied + { + // addBook: one book goes in (a creative player keeps theirs). + let book = book.clone(); + self.stats.add("used", &book.item, 1); + let sound = if &*book.item == "minecraft:enchanted_book" { + "minecraft:block.chiseled_bookshelf.insert.enchanted" + } else { + "minecraft:block.chiseled_bookshelf.insert" + }; + self.bookshelf_items(pos)?[slot] = Some(ItemStack { + count: 1, + ..book.clone() + }); + self.consume_held(); + self.chiseled_bookshelf_update_state(pos, slot); + self.audio.play(sound, Some(centre), 1.0, 1.0); + self.trigger_block("minecraft:item_used_on_block", pos, &book); + return Some(true); + } + // TRY_WITH_EMPTY_HAND: only the main hand goes on to useWithoutItem. + if self.hand != horizon_client::first_person::Hand::Main { + return None; + } + if !occupied { + return Some(false); + } + // removeBook: the book goes to the inventory, or is dropped. + let retrieved = self.bookshelf_items(pos)?[slot].take()?; + self.chiseled_bookshelf_update_state(pos, slot); + let sound = if &*retrieved.item == "minecraft:enchanted_book" { + "minecraft:block.chiseled_bookshelf.pickup.enchanted" + } else { + "minecraft:block.chiseled_bookshelf.pickup" + }; + self.audio.play(sound, Some(centre), 1.0, 1.0); + self.give_or_drop(retrieved); + self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None); + Some(true) + } + + /// The bookshelf's six slots (made if the block has no block entity yet). + fn bookshelf_items(&mut self, pos: [i32; 3]) -> Option<&mut [Option; 6]> { + let entity = self + .world + .block_entities + .get_or_insert_with((pos[0], pos[1], pos[2]), || { + BlockEntity::ChiseledBookshelf(Box::default()) + }); + match entity { + BlockEntity::ChiseledBookshelf(b) => Some(&mut b.items), + _ => None, + } + } + + /// `ChiseledBookShelfBlockEntity.updateState`: `slot` becomes the last + /// one touched, the block state takes the slots' occupancy + /// (`setBlockAndUpdate`) and `BLOCK_CHANGE` goes out. + fn chiseled_bookshelf_update_state(&mut self, pos: [i32; 3], slot: usize) { + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get_mut(&key) + else { + return; + }; + b.last_slot = slot as i32; + let occupied: Vec = b.items.iter().map(Option::is_some).collect(); + let registry = self.pack.assets.registry; + let Some(mut state) = registry + .state(self.world.block(pos[0], pos[1], pos[2])) + .cloned() + else { + return; + }; + for (i, occupied) in occupied.into_iter().enumerate() { + state + .properties + .insert(format!("slot_{i}_occupied"), occupied.to_string()); + } + let Some(new) = registry.id(&state) else { + return; + }; + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.set_block(level, ticks, at, new, flags::UPDATE_ALL)); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + self.post_block_game_event("minecraft:block_change", pos, None, Some(new)); + } + + /// The books a hopper or dropper put in or took out: the slot whose + /// occupancy no longer matches the block state is the one `setItem` or + /// `removeItem` updated. + pub(super) fn chiseled_bookshelf_synced(&mut self, pos: (i32, i32, i32)) { + let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get(&pos) else { + return; + }; + let Some(info) = self + .pack + .assets + .registry + .state(self.world.block(pos.0, pos.1, pos.2)) + else { + return; + }; + let moved = (0..6).rev().find(|i| { + let shown = info + .properties + .get(&format!("slot_{i}_occupied")) + .map(String::as_str); + b.items[*i].is_some() != (shown == Some("true")) + }); + if let Some(slot) = moved { + self.chiseled_bookshelf_update_state([pos.0, pos.1, pos.2], slot); + } + } +} diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index 1cf59733d..343390a1a 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -17,8 +17,10 @@ impl Game<'_> { return; } let mut events = Vec::new(); + let random = self.particles.level_random(); for m in self.mobs.iter_mut().filter(|m| !m.removed) { ambient::client_ai_step(m, &mut events); + ambient::client_particles(m, random, &mut events); } for event in events { match event { @@ -37,6 +39,7 @@ impl Game<'_> { } } self.eye_particles(); + self.panda_effects(); self.sprint_dust(); self.effect_swirls(); } diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index f69f1b695..808f489c7 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -42,9 +42,20 @@ pub(super) struct CombatTracker { /// The projectile hitting the player now is another player's that /// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally). pub(super) refuse_player_hit: bool, + /// The player whose melee hit is landing on the player now: where they + /// stand and the seconds their weapon disables a shield for + /// (`getSecondsToDisableBlocking`). + pub(super) player_attacker: Option<([f64; 3], f32)>, /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, + /// The blast now going off comes from a primed TNT, creeper, wither + /// skull, wither or TNT minecart, the sources that empty a hive they + /// destroy (`BeehiveBlock.getDrops`). + pub(super) hive_emptying_blast: bool, + /// The mob that owns the projectile exploding now (`getIndirectSourceEntity`): + /// the mobs the blast hurts record it as their attacker. + pub(super) explosion_owner: 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. @@ -131,6 +142,19 @@ impl Game<'_> { self.recheck_combat(); for e in events { let (name, amount) = match e { + // LivingEntity.getDamageAfterMagicAbsorb (Resistance) and + // Player.actuallyHurt (absorption hearts) and + // LivingEntity.hurtServer (the shield, only for an accepted + // hit), in tenths. + MotionEvent::Health(HealthEvent::Statistic { name, amount }) => { + match *name { + "resisted" => self.stats.custom("damage_resisted", *amount), + "absorbed" => self.stats.custom("damage_absorbed", *amount), + "blocked" => self.stats.custom("damage_blocked_by_shield", *amount), + _ => {} + } + continue; + } MotionEvent::Health(HealthEvent::RecordedDamage { source, amount }) => { let Some(d) = self.motion.health.damage.definition(*source) else { continue; @@ -177,6 +201,10 @@ impl Game<'_> { direct, }); self.combat.last_damage = now; + // InfestedMobEffect.onMobHurt. + if self.potions.effects.get("infested").is_some() { + self.player_infested(); + } } self.combat.pending.clear(); self.combat.pending_direct.clear(); diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index d3c40c3eb..f0bbdb13e 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2049,8 +2049,7 @@ impl Game<'_> { return false; } self.world.block_entities.insert(key, new); - let state = self.world.block(pos[0], pos[1], pos[2]); - let _ = self.world.set(pos[0], pos[1], pos[2], state); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); true } /// RandomizableContainer.tryLoadLootTable for a tag a command gives a @@ -2211,7 +2210,8 @@ impl Game<'_> { let dmax = [dest[0] + size[0], dest[1] + size[1], dest[2] + size[2]]; let overlap = (0..3).all(|i| dest[i] <= max[i] && dmax[i] >= min[i]); let moving = ctx.has("move"); - if !ctx.has("force") && overlap { + // Mode.canOverlap: only the normal mode refuses overlapping regions. + if !ctx.has("force") && !moving && overlap { return Err(err("commands.clone.overlap", &[])); } let area = (0..3).map(|i| i64::from(size[i] + 1)).product::(); @@ -2420,26 +2420,54 @@ impl Game<'_> { let levels = ctx.has("levels"); let unit = if levels { "levels" } else { "points" }; if ctx.has("query") { - let _ = self.entities(ctx, "target", true)?; - let e = &self.experience; - let value = if levels { - e.level - } else { - (e.progress * horizon_client::entities::Experience::needed(e.level) as f32) as i32 - }; + let target = self.entities(ctx, "target", true)?[0]; + // ExperienceCommand.queryExperience: the target's own level or points. + let value = self + .for_player(target, |g| { + let e = &g.experience; + if levels { + e.level + } else { + (e.progress * horizon_client::entities::Experience::needed(e.level) as f32) + as i32 + } + }) + .unwrap_or(0); self.system_message(Text::translate( &format!("commands.experience.query.{unit}"), - &[ - Text::literal(self.acting_player_name()), - Text::literal(value.to_string()), - ], + &[self.target_name(target), Text::literal(value.to_string())], )); return Ok(value); } let targets = self.entities(ctx, "target", true)?; let amount = Self::int(ctx, "amount").unwrap_or(0); - let op = if ctx.has("add") { "add" } else { "set" }; - if op == "add" { + let add = ctx.has("add"); + let op = if add { "add" } else { "set" }; + // Every target changes (a set of points can be refused for some). + let changed: Vec = targets + .iter() + .copied() + .filter(|&t| { + self.for_player(t, |g| g.change_experience(add, levels, amount)) == Some(true) + }) + .collect(); + if changed.is_empty() { + return Err(err("commands.experience.set.points.invalid", &[])); + } + let (key, who) = match changed[..] { + [only] => ("single", self.target_name(only)), + _ => ("multiple", Text::literal(changed.len().to_string())), + }; + self.feedback(Text::translate( + &format!("commands.experience.{op}.{unit}.success.{key}"), + &[Text::literal(amount.to_string()), who], + )); + Ok(changed.len() as i32) + } + /// ExperienceCommand's add and set on the player in place: false when + /// the points to set do not fit the level. + fn change_experience(&mut self, add: bool, levels: bool, amount: i32) -> bool { + if add { if levels { self.experience.level = (self.experience.level + amount).max(0); if self.experience.level == 0 && amount < 0 { @@ -2453,26 +2481,11 @@ impl Game<'_> { } else { let needed = horizon_client::entities::Experience::needed(self.experience.level); if amount > needed - 1 { - return Err(err("commands.experience.set.points.invalid", &[])); + return false; } self.experience.progress = amount as f32 / needed as f32; } - let key = format!( - "commands.experience.{op}.{unit}.success.{}", - if targets.len() == 1 { - "single" - } else { - "multiple" - } - ); - self.feedback(Text::translate( - &key, - &[ - Text::literal(amount.to_string()), - Text::literal(self.acting_player_name()), - ], - )); - Ok(targets.len() as i32) + true } fn cmd_gamerule(&mut self, ctx: &Context) -> R { let Some(name) = ctx.literals.get(1).cloned() else { @@ -2557,21 +2570,26 @@ impl Game<'_> { }; let yaw = ((rot[0] + 180.0).rem_euclid(360.0)) - 180.0; let pitch = rot[1].clamp(-90.0, 90.0); - // SetSpawnCommand: a forced point in the source's level. - if self.dim == Dim::Overworld { - self.spawn = Some(Vec3::new( - f64::from(pos[0]) + 0.5, - f64::from(pos[1]), - f64::from(pos[2]) + 0.5, - )); - self.respawn_config = None; - } else { - self.spawn = None; - self.respawn_config = Some(super::respawn_anchor::RespawnConfig { - dim: self.dim, - pos, - yaw, - forced: true, + // SetSpawnCommand: a forced point in the source's level, for each target. + let level = self.dim; + for &t in &targets { + self.for_player(t, |g| { + if level == Dim::Overworld { + g.spawn = Some(Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + )); + g.respawn_config = None; + } else { + g.spawn = None; + g.respawn_config = Some(super::respawn_anchor::RespawnConfig { + dim: level, + pos, + yaw, + forced: true, + }); + } }); } let dim = Text::literal(self.dim.id()); @@ -2751,6 +2769,44 @@ impl Game<'_> { }, }; let max = Self::int(ctx, "maxCount").unwrap_or(-1); + let counting = max == 0; + // ClearInventoryCommands.clearInventory: each player on their own. + let mut removed = 0i32; + let mut found = Vec::new(); + for &t in &targets { + let n = self + .for_player(t, |g| g.clear_matching(&predicate, max)) + .unwrap_or(0); + removed += n; + if n != 0 { + found.push(t); + } + } + if removed == 0 { + return Err(if targets.len() == 1 { + CommandError::new(Text::translate( + "clear.failed.single", + &[self.target_name(targets[0])], + )) + } else { + err("clear.failed.multiple", &[&targets.len()]) + }); + } + let kind = if counting { "test" } else { "success" }; + let (key, who) = match found[..] { + [only] => ("single", self.target_name(only)), + _ => ("multiple", Text::literal(found.len().to_string())), + }; + self.feedback(Text::translate( + &format!("commands.clear.{kind}.{key}"), + &[Text::literal(removed.to_string()), who], + )); + Ok(removed) + } + /// Inventory.clearOrCountMatchingItems for the player in place: `max` + /// of the matching items go (all when negative, none and only counted + /// when 0). Returns how many matched. + fn clear_matching(&mut self, predicate: &ItemInput, max: i32) -> i32 { let counting = max == 0; // Inventory slots 0..40: main, armor feet to head, off hand; // then clearOrCountMatchingItems visits the crafting grid and carried stack. @@ -2766,10 +2822,7 @@ impl Game<'_> { }; let matching: Vec = all(self) .iter() - .map(|s| { - s.as_ref() - .is_some_and(|s| self.stack_matches(&predicate, s)) - }) + .map(|s| s.as_ref().is_some_and(|s| self.stack_matches(predicate, s))) .collect(); let mut slots: Vec<&mut Option> = Vec::new(); slots.extend(self.inventory.iter_mut()); @@ -2799,25 +2852,7 @@ impl Game<'_> { } } } - if removed == 0 { - return Err(if targets.len() == 1 { - CommandError::new(Text::translate( - "clear.failed.single", - &[Text::literal(self.acting_player_name())], - )) - } else { - err("clear.failed.multiple", &[&targets.len()]) - }); - } - let kind = if counting { "test" } else { "success" }; - self.feedback(Text::translate( - &format!("commands.clear.{kind}.single"), - &[ - Text::literal(removed.to_string()), - Text::literal(self.acting_player_name()), - ], - )); - Ok(removed) + removed } /// `PoiTypes`: the point of interest type of a block state. fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { diff --git a/crates/horizon-client/src/game/consume.rs b/crates/horizon-client/src/game/consume.rs index dc187d207..e5fae08ca 100644 --- a/crates/horizon-client/src/game/consume.rs +++ b/crates/horizon-client/src/game/consume.rs @@ -67,6 +67,17 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.burp", self.feet(), 0.5, pitch); } + // SuspiciousStewEffects.onConsume, a ConsumableListener: each entry is + // added as a `MobEffectInstance(effect, duration)` (amplifier 0). + if let Some(data) = stack.extra.as_deref() { + for (id, duration) in &data.stew_effects { + if let Some(def) = horizon_client::brewing::effect(id) { + self.add_player_effect(horizon_client::effects::EffectInstance::new( + def.id, *duration, 0, + )); + } + } + } for effect in &consumable.effects { self.apply_consume_effect(effect); } diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 2f98e1c7e..1bb73d51d 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -44,13 +44,13 @@ impl Game<'_> { slot: usize, stack: Option, ) { - if let Some(e) = self - .world - .block_entities - .get_mut(&(chest[0], chest[1], chest[2])) + let key = (chest[0], chest[1], chest[2]); + if let Some(e) = self.world.block_entities.get_mut(&key) && let Some(s) = e.slots_mut().get_mut(slot) { *s = stack; + // TransportItemsBetweenContainers calls Container.setChanged. + self.container_changed(key); } } /// `ContainerOpenersCounter.recheckOpeners` every five ticks: the golems @@ -204,6 +204,64 @@ impl Game<'_> { } } // ---- interactions ----------------------------------------------------- + /// `WeatheringCopperGolemStatueBlock.useItemOn`: an axe on an unoxidized + /// statue turns it back into a golem (`CopperGolemStatueBlockEntity.removeStatue`), + /// wearing the axe. Weathered statues are scraped by the axe's own + /// transform instead. + pub(super) fn use_golem_statue(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { + if !held.is_some_and(|s| s.item.ends_with("_axe")) { + return false; + } + let registry = self.pack.assets.registry; + let Some(state) = registry.state(self.world.block(pos[0], pos[1], pos[2])) else { + return false; + }; + if state.name != "minecraft:copper_golem_statue" { + return false; + } + // `Direction.toYRot` of the statue's facing. + let yaw = match state.properties.get("facing").map(String::as_str) { + Some("west") => 90.0, + Some("north") => 180.0, + Some("east") => 270.0, + _ => 0.0, + }; + let waterlogged = state + .properties + .get("waterlogged") + .is_some_and(|w| w == "true"); + // initCopperGolem: at the block's feet, facing as the statue does. + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + let Some(id) = self.spawn_mob("minecraft:copper_golem", at, true) else { + return false; + }; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.yaw = yaw; + m.previous_yaw = yaw; + m.body_yaw = yaw; + m.previous_body_yaw = yaw; + m.head_yaw = yaw; + m.previous_head_yaw = yaw; + } + self.damage_held(1); + self.audio + .play("minecraft:entity.copper_golem.spawn", Some(at), 1.0, 1.0); + // Level.removeBlock(pos, false): air, or the water the statue stood in. + let replacement = registry.default_state(if waterlogged { + "minecraft:water" + } else { + "minecraft:air" + }); + if let Some(replacement) = replacement { + let _ = self.level_set(pos, replacement); + } + self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); + true + } /// `CopperGolem.mobInteract`; true when handled. pub(super) fn interact_copper_golem(&mut self, index: usize, item: &str) -> bool { if self.mobs[index].species() != Species::CopperGolem || !self.mobs[index].alive() { diff --git a/crates/horizon-client/src/game/creative_hotbar.rs b/crates/horizon-client/src/game/creative_hotbar.rs new file mode 100644 index 000000000..81e5ad6c4 --- /dev/null +++ b/crates/horizon-client/src/game/creative_hotbar.rs @@ -0,0 +1,39 @@ +//! The creative toolbars, `hotbar.nbt` beside `options.txt`: hold the save or +//! load key and press a hotbar key (`Minecraft.handleKeybinds`). +use super::Game; +use horizon_client::{hotbar, keybinds, text::Text}; + +impl Game<'_> { + /// Whether the key bound to `mapping` is held. + pub(super) fn mapped_key_down(&self, mapping: &str) -> bool { + keybinds::key_code(self.settings.keys.get(mapping)) + .is_some_and(|k| self.physical_keys.contains(&k)) + } + + /// `CreativeModeInventoryScreen.handleHotbarLoadOrSave` for the hotbar key + /// `index`: load puts the saved row in the hotbar (the creative slot + /// packets follow from the inventory change), save stores the hotbar and + /// says so on the action bar. + pub(super) fn hotbar_load_or_save(&mut self, index: usize, load: bool) { + let path = Self::options_path().with_file_name("hotbar.nbt"); + let known = |id: &str| self.res.items().get(id).is_some(); + let mut rows = hotbar::load(&path, &known); + if load { + for (slot, stack) in rows[index].iter().enumerate() { + self.inventory[slot] = stack.clone(); + } + return; + } + rows[index] = self.inventory[..hotbar::SIZE].to_vec(); + let _ = hotbar::save(&path, &rows); + let key = |mapping: &str| keybinds::display_name(self.settings.keys.get(mapping)); + let message = Text::translate( + "inventory.hotbarSaved", + &[ + key("key.loadToolbarActivator"), + key(&format!("key.hotbar.{}", index + 1)), + ], + ); + self.titles.set_overlay(message, false); + } +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 221af37f6..6384a3051 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -46,10 +46,27 @@ pub(super) struct Creatures { pub projectiles: Vec, /// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs). pub wind_bursts: Vec, + /// Mace smash knockback on the other players from a guest's turn, waiting + /// for it to end (game/mace.rs). + pub smash_pushes: Vec, + /// Explosion packets from a guest's turn, waiting for it to end + /// (centre, small, radius, blocks hit; game/lan_particles.rs). + pub lan_explosions: Vec<([f64; 3], bool, f32, usize)>, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. pub trader: super::wandering_trader::Spawner, + /// The cat spawner's countdown (`CatSpawner.nextTick`). + pub cat_tick: i32, + /// Particles from a guest's turn, waiting for it to end + /// (`lan_send_particles`: options, centre, spread, speed, count). + pub lan_particles: Vec<( + horizon_client::particles::ParticleOptions, + [f64; 3], + [f64; 3], + f64, + u32, + )>, } pub(super) struct ProjWorld<'a, 'w> { pub w: &'a MobWorld<'w>, @@ -146,6 +163,8 @@ fn flame_geometry( layer: 0, color: 0xFFFF_FFFF, light: packed, + + glint_uv: [0.0, 0.0], }); } h -= 0.45; @@ -182,22 +201,27 @@ impl Game<'_> { // EntitySelector.NO_CREATIVE_OR_SPECTATOR. creative: self.creative || self.spectator(), sneaking: self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft), + swimming: p.swimming, look: view_vector(self.yaw, self.pitch), main_hand: self.held().map(|s| s.item.clone()), off_hand: None, head: self.armor[0].as_ref().map(|s| s.item.clone()), armor_cover: self.armor.iter().filter(|a| a.is_some()).count() as f32 / 4.0, + invisible: self.potions.effects.get("invisibility").is_some(), spectator: self.spectator(), gold_armor: self.wearing_gold(), hurt_by: self.player_hurt_by(), last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)), velocity: p.velocity, yaw: self.yaw, + sprinting: p.sprinting, + riding: self.riding.is_some(), 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, + passenger: self.riding.is_some(), }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -402,6 +426,7 @@ impl Game<'_> { world: &self.world, registry: self.pack.assets.registry, facts: self.res.facts(), + fluid_tables: &self.motion.fluids, movement: &self.motion.blocks, collision: self.collision, data: self.res.mob_data(), @@ -419,11 +444,13 @@ impl Game<'_> { block_tags: &self.res.items().block_tags, biomes: self.res.biomes(), mob_griefing: self.ui.rules.bool("mob_griefing"), + mob_drops: self.ui.rules.bool("mob_drops"), end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, teams: std::sync::Arc::new(self.mob_teams()), items: Some(self.res.items()), + lid_openers: &self.lid_openers, difficulty: self.local_difficulty( self.player .as_ref() @@ -480,6 +507,7 @@ impl Game<'_> { if self.ui.rules.bool("spawn_mobs") { self.tick_wandering_trader(); self.tick_patrol_spawner(); + self.tick_cat_spawner(); } self.tick_raids(); self.tick_creature_entities() @@ -512,6 +540,7 @@ impl Game<'_> { let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); let mut dead = Vec::new(); + let mut corpses = Vec::new(); let mut died = std::mem::take(&mut self.died); let ticking = self.entity_ticking_area(); // With guests on, each mob sees its nearest player (game/lan_mobs.rs). @@ -561,6 +590,9 @@ impl Game<'_> { ..base.clone() }; let m = &mut mobs[i]; + // getCurrentDifficultyAt(blockPosition()): the mob's own chunk, + // not the local player's (a server thread has no player). + w.difficulty = self.local_difficulty([m.position.x, m.position.y, m.position.z]); w.nearest_player = super::natural_spawning::nearest_player( &players, m.position.x, @@ -606,6 +638,11 @@ impl Game<'_> { horizon_client::mobs::apply_mob_pushes(m, &mut pushes); let from = events.len(); let kept = m.tick(&w, &mut scratch, &mut events); + // A killed mob's body is removed: its effects that act on + // death run (`LivingEntity.remove` with KILLED). + if !kept && !m.alive() && !m.removed && !m.extra.effects.is_empty() { + corpses.push(m.clone()); + } horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); // LivingEntity.tickDeath: after twenty ticks the body is removed. if !kept && !m.removed && !m.alive() && m.death_time >= 20 { @@ -686,11 +723,22 @@ impl Game<'_> { for m in dead { self.mob_died(&m); } + for mut m in corpses { + let names: Vec<&'static str> = m + .extra + .effects + .iter() + .map(|e| e.0.trim_start_matches("minecraft:")) + .collect(); + let bounds = m.bounds(); + self.effects_on_death(&names, bounds, false, Some(m.id), Some(&mut m.random)); + } self.handle_mob_events(events)?; self.lan_guest_mob_events(guest_events); self.tick_projectiles()?; self.tick_fangs(); self.tick_allays(); + self.tick_pandas(); self.tick_breeze_effects(); self.tick_sniffer_effects(); self.piglin_pickups(); @@ -725,11 +773,12 @@ impl Game<'_> { let by_player = killer.is_some() || m.ai.last_hurt_by_player > 0; let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby - // takes the experience (before the loot is dropped). + // takes the experience (before the loot is dropped). It takes what + // would drop, whoever killed the mob. self.sculk_mob_died(m); let consumed = self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |_| { - if by_player { + if horizon_client::mobs::drops::drops_experience(&dying) { horizon_client::mobs::drops::base_experience(&mut dying).max(0) as u32 } else { 0 @@ -758,6 +807,7 @@ impl Game<'_> { self.villager_murdered(m, by_player); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; self.drop_death_loot(&mut dying, by_player, consumed, pos); + self.create_wither_rose(m); if m.species() == Species::CopperGolem { // CopperGolem.dropEquipment: the preserved equipment too. self.golem_drop_equipment(&mut dying); @@ -888,6 +938,18 @@ impl Game<'_> { } } } + /// `InfestedMobEffect.onMobHurt` for a mob: silverfish from half its height up. + pub(super) fn mob_infested(&mut self, mob: u32) { + if let Some(m) = self.mobs.iter().find(|m| m.id == mob) { + let at = [ + m.position.x, + m.position.y + f64::from(m.height()) / 2.0, + m.position.z, + ]; + let look = m.view_vector(); + self.infested_hurt(at, look, Some(mob)); + } + } /// `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 @@ -952,6 +1014,9 @@ impl Game<'_> { .map_or([0.0; 3], |m| [m.velocity.x, m.velocity.y, m.velocity.z]); self.drown_particles(at, v); } + MobEvent::EntityEvent { mob, event, at } => { + self.lan_entity_event(mob as i32, event, at) + } MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { self.audio @@ -980,6 +1045,18 @@ impl Game<'_> { MobEvent::AttackPlayer(amount, from) => { self.mob_hits_player(amount, from, "minecraft:mob_attack"); } + // doHurtTarget: the effect only when hurtServer took damage. + MobEvent::AttackPlayerWithEffect { + amount, + from, + effect, + ticks, + amplifier, + } => { + if self.mob_hits_player(amount, from, "minecraft:mob_attack") { + self.give_player_effect(effect, ticks, amplifier); + } + } MobEvent::DamagePlayer { amount, from, kind } => { self.mob_hits_player(amount, from, kind); } @@ -999,6 +1076,19 @@ impl Game<'_> { } } } + MobEvent::Knockback { + target, + power, + x, + z, + } => match target { + Who::Player => self.knock_back_player(power, x, z), + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.knockback(power, x, z); + } + } + }, MobEvent::Shift { target, delta } => { let d = Vec3::new(delta[0], delta[1], delta[2]); match target { @@ -1033,7 +1123,7 @@ impl Game<'_> { self.combat.charged_exploders.push(mob); } } - MobEvent::Explode(at, radius) => { + MobEvent::Explode(at, radius, species) => { // The exploding mob causes the damage (Creeper.explodeCreeper). let source_mob = self.combat.explosion_source.or_else(|| { self.mobs @@ -1049,7 +1139,14 @@ impl Game<'_> { self.note_attacker("minecraft:explosion", id); } self.combat.explosion_source = source_mob; - let result = self.explode(at, radius); + // Only a creeper or a wither empties the hives it blows up. + // The creeper is already gone from the list, so the event + // carries its kind. + let result = if matches!(species, Species::Creeper | Species::Wither) { + self.with_hive_emptying_blast(|g| g.explode(at, radius)) + } else { + self.explode(at, radius) + }; self.combat.explosion_source = None; result? } @@ -1060,6 +1157,7 @@ impl Game<'_> { } => { let mut killed = false; let mut hurt = false; + let mut infested = false; if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) { let hit = t.damage(amount, source); hurt = hit; @@ -1068,20 +1166,27 @@ impl Game<'_> { // The hurt or death sound the mob raised. let center = t.center(); for event in std::mem::take(&mut t.outbox) { - if let MobEvent::Sound(s, _, volume, pitch) = event { - self.audio.play( - &format!("minecraft:{s}"), - Some(center), - volume, - pitch, - ); - } else { - // Left for the end of the tick. - t.outbox.push(event); + match event { + MobEvent::Sound(s, _, volume, pitch) => { + self.audio.play( + &format!("minecraft:{s}"), + Some(center), + volume, + pitch, + ); + } + MobEvent::Infested { .. } => infested = true, + other => { + // Left for the end of the tick. + t.outbox.push(other); + } } } } } + if infested { + self.mob_infested(target); + } if hurt && let Some(Who::Mob(attacker)) = source.attacker && let Some(m) = self @@ -1127,6 +1232,7 @@ impl Game<'_> { } MobEvent::BecomeStatue { mob } => self.golem_become_statue(mob), MobEvent::EnterHive { mob, hive } => self.bee_enter_hive(mob, hive), + MobEvent::Infested { mob } => self.mob_infested(mob), MobEvent::Gift { target, item } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target) && m.saddle_item().is_none() @@ -1177,9 +1283,9 @@ impl Game<'_> { [0.0, 0.2, 0.0], 10, ), - MobEvent::SetBlock { pos, state } => { - self.world.set(pos[0], pos[1], pos[2], state)? - } + // `Level.setBlockAndUpdate`: neighbour and shape updates, so a crop + // above trampled farmland breaks and drops. + MobEvent::SetBlock { pos, state } => self.level_set(pos, state)?, MobEvent::SetDoorOpen { pos, open } => { let pos = BlockPos::new(pos[0], pos[1], pos[2]); self.with_level(|b, level, ticks| b.set_door_open(level, ticks, pos, open)); @@ -1290,12 +1396,17 @@ impl Game<'_> { } } MobEvent::AroundSelf { + mob, + event, kind, feet, width, height, burst, - } => self.particles_around(kind, feet, [width, height], burst), + } => { + self.lan_entity_event(mob as i32, event, feet); + self.particles_around(kind, feet, [width, height], burst) + } MobEvent::ParticleAt { kind, at, velocity } => { if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) { let options = horizon_client::particles::ParticleOptions::simple(ty); @@ -1323,6 +1434,27 @@ impl Game<'_> { .list .retain(|e| e.id != "mining_fatigue"); } + MobEvent::DolphinTreasure { mob } => { + // ServerLevel.findNearestMapStructure(#dolphin_located, 50). + let Some(at) = self.mobs.iter().find(|m| m.id == mob).map(|m| { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ] + }) else { + continue; + }; + let names = self.structure_tag("minecraft:dolphin_located"); + let found = self + .end + .locator() + .filter(|_| !names.is_empty()) + .and_then(|t| t.locate(&names, at, 50)); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + m.extra.home = found.map(|(_, p)| p); + } + } MobEvent::EffectPlayer { effect, ticks, @@ -1406,9 +1538,30 @@ impl Game<'_> { m.ai.aggressive |= aggressive; } } + MobEvent::PandaSneezed { mob } => self.panda_sneezed(mob), + MobEvent::ShedScute { mob, at, pitch } => { + // The mob already checked `shouldDropLoot` (a baby, `mob_drops`). + let table = "minecraft:gameplay/armadillo_shed"; + let drops = self.sequence_loot(table, table, None); + for d in drops { + self.spawn_at_location(Vec3::new(at[0], at[1], at[2]), 0.0, d); + } + self.audio.play( + "minecraft:entity.armadillo.scute_drop", + Some(at), + 1.0, + pitch, + ); + let ctx = self.who_context(Some(Who::Mob(mob)), None); + self.post_game_event("minecraft:entity_place", at, ctx); + } MobEvent::GiftLoot { mob, table, at } => { - // Turtle.ageBoundaryReached: only with mob loot on. - if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops") + // Turtle.ageBoundaryReached and Panda.afterSneeze: only + // with mob loot on. + if matches!( + table, + "minecraft:gameplay/turtle_grow" | "minecraft:gameplay/panda_sneeze" + ) && !self.ui.rules.bool("mob_drops") { continue; } @@ -1534,6 +1687,8 @@ impl Game<'_> { q.extra.in_love = 0; } let q = self.mobs.iter().find(|m| m.id == partner).cloned(); + // Animal.finalizeSpawnChildFromBreeding: entity event 18 for the parent. + self.mob_event_particles(parent, 18); // Sniffer.spawnChildFromBreeding: an egg instead of a baby. if p.species() == Species::Sniffer { self.lay_sniffer_egg(&p); @@ -1645,6 +1800,13 @@ impl Game<'_> { self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); return; } + // Panda.getBreedOffspring: genes from both parents. + if p.species() == Species::Panda { + horizon_client::mobs::panda::inherit(child, &p, q.as_ref().unwrap_or(&p)); + let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); + return; + } // Nautilus.getBreedOffspring: a tame parent's baby is tame too. if p.species() == Species::Nautilus && p.extra.tame { child.extra.tame = true; @@ -1653,6 +1815,10 @@ impl Game<'_> { } // Offspring inherit a parent's variant (pigs/cows/chickens) or mixed wool. child.extra.variant = p.extra.variant; + // Fox.getBreedOffspring: either parent's variant. + if p.species() == Species::Fox && !coin { + child.extra.variant = q.as_ref().map_or(p.extra.variant, |q| q.extra.variant); + } if p.species() == Species::Sheep { child.extra.color = p.extra.color; } @@ -1806,6 +1972,10 @@ impl Game<'_> { let (xd, zd) = from.map_or((0.0, 0.0), |from| { (from[0] - player.position.x, from[2] - player.position.z) }); + // dealDefaultKnockback's `indicateDamage`, unless blocked. + if o.blocked <= 0.0 { + player.health.indicate_damage(xd, zd, player.yaw); + } self.knock_back_player(f64::from(0.4_f32), xd, zd); if let Some(p) = self.player.as_mut() && let Some(r) = p.hurt_log.last_mut() @@ -1818,6 +1988,23 @@ impl Game<'_> { self.thorns(a); } } + // LivingEntity.hurtServer: ENTITY_HURT_PLAYER, unless it returned + // early (invulnerable, or inside the hurt cooldown). + if outcome.hurt || outcome.sound { + let source = attacker + .or(owner) + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|m| self.mob_entity(m)); + self.trigger_entity_hurt_player(&horizon_client::advancements::DamageView { + kind: damage_type.to_owned(), + direct: source.clone().filter(|_| !projectile), + is_direct: !projectile, + source, + original: amount, + actual: amount - outcome.blocked, + blocked: outcome.blocked > 0.0, + }); + } if raised { self.after_block(outcome, amount, attacker, projectile); } @@ -2050,6 +2237,21 @@ impl Game<'_> { if super::remote_projectiles::has_smoke_trail(&p.kind) { trails.push(p.position); } + // ThrownEnderpearl.onAboveBubbleColumn / onInsideBubbleColumn. + if keep && hit == Hit::None && matches!(p.kind, ProjectileKind::EnderPearl) { + let (at, h) = (p.position, 0.125); + horizon_client::motion::bubble_column_push( + w.world, + w.registry, + w.facts, + w.collision, + Aabb::new( + Vec3::new(at.x - h, at.y, at.z - h), + Vec3::new(at.x + h, at.y + 2.0 * h, at.z + h), + ), + &mut p.velocity, + ); + } if let Some(a) = p.arrow.as_mut() { arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); } @@ -2125,6 +2327,7 @@ impl Game<'_> { _ => self.projectile_hit(&p, hit)?, } } + self.flush_lan_explosions(); self.flush_wind_bursts() } /// `projectile_hit` for a projectile the guest `conn` shot, run as them; @@ -2474,14 +2677,57 @@ impl Game<'_> { .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { self.last_hurt_by_player.insert(id, self.lan_acting); + if hurt && let Some(m) = self.mobs.iter().find(|m| m.id == id) { + // LivingEntity.hurtServer: PLAYER_HURT_ENTITY. + let victim = self.mob_entity(m); + let spectral = p.arrow.as_ref().is_some_and(|a| { + &*a.pickup_item.item == "minecraft:spectral_arrow" + }); + let direct = horizon_client::advancements::EntityView { + kind: if spectral { + "minecraft:spectral_arrow" + } else { + "minecraft:arrow" + } + .into(), + position: [p.position.x, p.position.y, p.position.z], + ..Default::default() + }; + self.player_hit(&victim, "minecraft:arrow", Some(direct), amount); + } + // AbstractArrow.onHitEntity: KILLED_BY_ARROW for a kill + // (piercing arrows are not modelled). + if hurt + && let Some(m) = self.mobs.iter().find(|m| m.id == id) + && !m.alive() + { + let victim = self.mob_entity(m); + let weapon = + p.arrow.as_ref().and_then(|a| a.fired_from_weapon.as_ref()); + self.trigger_killed_by_arrow(&[victim], weapon); + } } hurt } }; - // doKnockback: Punch pushes along the flight. + // doKnockback: Punch pushes along the flight, less the target's + // knockback resistance. let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt(); - if hurt && p.bonus.punch > 0 && flight > 1e-6 { - let k = f64::from(p.bonus.punch) * 0.6 / flight; + let resistance = match who { + Who::Player => self + .player + .as_mut() + .and_then(|pl| pl.attribute("minecraft:knockback_resistance").ok()) + .unwrap_or(0.0), + Who::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .map_or(0.0, |m| m.attrs.knockback_resistance), + }; + let push = f64::from(p.bonus.punch) * 0.6 * (1.0 - resistance).max(0.0); + if hurt && push > 0.0 && flight > 1e-6 { + let k = push / flight; self.handle_mob_events(vec![MobEvent::Push { target: who, velocity: [p.velocity.x * k, 0.1, p.velocity.z * k], @@ -2517,6 +2763,7 @@ impl Game<'_> { }; m.damage(amount, source); } + self.thrown_break_event(p.id, atp); self.item_burst(atp, "minecraft:snowball"); } (ProjectileKind::Egg, hit) => { @@ -2542,6 +2789,7 @@ impl Game<'_> { } } } + self.thrown_break_event(p.id, atp); self.item_burst(atp, "minecraft:egg"); } (ProjectileKind::EnderPearl, hit) => { @@ -2645,7 +2893,10 @@ impl Game<'_> { if let Some(owner) = self.combat.projectile_owner { self.note_attacker("minecraft:explosion", owner); } - self.explode(atp, *power as f32)?; + self.combat.explosion_owner = self.combat.projectile_owner; + let result = self.explode(atp, *power as f32); + self.combat.explosion_owner = None; + result?; } ( ProjectileKind::Potion { @@ -2791,10 +3042,17 @@ impl Game<'_> { } Ok(()) } + /// `Snowball`/`ThrownEgg.onHit`: entity event 3 for the guests, before the + /// projectile is discarded (the clients lose it when the tracker next runs). + fn thrown_break_event(&mut self, id: u32, at: [f64; 3]) { + if id != 0 { + self.lan_entity_event(id as i32, 3, at); + } + } /// `Snowball`/`ThrownEgg.handleEntityEvent(3)`: eight crumbs of the /// thrown item where it broke, at rest for a snowball, scattered by the /// client entity's random (the particle engine's here) for an egg. - fn item_burst(&mut self, at: [f64; 3], item: &str) { + pub(super) fn item_burst(&mut self, at: [f64; 3], item: &str) { let options = self.item_particle(&horizon_client::items::ItemStack::new(item, 1)); let egg = item != "minecraft:snowball"; for _ in 0..8 { @@ -2830,6 +3088,10 @@ impl Game<'_> { if self.name_mob(index) { return Ok(true); } + if self.spawn_egg_offspring(index) { + self.swing_arm(); + return Ok(true); + } { let item = self.held().map(|h| h.item.to_string()).unwrap_or_default(); if self.interact_leash(index, &item) { @@ -2872,6 +3134,14 @@ impl Game<'_> { let creative = self.creative; // The hand's slot (Player.interactOn passes the hand). let selected = self.held_slot(); + // Panda.mobInteract: bamboo, or a click on a panda lying on its back. + if self.mobs[index].species() == Species::Panda && self.mobs[index].alive() { + let taken = self.interact_panda(index, &item); + if taken { + self.swing_arm(); + } + return Ok(taken); + } if self.interact_zombie_villager(index, &item) { return Ok(true); } @@ -2891,6 +3161,14 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.interact_armadillo(index, &item) { + if let Some(stack) = &held { + let target = self.mob_entity(&self.mobs[index]); + self.trigger_item_entity("minecraft:player_interacted_with_entity", stack, &target); + } + self.swing_arm(); + return Ok(true); + } if self.interact_copper_golem(index, &item) { self.swing_arm(); return Ok(true); @@ -2919,11 +3197,18 @@ impl Game<'_> { .item_tags .get("minecraft:creeper_igniters") .is_some_and(|t| t.contains(&*item)); + let fish = self + .res + .items() + .item_tags + .get("minecraft:fishes") + .is_some_and(|t| t.contains(&*item)); let damageable = self .res .items() .get(&item) .is_some_and(|i| i.max_damage > 0); + let acting = self.acting_player_uuid(); let m = &mut self.mobs[index]; if !m.alive() { return Ok(false); @@ -2946,6 +3231,16 @@ impl Game<'_> { consume = true; sound = Some("entity.cow.milk"); } + // Goat.mobInteract: a bucket on an adult gives milk. + Species::Goat if item == "minecraft:bucket" && !m.is_baby() => { + give = Some("minecraft:milk_bucket"); + consume = true; + sound = Some(if m.extra.screaming { + "entity.goat.screaming.milk" + } else { + "entity.goat.milk" + }); + } Species::Mooshroom if item == "minecraft:bowl" && !m.is_baby() => { give = Some("minecraft:mushroom_stew"); consume = true; @@ -2972,6 +3267,7 @@ impl Game<'_> { at: pos, setup, }])?; + self.damage_held_tool(); } Species::Sheep if item == "minecraft:shears" && !m.extra.sheared && !m.is_baby() => { m.extra.sheared = true; @@ -3011,13 +3307,15 @@ impl Game<'_> { .items() .get(&item) .and_then(|i| i.food.as_ref()) - .map_or(2.0, |f| f.0 as f32); - // TamableAnimal.feed: playEatingSound, which wolves leave empty. + .map_or(2.0, |f| f.0 as f32 * 2.0); + // TamableAnimal.feed(.., 2.0F, 2.0F): heals twice the nutrition, + // then playEatingSound, which wolves leave empty. m.health = (m.health + heal).min(m.attrs.max_health); consume = true; } Species::Wolf if m.extra.tame + && m.extra.owner == Some(acting) && item.ends_with("_dye") && horizon_client::mobs::render::DYE_NAMES .iter() @@ -3040,7 +3338,9 @@ impl Game<'_> { consume = true; } Species::Wolf - if m.extra.tame && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => + if m.extra.tame + && m.extra.owner == Some(acting) + && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => { m.extra.sitting = !m.extra.sitting; m.ai.jumping = false; @@ -3060,20 +3360,14 @@ impl Game<'_> { let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0; if tamed { horizon_client::mobs::tame::set_tame(m, true); - m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + m.extra.owner = Some(acting); m.persistent = true; m.nav_stop(); m.ai.target = None; m.extra.sitting = true; } - // TamableAnimal.spawnTamingParticles. - let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). - self.particles_around_mob( - self.mobs[index].id, - kind, - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 }); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); @@ -3087,6 +3381,7 @@ impl Game<'_> { // Cat.mobInteract: dye, heal or sit when tame; fish may tame a wild one. Species::Cat if m.extra.tame + && m.extra.owner == Some(acting) && item.ends_with("_dye") && horizon_client::mobs::render::DYE_NAMES .iter() @@ -3109,7 +3404,12 @@ impl Game<'_> { m.persistent = true; consume = true; } - Species::Cat if m.extra.tame && is_food && m.health < m.attrs.max_health => { + Species::Cat + if m.extra.tame + && m.extra.owner == Some(acting) + && is_food + && m.health < m.attrs.max_health => + { let heal = self .res .items() @@ -3122,7 +3422,9 @@ impl Game<'_> { eat = eating_sound(m, &mut self.world.random); } Species::Cat - if m.extra.tame && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => + if m.extra.tame + && m.extra.owner == Some(acting) + && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => { m.extra.sitting = !m.extra.sitting; self.world.modified.insert(( @@ -3136,17 +3438,12 @@ impl Game<'_> { let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0; if tamed { m.extra.tame = true; - m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + m.extra.owner = Some(acting); m.extra.sitting = true; } eat = eating_sound(m, &mut self.world.random); - let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). - self.particles_around_mob( - self.mobs[index].id, - kind, - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 }); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); @@ -3194,18 +3491,54 @@ impl Game<'_> { m.extra.tame = true; m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); } - let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). - self.particles_around_mob( - self.mobs[index].id, - kind, - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 }); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); } } + // Dolphin.mobInteract: a fish makes a baby grow by a tenth and an + // adult remember it (`gotFish`), to swim to a treasure. + Species::Dolphin if fish => { + eat = Some(("entity.dolphin.eat", 1.0, 1.0)); + if m.extra.age < 0 { + let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32; + horizon_client::mobs::ai::age_up(m, secs, true); + } else { + m.extra.flag = true; + } + consume = true; + } + // Tadpole.feed: frog food ages it by a tenth of the time left to + // grow into a frog (it grows on its next tick once past 24000). + Species::Tadpole if is_food && !m.extra.age_locked => { + consume = true; + let left = 24_000 - m.extra.age; + m.extra.age += ((left / 20) as f32 * 0.1) as i32 * 20; + // One happy villager particle at rest about the body. + self.particles_around_mob( + self.mobs[index].id, + "happy_villager", + horizon_client::particles::Burst::HORSE_EATING, + ); + } + // Bee.mobInteract: a wither rose or an open eyeblossom is eaten for + // its `getBeeInteractionEffect` instead of breeding the bee. + Species::Bee + if is_food + && matches!( + &*item, + "minecraft:wither_rose" | "minecraft:open_eyeblossom" + ) => + { + if &*item == "minecraft:wither_rose" { + m.add_effect("minecraft:wither", 40, 0); + } else { + m.add_effect("minecraft:poison", 25, 0); + } + consume = true; + } // HappyGhast.canFallInLove: never, so only a ghastling takes food. _ if is_food && m.kind.flags.animal @@ -3218,6 +3551,11 @@ impl Game<'_> { Some(sound) => { consume = true; eat = sound; + // Animal.setInLove: entity event 18 (a baby that + // only grew is not in love). + if self.mobs[index].extra.in_love > 0 { + self.mob_event_particles(self.mobs[index].id, 18); + } } // Animal.mobInteract still consumes the client click when // an adult cannot breed, without swinging or taking food. @@ -3293,23 +3631,53 @@ impl Game<'_> { } Ok(true) } - pub(super) fn damage_held_tool(&mut self) { - if self.creative { - return; - } - let slot = self.held_slot(); - let max_damage = self - .held() - .and_then(|s| self.res.items().get(&s.item)) - .map_or(0, |i| i.max_damage); - if max_damage > 0 - && let Some(stack) = self.stack_in_mut(slot).as_mut() + /// `Armadillo.mobInteract`: a brush brushes a scute off an adult + /// (`brushOffScute`) and loses 16 durability. + fn interact_armadillo(&mut self, index: usize, item: &str) -> bool { + let m = &self.mobs[index]; + if item != "minecraft:brush" + || m.species() != Species::Armadillo + || !m.alive() + || m.is_baby() { - stack.damage += 1; - if stack.damage >= max_damage { - *self.stack_in_mut(slot) = None; + return false; + } + let (id, at) = (m.id, m.position); + let feet = [at.x, at.y, at.z]; + let tool = self.held().cloned(); + let table = "minecraft:brush/armadillo"; + for d in self.sequence_loot(table, table, tool.as_ref()) { + self.spawn_at_location(at, 0.0, d); + } + self.audio + .play("minecraft:entity.armadillo.brush", Some(feet), 1.0, 1.0); + let ctx = self.who_context(Some(Who::Mob(id)), None); + self.post_game_event("minecraft:entity_interact", feet, ctx); + // ItemStack.hurtAndBreak(16). + if !self.creative + && let Some(stack) = tool + { + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |i| i.max_damage); + if max > 0 { + let loss = self.durability_loss(&stack, 16); + let slot = self.held_slot(); + if let Some(held) = self.stack_in_mut(slot).as_mut() { + held.damage += loss; + if held.damage >= max { + *self.stack_in_mut(slot) = None; + } + } } } + true + } + /// `ItemStack.hurtAndBreak(1, ...)` on the held tool: Unbreaking, break sound and stat. + pub(super) fn damage_held_tool(&mut self) { + self.damage_held(1); } /// Throwables and spawn eggs (SnowballItem/EggItem/EnderpearlItem/SpawnEggItem.use). pub(super) fn throw_item(&mut self, stack: &ItemStack) -> Result { @@ -3370,6 +3738,45 @@ impl Game<'_> { } Ok(true) } + /// `Mob.checkAndHandleImportantInteractions` with a spawn egg of mob + /// `index`'s own kind (`SpawnEggItem.spawnOffspringFromSpawnEgg`): a baby + /// at the mob's feet, taking the parent's variant as `getBreedOffspring` + /// does, and one egg used. False (PASS) when the mob has no baby form. + fn spawn_egg_offspring(&mut self, index: usize) -> bool { + let Some(stack) = self.held().cloned() else { + return false; + }; + let parent = &self.mobs[index]; + if !parent.alive() + || stack.item.strip_suffix("_spawn_egg") != Some(parent.kind.id.as_str()) + || !horizon_client::mobs::drops::can_be_baby(parent.species()) + // WanderingTrader.getBreedOffspring returns null: no offspring, the + // click carries on to trading. + || parent.species() == Species::WanderingTrader + { + return false; + } + let (kind, at) = ( + parent.kind.id.clone(), + [parent.position.x, parent.position.y, parent.position.z], + ); + let (species, variant, color) = + (parent.species(), parent.extra.variant, parent.extra.color); + let target = self.mob_entity(&self.mobs[index]); + let Some(id) = self.spawn_mob(&kind, at, true) else { + return false; + }; + if let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) { + horizon_client::mobs::finalize::set_baby(child, true); + child.extra.variant = variant; + if species == Species::Sheep { + child.extra.color = color; + } + } + self.trigger_item_entity("minecraft:player_interacted_with_entity", &stack, &target); + self.consume_held(); + true + } fn use_spawn_egg(&mut self, stack: &ItemStack) -> Result { let Some(hit) = self.pick() else { return Ok(false); @@ -3501,8 +3908,10 @@ impl Game<'_> { let scale = self.view_scale(); for mob in &self.mobs { let entity_start = out.len(); - // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws. - if mob.invisible { + let outline = self.mob_outline(mob); + // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws (and + // the outline of a glowing mob, LivingEntityRenderer.getRenderType). + if mob.invisible && outline.is_none() { continue; } let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; @@ -3571,9 +3980,18 @@ impl Game<'_> { out, ); self.mob_block_geometry(mob, camera, alpha, packed, out); + if let Some(rgb) = outline { + self.mark_outline(&out[entity_start..], rgb); + if mob.invisible { + out.truncate(entity_start); + continue; + } + } // Glowing outlines and a guardian's beam remain visible independently // of whether the body is hidden behind terrain. - if !mob.glowing && horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none() { + if outline.is_none() + && horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none() + { self.cull_entity_vertices(out, entity_start); } // GuardianRenderer: the laser to the locked target. @@ -3621,7 +4039,15 @@ impl Game<'_> { super::pickups::Taken::Arrow(a) => Some((&**a, super::pickups::position(p, alpha))), _ => None, }); + // A glowing projectile's outline: what it drew up to the next one. + let mut glowing = None; for (a, at) in live.chain(taken) { + if let Some((start, rgb)) = glowing.take() { + self.mark_outline(&out[start..], rgb); + } + if a.id != 0 && self.entity_glowing(a.id) { + glowing = Some((out.len(), super::glowing::team_color(self.mob_team(a.id)))); + } let p = glam::DVec3::from_array(at) - camera; let c = p.as_vec3(); let light = self.world.light( @@ -3750,9 +4176,14 @@ impl Game<'_> { layer: 0, color: 0xFFFF_FFFF, light: packed, + + glint_uv: [0.0, 0.0], }); } } + if let Some((start, rgb)) = glowing { + self.mark_outline(&out[start..], rgb); + } } } /// `Bucketable.getBucketItemStack` and `getPickupSound` of a mob that a water @@ -3822,6 +4253,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), } } /// A generated loot stack as a Horizon item stack. @@ -3841,6 +4273,9 @@ fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack { if let Some(amplifier) = stack.ominous_amplifier.filter(|a| *a > 0) { item.data_mut().ominous_amplifier = Some(amplifier as u8); } + for (id, text) in &stack.names { + item.data_mut().set_loot_name(id, text); + } item } impl Game<'_> { @@ -3884,6 +4319,9 @@ impl Game<'_> { f64::from(y + 1), f64::from(pos[2]) + 0.5, ]; - let _ = self.spawn_mob("minecraft:zombified_piglin", at, false); + // setPortalCooldown: the new piglin does not travel at once. + if let Some(id) = self.spawn_mob("minecraft:zombified_piglin", at, false) { + self.set_portal_cooldown(id); + } } } diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index d66610183..0c58b69f9 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -219,6 +219,7 @@ impl Game<'_> { if let Some(a) = arrow.arrow.as_mut() { a.set_item(ammo); a.set_owner(Some(Who::Player)); + a.fired_from_weapon = Some(weapon.clone()); a.pierce = pierce; } arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0); @@ -235,6 +236,11 @@ impl Game<'_> { .play("minecraft:item.crossbow.shoot", Some(eye), 1.0, pitch); self.damage_held(if rocket { 3 } else { 1 }); } + // CrossbowItem.performShooting: SHOT_CROSSBOW with the crossbow, which + // is an empty stack (no match) when the shots broke it. + if let Some(stack) = self.held().cloned() { + self.trigger_item("minecraft:shot_crossbow", &stack); + } } } diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index dc79bf8c1..1b822430b 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -244,7 +244,8 @@ impl Game<'_> { if on { "visible" } else { "hidden" } ) }; - let remote = self.remote.is_some(); + // `DebugScreenOverlay`: the single-player variants for a local server. + let remote = !self.has_singleplayer_server(); let c = &self.debug_charts; [ format!( @@ -463,7 +464,7 @@ impl Game<'_> { height, self.settings.max_fps, 1000.0 / self.clock.rate(), - self.remote.is_some(), + !self.has_singleplayer_server(), ); draws.push(hud_layout::GuiDraw::Push(vec![hud_layout::PoseOp::Scale( scale, scale, diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 73c6fd4cc..1e69f2c05 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -412,6 +412,8 @@ struct ServerState { paused: bool, /// `broadcast-console-to-ops`. broadcast_console: bool, + /// `op-permission-level`: what `/op` grants (operatorUserPermissions). + op_level: i32, } /// The dedicated-only commands' replies vanilla sends with `broadcast` @@ -573,6 +575,14 @@ impl Game<'_> { // DedicatedServer.initServer: worldData.setGameType; forceDifficulty. self.set_default_game_mode(game_mode); self.ui.difficulty = props.difficulty as u8; + // DedicatedServer.initServer: a legacy `announce-player-achievements` + // sets the show_advancement_messages rule once, as the file is read. + if let Some(announce) = props.announce_player_achievements { + self.ui.rules.set( + "show_advancement_messages", + horizon_client::gamerules::Value::Bool(announce), + ); + } self.settings.render_distance = props.view_distance.clamp(2, 32); self.settings.simulation_distance = props.simulation_distance.clamp(2, 32); self.streaming.radius = self.settings.render_distance; @@ -685,6 +695,7 @@ impl Game<'_> { ticks: Default::default(), paused: false, broadcast_console: props.broadcast_console_to_ops, + op_level: props.op_permission_level, }; let pause_after = props.pause_when_empty_seconds * 20; let idle_timeout = props.player_idle_timeout; @@ -946,7 +957,7 @@ impl Game<'_> { let Some(user) = self.resolve(rest[0]) else { return; }; - let level = 4; + let level = state.op_level; let changed = { let mut l = state.lists.lock().unwrap(); if command == "op" { @@ -972,6 +983,10 @@ impl Game<'_> { self.console_reply(Text::translate(key, &[lit(&user.name)])); let lists = state.lists.clone(); self.sync_ops(&lists); + // DeOpCommands.deopPlayers. + if command == "deop" && changed { + self.kick_unlisted_players(&lists); + } } "whitelist" => self.console_whitelist(state, &rest), "ban" if !rest.is_empty() => { @@ -1183,6 +1198,7 @@ impl Game<'_> { ["on"] | ["off"] => { let on = rest[0] == "on"; let mut l = state.lists.lock().unwrap(); + let turned_on = on && !l.use_whitelist; let key = match (on, l.use_whitelist) { (true, true) => "commands.whitelist.alreadyOn", (true, false) => "commands.whitelist.enabled", @@ -1193,6 +1209,10 @@ impl Game<'_> { drop(l); self.store_property("white-list", on.to_string()); self.console_reply(Text::translate(key, &[])); + if turned_on { + let lists = state.lists.clone(); + self.kick_unlisted_players(&lists); + } } ["list"] => { let names: Vec = state @@ -1216,6 +1236,8 @@ impl Game<'_> { ["reload"] => { let _ = state.lists.lock().unwrap().white.load(); self.console_reply(Text::translate("commands.whitelist.reloaded", &[])); + let lists = state.lists.clone(); + self.kick_unlisted_players(&lists); } ["add", name] | ["remove", name] => { let Some(user) = self.resolve(name) else { @@ -1241,6 +1263,10 @@ impl Game<'_> { Vec::new() }; self.console_reply(Text::translate(key, &args)); + if ok && rest[0] == "remove" { + let lists = state.lists.clone(); + self.kick_unlisted_players(&lists); + } } _ => self.console_reply(Text::translate("command.unknown.argument", &[])), } @@ -1256,6 +1282,38 @@ impl Game<'_> { } } + /// MinecraftServer.kickUnlistedPlayers: with `enforce-whitelist` and the + /// whitelist on, whoever is online and not on the whitelist file is + /// disconnected (operators are not spared here). + fn kick_unlisted_players(&mut self, lists: &Arc>) { + let unlisted: Vec = { + let l = lists.lock().unwrap(); + let Some(host) = self.lan.as_ref() else { + return; + }; + if !(l.enforce_whitelist && l.use_whitelist) { + return; + } + host.hub + .guests + .iter() + .filter(|g| { + !l.white.contains(&NameAndId { + id: g.uuid, + name: g.name.clone(), + }) + }) + .map(|g| g.uuid) + .collect() + }; + for uuid in unlisted { + self.kick_uuid( + uuid, + translatable("multiplayer.disconnect.not_whitelisted", &[]), + ); + } + } + fn kick_uuid(&mut self, uuid: u128, reason: Tag) { if let Some(h) = self.lan.as_mut() { let conns: Vec = h diff --git a/crates/horizon-client/src/game/deflect.rs b/crates/horizon-client/src/game/deflect.rs index a08de87b3..088374a34 100644 --- a/crates/horizon-client/src/game/deflect.rs +++ b/crates/horizon-client/src/game/deflect.rs @@ -120,6 +120,11 @@ impl Game<'_> { p.guest = guest; // Not into the one who turned it on its way out. p.left_owner = false; + // `AbstractHurtingProjectile.onDeflection` by an attack, and the + // `needsSync` that `AIM_DEFLECT` sets: a server's players see it turn + // at once, not at the fireball's next update ten ticks later. + p.acceleration = 0.1; + p.needs_sync = true; self.reset_attack_strength(); self.swing_arm(); let from = self diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index a0a9bfd93..a34433573 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1548,6 +1548,7 @@ impl Game<'_> { return Ok((Some(stack), FAIL)); }; let target = (placed.x, placed.y, placed.z); + let state = self.apply_item_block_state([target.0, target.1, target.2], state, &stack)?; if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { self.world.block_entities.insert(target, entity); self.apply_placed_item([target.0, target.1, target.2], &stack, false); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 4f6cdb0b3..192b72552 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -27,6 +27,8 @@ pub(super) const SPECIAL: u32 = u32::MAX - 4096; const CRYSTAL_IDS: u32 = SPECIAL + 16; const FIGHT_FILE: &str = "data/minecraft/ender_dragon_fight.dat"; const MAX_HEALTH: f32 = 200.0; +/// `Mob.getAmbientSoundInterval`. +const AMBIENT_INTERVAL: i32 = 80; #[derive(Default)] pub(super) struct Fight { @@ -48,6 +50,9 @@ pub(super) struct Fight { respawn: Option<(Respawn, i32)>, /// The four crystals on the exit portal driving the respawn. respawn_crystals: Vec, + /// The player behind the crystal blast under way, whose `explosion` + /// damage source names them (`EndCrystal.hurtServer`). + blast_by: Option, dirty: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -262,6 +267,9 @@ pub(super) struct Dragon { /// only damage above the last hit lands, and only the excess. invulnerable: i32, last_hurt: f32, + /// `lastHurtByPlayer` with its 100 tick memory: the player credited with + /// the kill, and the dragon tick of their last hit. + hurt_by_player: Option<(FightWho, i32)>, pub death_time: i32, pub flap: f32, pub old_flap: f32, @@ -270,6 +278,8 @@ pub(super) struct Dragon { flame_count: i32, sitting_damage: f32, growl: i32, + /// `Mob.ambientSoundTime`. + ambient_time: i32, ticks: i32, /// DragonFlightHistory: (y, yRot) samples, newest at `head`. history: [(f64, f32); 64], @@ -291,11 +301,11 @@ pub(super) enum FightWho { } /// A player in the End as the dragon sees it. #[derive(Clone, Copy, Debug)] -struct FightPlayer { - who: FightWho, - position: Vec3, - bounds: Aabb, - alive: bool, +pub(super) struct FightPlayer { + pub(super) who: FightWho, + pub(super) position: Vec3, + pub(super) bounds: Aabb, + pub(super) alive: bool, creative: bool, spectator: bool, } @@ -385,6 +395,7 @@ impl Dragon { hurt_time: 0, invulnerable: 0, last_hurt: 0.0, + hurt_by_player: None, death_time: 0, flap: 0.0, old_flap: 0.0, @@ -397,6 +408,7 @@ impl Dragon { flame_count: 0, sitting_damage: 0.0, growl: 100, + ambient_time: 0, ticks: 0, history: [(position.y, yaw); 64], head: 0, @@ -426,6 +438,10 @@ impl Dragon { pub fn alive(&self) -> bool { self.health > 0.0 } + /// `isDeadOrDying` for the killing blow: the dying flight, or no health. + fn down(&self) -> bool { + matches!(self.phase, Phase::Dying { .. }) || !self.alive() + } fn part_box(&self, i: usize) -> Aabb { let (w, h) = PART_SIZES[i]; let p = self.parts[i].0; @@ -693,7 +709,7 @@ impl Game<'_> { } /// The players in the level the dragon sees (`level.players()`): the /// window's own, then every guest in the level. - fn fight_players(&self) -> Vec { + pub(super) fn fight_players(&self) -> Vec { let mut out = Vec::new(); if let Some(p) = self.player.as_ref() { out.push(FightPlayer { @@ -722,7 +738,7 @@ impl Game<'_> { } /// Run `f` as the fight's player `who` (a guest's turn, its knockback /// sent to its client). - fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) { + pub(super) fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) { match who { FightWho::Host => f(self), FightWho::Guest(conn) => { @@ -893,8 +909,12 @@ impl Game<'_> { .any(|p| p.distance_squared(c.position) < 0.01); if damage == CrystalDamage::Direct { let at = [c.position.x, c.position.y, c.position.z]; + // The blast's damage source carries the player, so the dragon + // remembers them before the blast can kill it. + self.fight.blast_by = by; let _ = self.server_explode(at, 6.0, super::explosion::BlockInteraction::Destroy, false); + self.fight.blast_by = None; } if respawn_crystal { self.abort_respawn(); @@ -905,7 +925,7 @@ impl Game<'_> { if let Some(d) = self.dragon.as_mut() { if d.nearest_crystal == Some(index) { d.nearest_crystal = None; - self.hurt_dragon(0, 10.0, true, false); + self.hurt_dragon(0, 10.0, true, by, false); } else if let Some(n) = d.nearest_crystal.as_mut() && *n > index { @@ -977,18 +997,46 @@ impl Game<'_> { self.destroy_crystal(index, by, CrystalDamage::Direct); Hurt::Landed { full: true } } else if id >= SPECIAL { - self.hurt_dragon((id - SPECIAL) as usize, amount, by_player, arrow) + let by = by_player.then(|| self.acting_player()); + self.hurt_dragon((id - SPECIAL) as usize, amount, by_player, by, arrow) } else { Hurt::Refused } } /// `EnderDragon.hurt(part, source, damage)` on the dragon in the level. - fn hurt_dragon(&mut self, part: usize, damage: f32, counts: bool, arrow: bool) -> Hurt { + /// `by` is the player behind the hit, remembered for the kill credit. + fn hurt_dragon( + &mut self, + part: usize, + damage: f32, + counts: bool, + by: Option, + arrow: bool, + ) -> Hurt { let Some(d) = self.dragon.as_mut() else { return Hurt::Refused; }; + let was_down = d.down(); + let (cooldown, last_hurt) = (d.invulnerable, d.last_hurt); let hurt = d.hurt(part, damage, counts, arrow); + // LivingEntity.hurtServer: damage that is applied sets lastHurtByPlayer + // (100 ticks); a hit the damage cooldown absorbs returns before that. + if counts + && matches!(hurt, Hurt::Landed { .. }) + && (d.invulnerable != cooldown || d.last_hurt != last_hurt) + && let Some(who) = by + { + d.hurt_by_player = Some((who, d.ticks)); + } + if !was_down && d.down() { + self.credit_dragon_kill(); + } + let Some(d) = self.dragon.as_mut() else { + return hurt; + }; if hurt == (Hurt::Landed { full: true }) { + // Mob.playHurtSound: the ambient sound clock starts again. + d.ambient_time = -AMBIENT_INTERVAL; let at = [d.position.x, d.position.y, d.position.z]; let pitch = 0.8 + self.world.random.next_float() * 0.3; self.audio @@ -996,6 +1044,47 @@ impl Game<'_> { } hurt } + /// `LivingEntity.die`: `getKillCredit().awardKillScore`, for the player + /// who hurt the dragon within the last 100 ticks. A guest's kill is + /// theirs: their statistics, scores and advancements. + fn credit_dragon_kill(&mut self) { + let Some(d) = self.dragon.as_ref() else { + return; + }; + let Some((who, _)) = d.hurt_by_player.filter(|(_, hit)| d.ticks - hit <= 100) else { + return; + }; + let view = horizon_client::advancements::EntityView { + kind: "minecraft:ender_dragon".to_owned(), + position: [d.position.x, d.position.y, d.position.z], + ..Default::default() + }; + let id = d.id; + let guest = match who { + FightWho::Guest(conn) if self.lan_acting.is_none() => Some(conn), + _ => None, + }; + let credited = guest.is_some_and(|conn| { + let Some(mut host) = self.lan.take() else { + return false; + }; + let done = self + .as_guest(&mut host, conn, |g| g.award_dragon_kill(id, &view)) + .is_some(); + self.lan = Some(host); + done + }); + if !credited { + self.award_dragon_kill(id, &view); + } + } + /// `ServerPlayer.awardKillScore` for the dragon, on the killer's state. + fn award_dragon_kill(&mut self, id: u32, view: &horizon_client::advancements::EntityView) { + self.stats.add("killed", "minecraft:ender_dragon", 1); + self.stats.custom("mob_kills", 1); + self.score_player_killed(super::commands::Target::Mob(id)); + self.trigger_entity("minecraft:player_killed_entity", "entity", view); + } /// Player melee on the dragon's parts or a crystal under the crosshair. /// The dragon part under the crosshair within reach: its id and distance. pub(super) fn dragon_hit(&self) -> Option<(u32, f64)> { @@ -1376,7 +1465,16 @@ impl Game<'_> { } } let d2 = (pp.x - pos.x).powi(2) + (pp.y - pos.y).powi(2) + (pp.z - pos.z).powi(2); - if d2 < 4096.0 { + // Entity.hasLineOfSight: eye to eye (the dragon's eye is 0.85 of + // its 8 block height), blocks only. + let sees = d2 < 4096.0 && { + let eye = Vec3::new(pos.x, pos.y + 6.8, pos.z); + let target_eye = + tracked.map_or(pp.y + 1.62, |p| p.bounds.max_position().y - 0.18); + self.mob_world_base(&[]) + .line_of_sight(eye, Vec3::new(pp.x, target_eye, pp.z)) + }; + if sees { *charge += 1; let d = self.dragon.as_ref().expect("dragon"); let r = d.yaw.to_radians(); @@ -1568,6 +1666,7 @@ impl Game<'_> { age: 0, duration: 200, from_dragon: true, + potion: None, }); } } @@ -1660,6 +1759,24 @@ impl Game<'_> { self.tick_dragon_death(); return; } + // Mob.baseTick: the ambient sound, rarer right after one. + let roll = d.random.next_int_bound(1000).unwrap_or(999); + let waited = d.ambient_time; + d.ambient_time += 1; + if roll < waited { + d.ambient_time = -AMBIENT_INTERVAL; + let at = [d.position.x, d.position.y, d.position.z]; + // LivingEntity.getVoicePitch, from the dragon's own random. + let r = &mut d.random; + let pitch = (r.next_float() - r.next_float()) * 0.2 + 1.0; + self.audio.play( + "minecraft:entity.ender_dragon.ambient", + Some(at), + 5.0, + pitch, + ); + } + let d = self.dragon.as_mut().expect("dragon"); // Flapping, growls and the flap sound. let flap_was = (d.old_flap * std::f32::consts::TAU).cos(); let v = d.velocity; @@ -2080,12 +2197,18 @@ impl Game<'_> { age: 0, duration: 600, from_dragon: false, + potion: None, }); - self.audio.play( - "minecraft:entity.dragon_fireball.explode", - Some([next.x, next.y, next.z]), - 1.0, - 1.0, + // DragonFireball.onHit: level event 2006 (the burst of dragon + // breath and the explosion sound) at its block position. + self.level_event_at( + 2006, + [ + next.x.floor() as i32, + next.y.floor() as i32, + next.z.floor() as i32, + ], + 1, ); return false; } @@ -2112,6 +2235,10 @@ impl Game<'_> { let mut harmed: Vec<(FightWho, f32)> = Vec::new(); let mut clouds = std::mem::take(&mut self.breath_clouds); clouds.retain_mut(|c| { + // Lingering potions' clouds tick with the potions. + if c.potion.is_some() { + return true; + } c.age += 1; if c.age >= c.duration { return false; @@ -2129,10 +2256,12 @@ impl Game<'_> { c.at[1], c.at[2] + f64::from(a.sin() * d), ]; - self.particles.add( + self.particles.add_with( &ParticleOptions::simple(ParticleType::DragonBreath), at, [0.0, 0.0, 0.0], + false, + true, ); } // AreaEffectCloud: after its 20-tick wait, every 20 ticks per entity. @@ -2259,8 +2388,22 @@ pub(super) struct Breath { pub(super) at: [f64; 3], pub(super) radius: f32, pub(super) age: i32, - duration: i32, - from_dragon: bool, + pub(super) duration: i32, + pub(super) from_dragon: bool, + /// A lingering potion's cloud (`ThrownLingeringPotion`): what it applies. + pub(super) potion: Option, +} +impl Breath { + /// `AreaEffectCloud.isWaiting`: before its wait time (20 ticks, 10 for a + /// lingering potion's). + pub(super) fn waiting(&self) -> bool { + self.age + < if self.potion.is_some() { + super::potions::LINGERING_WAIT + } else { + 20 + } + } } impl Game<'_> { /// `EnderDragonRenderer` and `EnderDragonModel.setupAnim`. @@ -2487,6 +2630,8 @@ impl Game<'_> { layer: 2, color: c, light: 0, + + glint_uv: [0.0, 0.0], }); } } @@ -2552,6 +2697,8 @@ impl Game<'_> { layer: 6, color: c, light: wrap_light, + + glint_uv: [0.0, 0.0], }); } (last_sin, last_cos, last_u) = (sin, cos, uu); @@ -2597,6 +2744,8 @@ impl Game<'_> { layer: 0, color: 0xFFFF_FFFF, light: 240 | 240 << 8, + + glint_uv: [0.0, 0.0], }); } } @@ -2722,8 +2871,9 @@ impl Game<'_> { let (lo, hi) = (b.min_position(), b.max_position()); self.seen_percent(center, [lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]) }); + let by = self.fight.blast_by; for (part, amount) in hits { - self.hurt_dragon(part, amount, true, false); + self.hurt_dragon(part, amount, true, by, false); } } } diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index b24a62520..5688a3226 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -157,8 +157,10 @@ impl Game<'_> { items: Some(self.res.items()), ..Default::default() }; - // minecraft:post_attack ignite effects of the attacker's weapon (fire aspect). + // minecraft:post_attack effects of the attacker's weapon on the victim: + // ignite (fire aspect) and apply_mob_effect (bane of arthropods). let mut ignite = 0.0f32; + let mut mob_effects = Vec::new(); for (id, level) in held.enchantments() { let Some(def) = self.res.stations().enchantments.get(id) else { continue; @@ -168,24 +170,33 @@ impl Game<'_> { .into_iter() .flatten() { - if effect["enchanted"] == "attacker" - && effect["affected"] == "victim" - && effect["effect"]["type"] == "minecraft:ignite" + let e = &effect["effect"]; + let kind_of = e["type"].as_str(); + if effect["enchanted"] != "attacker" + || effect["affected"] != "victim" + || !matches!( + kind_of, + Some("minecraft:ignite" | "minecraft:apply_mob_effect") + ) { - let mut random = self.world.random.clone(); - let ok = effect.get("requirements").is_none_or(|r| { - self.res - .stations() - .enchantments - .condition(r, *level, &ctx, &mut random) - }); - self.world.random = random; - if ok { - ignite = ignite.max(horizon_client::enchant::level_value( - &effect["effect"]["duration"], - *level, - )); - } + continue; + } + let mut random = self.world.random.clone(); + let ok = effect.get("requirements").is_none_or(|r| { + self.res + .stations() + .enchantments + .condition(r, *level, &ctx, &mut random) + }); + self.world.random = random; + if !ok { + continue; + } + if kind_of == Some("minecraft:ignite") { + ignite = + ignite.max(horizon_client::enchant::level_value(&e["duration"], *level)); + } else { + mob_effects.push((e.clone(), *level)); } } } @@ -195,8 +206,41 @@ impl Game<'_> { { m.ignite_for_ticks((ignite * 20.0) as i32); } + for (effect, level) in mob_effects { + self.apply_mob_effect(mob, &effect, level); + } self.post_attack_bursts(&held, &kind); } + /// `ApplyMobEffect.apply`: one of `to_apply` (a single id or a list) for a + /// random duration and amplifier between the level-based bounds. + fn apply_mob_effect(&mut self, mob: usize, effect: &serde_json::Value, level: u32) { + use horizon_client::enchant::level_value; + let Some(m) = self.mobs.get_mut(mob) else { + return; + }; + let ids: Vec<&str> = match &effect["to_apply"] { + serde_json::Value::String(id) => vec![id.as_str()], + serde_json::Value::Array(list) => list.iter().filter_map(|v| v.as_str()).collect(), + _ => Vec::new(), + }; + if ids.is_empty() { + return; + } + // HolderSet.getRandomElement, then Mth.randomBetween for both values. + let pick = m.random.next_int_bound(ids.len() as i32).unwrap_or(0) as usize; + let mut between = |min: &str, max: &str| { + let (lo, hi) = ( + level_value(&effect[min], level), + level_value(&effect[max], level), + ); + m.random.next_float() * (hi - lo) + lo + }; + let ticks = (between("min_duration", "max_duration") * 20.0).round() as i32; + let amplifier = (between("min_amplifier", "max_amplifier").round() as i32).max(0); + if let Some(id) = super::potions::mob_effect_id(ids[pick]) { + m.add_effect(id, ticks, amplifier); + } + } /// `minecraft:post_attack` explode effects on the attacker (wind burst): /// a burst at the player's feet that only knocks back and triggers /// blocks (`ExplodeEffect` with `block_interaction: trigger`). @@ -307,8 +351,10 @@ impl Game<'_> { continue; } hits.push(1.0 + self.world.random.next_float() * 4.0); + // ChangeItemDamage -> ItemStack.hurtAndBreak: unbreaking applies. + let loss = self.durability_loss(&stack, 2); if let Some(s) = self.armor[slot].as_mut() { - s.damage += 2; + s.damage += loss; if self .res .items() diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index bb0f3789d..41c4e1628 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -5,6 +5,7 @@ use super::{Dim, Game}; use horizon_client::{ Result, + containers::{BlockEntity, EndGateway}, environment::Environment, items::ItemStack, mesher::Vertex, @@ -27,14 +28,64 @@ const GATEWAY_Y: i32 = 75; const GATEWAY_FILE: &str = "horizon-end-gateways.json"; /// A gateway teleport waiting for its destination chunks. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum GatewayJob { /// TheEndGatewayBlockEntity.findOrCreateValidTeleportPos from this gateway. - Find { gateway: [i32; 3] }, + /// `exact` is the gateway's own `ExactTeleport`, read while its chunk is loaded. + Find { gateway: [i32; 3], exact: bool }, /// A known exit (exact, or findExitPosition around it). Known { exit: [i32; 3], exact: bool }, } +impl GatewayJob { + /// TheEndGatewayBlockEntity.getPortalPosition, with legacy save fallbacks. + fn for_gateway( + gateway: [i32; 3], + entity: Option<&BlockEntity>, + legacy: Option<([i32; 3], bool)>, + ) -> Self { + let configured = match entity { + Some(BlockEntity::EndGateway(g)) => g.exit_portal.map(|exit| (exit, g.exact_teleport)), + _ => None, + }; + match configured.or(legacy) { + Some((exit, exact)) => Self::Known { exit, exact }, + // Worldgen return gateways (end_gateway_return) lead exactly to the End spawn. + None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => Self::Known { + exit: END_SPAWN, + exact: true, + }, + None => Self::Find { + gateway, + exact: exact_teleport(entity), + }, + } + } +} + +/// `TheEndGatewayBlockEntity.exactTeleport` of the block entity at a gateway +/// (false without one). +fn exact_teleport(entity: Option<&BlockEntity>) -> bool { + matches!(entity, Some(BlockEntity::EndGateway(g)) if g.exact_teleport) +} + +/// Moves an exit that only the side file knew into the gateway's block entity, unless the block +/// entity has its own; true when it took the saved one. +fn adopt_saved_exit(entity: &mut EndGateway, (exit, exact): ([i32; 3], bool)) -> bool { + if entity.exit_portal.is_some() { + return false; + } + entity.exit_portal = Some(exit); + entity.exact_teleport = exact; + true +} + +/// The end of `getPortalPosition`: the exit itself when the teleport is exact, +/// else the spot [`Game::resolve_gateway`] finds around it (`findExitPosition`). +fn exit_target(exit: [i32; 3], exact: bool, find: impl FnOnce([i32; 3]) -> [i32; 3]) -> [i32; 3] { + if exact { exit } else { find(exit) } +} + #[derive(Default)] pub(super) struct EndState { /// Gateway position -> (exit, exact teleport); loaded lazily from the save. @@ -247,6 +298,8 @@ impl Game<'_> { layer: 2, color, light: 0, + + glint_uv: [0.0, 0.0], }); } } @@ -606,7 +659,9 @@ impl Game<'_> { /// EnderDragonFight without a dragon: once the centre of the main island /// is loaded, place the active exit portal (EndPodiumFeature) and the - /// first gateway (spawnNewGateway) if the portal is not there yet. + /// first gateway (spawnNewGateway) if the portal is not there yet. Like + /// scanState and spawnExitPortal, only while the fight has no exit portal + /// location: a podium that is later broken stays broken. fn ensure_exit_portal(&mut self) -> Result<()> { if self.travelling.is_some() || !(-1..=0).all(|cz| (-1..=0).all(|cx| self.streaming.is_lit(cx, cz))) @@ -616,8 +671,14 @@ impl Game<'_> { } let won = self.fight.previously_killed; let gateway = self.first_gateway(); - if (0..256).any(|y| &*self.block_name([0, y, 0]) == "minecraft:bedrock") { - // The podium exists; the gateway may have been out of range when it was placed. + if self.exit_portal().is_none() { + // findExitPortal remembers the location of a podium that is already there. + if let Some(level) = self.podium_level() { + self.set_exit_portal([0, level, 0]); + } + } + if self.exit_portal().is_some() { + // The gateway may have been out of range when it was placed. if won && self.world.loaded(gateway[0], gateway[2]) && &*self.block_name(gateway) != "minecraft:end_gateway" @@ -648,17 +709,40 @@ impl Game<'_> { } Ok(()) } + /// The portal level of the podium around the centre column, read from the + /// bedrock that EndPodiumFeature places (rim at the portal level, disc + /// below it, the torch column) so a broken column does not hide it. + fn podium_level(&self) -> Option { + let mut offsets: Vec<[i32; 3]> = (0..4).map(|dy| [0, dy, 0]).collect(); + for z in -4..=4i32 { + for x in -4..=4i32 { + let flat = f64::from(x * x + z * z); + if (6.25..12.25).contains(&flat) { + offsets.push([x, 0, z]); + } else if flat + 1.0 < 6.25 { + offsets.push([x, -1, z]); + } + } + } + (1..253) + .map(|y| { + let score = offsets + .iter() + .filter(|o| &*self.block_name([o[0], y + o[1], o[2]]) == "minecraft:bedrock") + .count(); + (score, y) + }) + .filter(|&(score, _)| score >= 3) + .max() + .map(|(_, y)| y) + } /// `spawnExitPortal(true)` after the dragon dies. pub(super) fn activate_exit_portal(&mut self) -> Result<()> { let origin = match self.exit_portal() { Some(o) => o, None => { - // The rim's level: the top of the bedrock column minus three. - let top = (0..256) - .rev() - .find(|&y| &*self.block_name([0, y, 0]) == "minecraft:bedrock") - .unwrap_or(64); - [0, top - 3, 0] + // The rim's level, found without assuming the centre column is intact. + [0, self.podium_level().unwrap_or(61), 0] } }; self.place_podium(origin, true) @@ -761,6 +845,11 @@ impl Game<'_> { } } } + self.world + .block_entities + .get_or_insert_with((origin[0], origin[1], origin[2]), || { + BlockEntity::EndGateway(Default::default()) + }); Ok(()) } @@ -782,8 +871,7 @@ impl Game<'_> { self.end.exits.as_mut().expect("loaded exits") } - fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { - self.gateway_exits().insert(gateway, (exit, exact)); + fn save_gateway_exits(&mut self) -> Result<()> { let list: Vec<_> = self .gateway_exits() .iter() @@ -795,6 +883,35 @@ impl Game<'_> { Ok(()) } + /// Drops a gateway's entry from the side file: its block entity is the source of truth. + fn forget_gateway_exit(&mut self, gateway: [i32; 3]) -> Result<()> { + if self.gateway_exits().remove(&gateway).is_some() { + self.save_gateway_exits()?; + } + Ok(()) + } + + fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { + // TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit). + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + // The gateway's chunk can be unloaded by now (travel waits for the destination): the + // exit then waits in the side file until the gateway is used again (`gateway_job`). + if self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + g.exit_portal = Some(exit); + g.exact_teleport = exact; + self.world.modified.insert(chunk); + return self.forget_gateway_exit(gateway); + } + self.gateway_exits().insert(gateway, (exit, exact)); + self.save_gateway_exits() + } + /// EndGatewayBlock.entityInside and TheEndGatewayBlockEntity.getPortalPosition: /// travel within the End, waiting for the destination chunks to load. fn enter_gateway(&mut self, gateway: [i32; 3]) -> Result<()> { @@ -814,25 +931,39 @@ impl Game<'_> { /// its exit, or the search for one, and the spot to load before either /// is resolved ([`Game::resolve_gateway`]). pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) { - let known = self.gateway_exits().get(&gateway).copied(); - let job = match known { - Some((exit, exact)) => GatewayJob::Known { exit, exact }, - // Worldgen return gateways (end_gateway_return) lead exactly to the End spawn. - None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => { - GatewayJob::Known { - exit: END_SPAWN, - exact: true, - } + let mut known = self.gateway_exits().get(&gateway).copied(); + // Once the gateway's chunk is loaded its block entity is the source of truth: an exit the + // side file kept for it moves there, and the entry is dropped, so removing or replacing + // the exit (`/data remove block`) is not undone by an old entry. + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + if let Some(saved) = known + && self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + if adopt_saved_exit(g, saved) { + self.world.modified.insert(chunk); } - None => GatewayJob::Find { gateway }, - }; + known = None; + let _ = self.forget_gateway_exit(gateway); + } + let job = GatewayJob::for_gateway( + gateway, + self.world + .block_entities + .get(&(gateway[0], gateway[1], gateway[2])), + known, + ); let destination = match job { GatewayJob::Known { exit, .. } => Vec3::new( f64::from(exit[0]) + 0.5, f64::from(exit[1]), f64::from(exit[2]) + 0.5, ), - GatewayJob::Find { gateway } => { + GatewayJob::Find { gateway, .. } => { let d = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2])) .normalize_or_zero() * 1024.0; @@ -889,12 +1020,10 @@ impl Game<'_> { [p[0], p[1] + 1, p[2]] }; match job { - GatewayJob::Known { exit, exact } => Ok(bottom_center(if exact { - exit - } else { - find_exit(self, exit) - })), - GatewayJob::Find { gateway } => { + GatewayJob::Known { exit, exact } => Ok(bottom_center(exit_target(exit, exact, |e| { + find_exit(self, e) + }))), + GatewayJob::Find { gateway, exact } => { // findExitPortalXZPosTentative over the loaded chunks. let dir = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2])) .normalize_or_zero(); @@ -954,8 +1083,11 @@ impl Game<'_> { let exit = [tallest[0], tallest[1] + 10, tallest[2]]; self.place_gateway(exit)?; self.set_gateway_exit(exit, gateway, false)?; - self.set_gateway_exit(gateway, exit, false)?; - Ok(bottom_center(find_exit(self, exit))) + // setExitPosition keeps the gateway's own exactTeleport. + self.set_gateway_exit(gateway, exit, exact)?; + Ok(bottom_center(exit_target(exit, exact, |e| { + find_exit(self, e) + }))) } } } @@ -1247,8 +1379,103 @@ impl Game<'_> { layer: 0, color: 0xFFFF_FFFF, light: full, + + glint_uv: [0.0, 0.0], }); } } } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::containers::EndGateway; + + #[test] + fn a_saved_exit_moves_into_a_gateway_without_one() { + let saved = ([8, 100, 0], true); + let mut bare = EndGateway::default(); + assert!(adopt_saved_exit(&mut bare, saved)); + assert_eq!(bare.exit_portal, Some([8, 100, 0])); + assert!(bare.exact_teleport); + // The block entity's own exit wins over a stale entry. + let mut own = EndGateway { + exit_portal: Some([1, 2, 3]), + ..Default::default() + }; + assert!(!adopt_saved_exit(&mut own, saved)); + assert_eq!(own.exit_portal, Some([1, 2, 3])); + assert!(!own.exact_teleport); + } + + #[test] + fn a_new_exit_keeps_the_gateways_exact_teleport() { + let exact = BlockEntity::EndGateway(EndGateway { + exact_teleport: true, + ..Default::default() + }); + let plain = BlockEntity::EndGateway(EndGateway::default()); + assert!(exact_teleport(Some(&exact))); + assert!(!exact_teleport(Some(&plain))); + assert!(!exact_teleport(None)); + assert!(!exact_teleport(Some(&BlockEntity::DaylightDetector))); + let exit = [8, 100, 0]; + // Exact: the exit itself, nothing is searched for. + assert_eq!(exit_target(exit, true, |_| panic!("searched")), exit); + assert_eq!( + exit_target(exit, false, |e| [e[0], e[1] + 11, e[2]]), + [8, 111, 0] + ); + } + + #[test] + fn end_gateway_job_prefers_block_entity_then_legacy_then_heuristic() { + let gateway = [702, 100, 0]; + let exit = [8, 100, 0]; + for exact in [true, false] { + let entity = BlockEntity::EndGateway(EndGateway { + exit_portal: Some(exit), + exact_teleport: exact, + ..Default::default() + }); + assert_eq!( + GatewayJob::for_gateway(gateway, Some(&entity), Some((END_SPAWN, !exact))), + GatewayJob::Known { exit, exact }, + ); + } + let empty = BlockEntity::EndGateway(EndGateway::default()); + for entity in [None, Some(&empty)] { + assert_eq!( + GatewayJob::for_gateway(gateway, entity, Some((exit, false))), + GatewayJob::Known { exit, exact: false } + ); + assert_eq!( + GatewayJob::for_gateway(gateway, entity, None), + GatewayJob::Known { + exit: END_SPAWN, + exact: true + } + ); + let nearby = [96, 75, 0]; + let exact = BlockEntity::EndGateway(EndGateway { + exact_teleport: true, + ..Default::default() + }); + assert_eq!( + GatewayJob::for_gateway(nearby, Some(&exact), None), + GatewayJob::Find { + gateway: nearby, + exact: true + } + ); + assert_eq!( + GatewayJob::for_gateway(nearby, entity, None), + GatewayJob::Find { + gateway: nearby, + exact: false + } + ); + } + } +} diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index b2191aa9f..88ef4263a 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -307,6 +307,12 @@ impl Game<'_> { ) { outcome = o; + // dealDefaultKnockback's `indicateDamage` points at the blast + // (the source position), not the no-direction fallback. + if o.knockback && o.blocked <= 0.0 { + p.health + .indicate_damage(center[0] - feet[0], center[2] - feet[2], p.yaw); + } } if !spectator && !(creative && flying) { p.velocity = Vec3::new( @@ -394,7 +400,14 @@ impl Game<'_> { // it kills drop its charged-creeper loot (`Creeper.killedEntity`). let source = horizon_client::mobs::Damage { kind: horizon_client::mobs::DamageKind::Explosion, - attacker: exploding.map(horizon_client::mobs::Who::Mob), + // A projectile's owner (`getIndirectSourceEntity`), else + // the exploding mob itself. + attacker: self + .combat + .explosion_owner + .or(exploding) + .filter(|&o| o != m.id) + .map(horizon_client::mobs::Who::Mob), from: Some(center), }; if hurtable && !m.damage(damage(dist, exposure), source) { @@ -490,6 +503,15 @@ impl Game<'_> { ); } } + /// Runs an explosion whose source empties the hives it destroys + /// (`BeehiveBlock.getDrops`: primed TNT, creeper, wither skull, wither, + /// TNT minecart). + pub(super) fn with_hive_emptying_blast(&mut self, blast: impl FnOnce(&mut Self) -> R) -> R { + self.combat.hive_emptying_blast = true; + let result = blast(self); + self.combat.hive_emptying_blast = false; + result + } /// `Level.explode` on the server: positions, entities, blocks, fire; then /// the client's explosion sound. pub(super) fn server_explode( @@ -606,6 +628,22 @@ impl Game<'_> { // Block.onExplosionHit: the drops copy from the block entity, which // then spills its contents as the block turns to air. let key = (pos[0], pos[1], pos[2]); + let is_hive = matches!(&*name, "minecraft:beehive" | "minecraft:bee_nest"); + // BeehiveBlock.getDrops: the bees of a hive blown up by TNT, a + // creeper, a wither skull, a wither or a TNT minecart come out. + if is_hive && self.combat.hive_emptying_blast { + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()); + self.empty_hive( + pos, + horizon_client::beehive::facing_step(facing.as_deref()), + horizon_client::beehive::Release::Emergency, + ); + } if let Some(entity) = self.world.block_entities.get(&key).cloned() { let custom = self.world.block_names.get(&key).cloned(); self.pending.record(pos, &entity, &name, custom); @@ -638,6 +676,10 @@ impl Game<'_> { } self.pending.clear(pos); self.level_set(pos, self.world.air)?; + // BeehiveBlock.onExplosionHit: the bees about turn on the player. + if is_hive { + self.anger_nearby_bees(pos); + } // TntBlock.wasExploded: new PrimedTnt (its push drawn first), then // getRandomShortFuse(80); no game event. if is_tnt && self.ui.rules.bool("tnt_explodes") { diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 5aa540fcd..f66fd4d3a 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -62,11 +62,56 @@ impl Rocket { item, } } - /// One tick of a server's client: the previous position, then `step`. - pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + /// One tick of a server's client: the rocket flies on by itself between + /// the server's updates (a rocket that follows an entity is placed by the + /// caller). + pub(super) fn remote_step(&mut self, scene: &mut SceneCollisions) { self.previous = self.position; + if self.attached_to.is_none() { + self.free_flight(scene); + } self.life += 1; - self.position = step(self.position); + } + /// `FireworkRocketEntity.tick` for a rocket attached to no entity: speed + /// up (an angled one keeps its motion) and rise, then move. True when a + /// block stopped it. + fn free_flight(&mut self, scene: &mut SceneCollisions) -> bool { + let h = 0.125; + 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 + 2.0 * h, + self.position.z + h, + ), + ); + let wanted = if self.angled { + self.velocity + } else { + Vec3::new( + self.velocity.x * 1.15, + self.velocity.y + 0.04, + self.velocity.z * 1.15, + ) + }; + let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) else { + return false; + }; + let blocked = (moved.x - wanted.x).abs() > 1e-7 + || (moved.y - wanted.y).abs() > 1e-7 + || (moved.z - wanted.z).abs() > 1e-7; + let horizontal = (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7; + self.position = Vec3::new( + self.position.x + moved.x, + self.position.y + moved.y, + self.position.z + moved.z, + ); + self.velocity = if horizontal { + Vec3::new(self.velocity.x, wanted.y, self.velocity.z) + } else { + wanted + }; + blocked } /// Position and motion (the dispenser parity fixture). pub(super) fn motion(&self) -> (Vec3, Vec3) { @@ -191,46 +236,14 @@ impl Game<'_> { r.velocity = p.velocity; } } else { - // Not shot at an angle: accelerate (unless blocked sideways) and rise. let mut scene = SceneCollisions { world: &self.world, binding: self.collision, subject: None, }; - let h = 0.125; - let bounds = Aabb::new( - Vec3::new(r.position.x - h, r.position.y, r.position.z - h), - Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h), - ); - let wanted = if r.angled { - r.velocity - } else { - Vec3::new( - r.velocity.x * 1.15, - r.velocity.y + 0.04, - r.velocity.z * 1.15, - ) - }; - if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) { - let blocked = (moved.x - wanted.x).abs() > 1e-7 - || (moved.y - wanted.y).abs() > 1e-7 - || (moved.z - wanted.z).abs() > 1e-7; - if r.angled && blocked { - // hitTargetOrDeflectSelf: explode on the block. - r.life = r.lifetime; - } - let horizontal = - (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7; - r.position = Vec3::new( - r.position.x + moved.x, - r.position.y + moved.y, - r.position.z + moved.z, - ); - r.velocity = if horizontal { - Vec3::new(r.velocity.x, wanted.y, r.velocity.z) - } else { - wanted - }; + if r.free_flight(&mut scene) && r.angled { + // hitTargetOrDeflectSelf: explode on the block. + r.life = r.lifetime; } } let at = [r.position.x, r.position.y, r.position.z]; @@ -383,7 +396,12 @@ impl Game<'_> { /// lit at the rocket's light probe. pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let orientation = glam::Mat4::from_quat(self.camera_orientation()); - for r in self.rockets.iter().filter(|r| !r.attached) { + // shouldRender: not while attached to an entity (`isAttachedToEntity`). + for r in self + .rockets + .iter() + .filter(|r| !r.attached && r.attached_to.is_none()) + { // FireworkRocketEntity.shouldRenderAtSqrDistance: within 64 blocks; // EntityRenderer.shouldRender: its 0.25 box in the view. if !self.standing_entity_in_view( diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index b308b9f1d..fa2627693 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -2,6 +2,7 @@ //! bobbing, lure and bite timers, open water, hooking mobs, retrieving the //! `gameplay/fishing` loot) and `FishingHookRenderer` (bobber and line). use super::{Game, view_vector}; +use horizon_client::advancements::EntityView; use horizon_client::lan::{entity::States, hub::Hub}; use horizon_client::{ blocks::Fluid, @@ -14,6 +15,7 @@ use horizon_client::{ }; use horizon_core::{ geometry::{Aabb, Vec3, trig}, + position::BlockPos, random::RandomSource, }; use horizon_protocol::entity_data::{Value, serializer}; @@ -77,7 +79,7 @@ impl Game<'_> { let at = [p.position.x, p.position.y, p.position.z]; let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); if self.hook.is_some() { - let damage = self.retrieve_hook(); + let damage = self.retrieve_hook(stack); self.damage_held(damage); self.audio.play( "minecraft:entity.fishing_bobber.retrieve", @@ -143,7 +145,7 @@ impl Game<'_> { true } /// `FishingHook.retrieve`: the rod damage it costs. - fn retrieve_hook(&mut self) -> u32 { + fn retrieve_hook(&mut self, rod: &ItemStack) -> u32 { let Some(hook) = self.hook.take() else { return 0; }; @@ -167,6 +169,15 @@ impl Game<'_> { item.velocity = pulled(item.velocity); hooked_item = true; } + // CriteriaTriggers.FISHING_ROD_HOOKED with no items. + let hooked = self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| self.mob_entity(m)); + if let Some(hooked) = hooked { + self.trigger_fishing_rod_hooked(rod, &hooked, &[]); + } // `hookedIn instanceof ItemEntity ? 3 : 5`. damage = if hooked_item { 3 } else { 5 }; } else if hook.nibble > 0 { @@ -191,6 +202,7 @@ impl Game<'_> { Some(hook.open_water), ); self.world.random = random; + let mut caught = Vec::new(); for stack in items { // FishingHook.retrieve: fish_caught for each catch in #minecraft:fishes. if self @@ -222,6 +234,7 @@ impl Game<'_> { if let Some(potion) = &stack.potion { item = item.with_potion(potion); } + caught.push(item.clone()); let (dx, dy, dz) = ( owner.x - hook.position.x, owner.y - hook.position.y, @@ -236,11 +249,20 @@ impl Game<'_> { item, [hook.position.x, hook.position.y, hook.position.z], v, - 10, + 0, ); let xp = self.world.random.next_int_bound(6).unwrap_or(0) as u32 + 1; self.spawn_orbs([owner.x, owner.y + 0.5, owner.z + 0.5], xp); } + // CriteriaTriggers.FISHING_ROD_HOOKED: the hook itself is the entity. + let bobber = EntityView { + kind: "minecraft:fishing_bobber".into(), + position: [hook.position.x, hook.position.y, hook.position.z], + on_ground: hook.on_ground, + fishing_open_water: Some(hook.open_water), + ..Default::default() + }; + self.trigger_fishing_rod_hooked(rod, &bobber, &caught); damage = 1; } if hook.on_ground { @@ -318,9 +340,12 @@ impl Game<'_> { let mut speed = 1; let above = [b[0], b[1] + 1, b[2]]; let sky = self.world.light(above[0], above[1], above[2]) >> 4 == 15; - let raining = self.world.weather.raining; - let r = &mut self.world.random; - if r.next_float() < 0.25 && raining && sky { + // Level.isRainingAt: rain (not snow) reaches the position. + if self.world.random.next_float() < 0.25 + && self.with_level(|b, level, _| { + b.is_raining_at(level, BlockPos::new(above[0], above[1], above[2])) + }) + { speed += 1; } let r = &mut self.world.random; @@ -433,6 +458,8 @@ impl Game<'_> { let options = ParticleOptions::simple(kind); self.particles .send_particles(&options, at, spread, speed, count); + // The players a server serves are sent them too. + self.lan_send_particles(&options, at, spread, speed, count); } /// `FishingHook.tick`. pub(super) fn tick_fishing(&mut self) { @@ -643,6 +670,8 @@ impl Game<'_> { layer: 0, color: 0xFFFF_FFFF, light: packed, + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 95e2e1e6e..364f89189 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -114,7 +114,7 @@ impl Game<'_> { living: Some(HurtBob { hurt_time: p.health.hurt_animation_time as f32 - partial, hurt_duration: hurt.hurt_duration, - hurt_dir: 0.0, + hurt_dir: p.health.hurt_dir, death_time: self.death_time().map(|t| t as f32 + partial), }), player: Some(( diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 946d1c017..f4721ae26 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -378,6 +378,8 @@ impl Game<'_> { layer: 0, color: 0xFFFF_FFFF, light, + + glint_uv: [0.0, 0.0], }); } }; diff --git a/crates/horizon-client/src/game/glowing.rs b/crates/horizon-client/src/game/glowing.rs new file mode 100644 index 000000000..8c78dbd77 --- /dev/null +++ b/crates/horizon-client/src/game/glowing.rs @@ -0,0 +1,53 @@ +//! Glowing entities (`EntityRenderer.extractRenderState`'s outlineColor): which entities +//! appear glowing, in which team colour, and their silhouettes for the renderer's entity +//! outline (`OutlineBufferSource`). +use super::{Game, Vertex}; +use horizon_client::{mobs::Mob, scoreboard as sb}; + +/// `Entity.getTeamColor`: the team's colour, else white. +pub(super) fn team_color(team: Option<&sb::Team>) -> u32 { + team.and_then(|t| t.color.as_deref()) + .and_then(sb::team_color_rgb) + .unwrap_or(0xFF_FFFF) +} + +impl Game<'_> { + /// `Entity.isCurrentlyGlowing` of an entity that is not living (an item, a projectile): + /// its `Glowing` tag, or shared flag 6 as a server sent it. + pub(super) fn entity_glowing(&self, id: u32) -> bool { + self.remote_glowing(id).unwrap_or_else(|| { + self.persist_raw(id) + .and_then(|t| horizon_client::save::number(t.get("Glowing"))) + .is_some_and(|b| b != 0) + }) + } + + /// `Minecraft.shouldEntityAppearGlowing` of a mob or another player, with its outline + /// colour (`getTeamColor`; another player's team goes by name). + pub(super) fn mob_outline(&self, m: &Mob) -> Option { + if !m.is_currently_glowing() { + return None; + } + let team = if &*m.kind.id == "minecraft:player" { + let names = self.remote_player_names(); + let name = names.into_iter().find(|(id, _)| *id == m.id); + name.and_then(|(_, name)| self.score.board.players_team(&name)) + } else { + self.mob_team(m.id) + }; + Some(team_color(team)) + } + + /// Adds one glowing entity's geometry to the outline pass in `rgb`, the textures' + /// alpha kept (`OutlineBufferSource`'s team-coloured copy of each draw). + pub(super) fn mark_outline(&self, vertices: &[Vertex], rgb: u32) { + let color = horizon_client::mobs::render::abgr(rgb); + self.glowing_vertices + .borrow_mut() + .extend(vertices.iter().map(|v| Vertex { + color, + normal: [0; 4], + ..*v + })); + } +} diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index d91d3b979..8b835725f 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -3,7 +3,7 @@ //! `continueAttack`, `MultiPlayerGameMode` block breaking), the arm swing //! (`LivingEntity.SwingState`) and the first-person equip heights //! (`FirstPersonHandsAndItems`) with the item swap ticker they read. -use super::{Game, Mining, Screen}; +use super::{Game, Mining, Screen, minecarts::CartKind}; use horizon_client::{ Result, attack_strength::HeldStack, @@ -144,6 +144,11 @@ impl Game<'_> { let harvest = !facts.requires_tool || self.res.items().correct_for_drops(held, &facts.name); speed / facts.hardness / if harvest { 30.0 } else { 100.0 } } + /// A key for the main-hand stack (`destroyingItem`): its item and components. + pub(super) fn main_hand_key(&self) -> String { + self.held() + .map_or(String::new(), |s| format!("{} {:?}", s.item, s.extra)) + } /// Whether an attack would hit an entity rather than the block behind /// it: the crosshair's `EntityHitResult`. pub(super) fn entity_targeted(&self) -> bool { @@ -289,6 +294,64 @@ impl Game<'_> { // Only alive mobs are hit, so a picked living entity is alive. Some(true) } + /// `Hud.canRenderCrosshairForSpectator` for the nearest hit in reach: an + /// entity that is a `MenuProvider` (a chest or hopper minecart, a chest + /// boat), or a block whose `showAsInteractableInSpectatorMode` holds. + pub(super) fn spectator_crosshair(&self) -> bool { + let cart = self.cart_hit().map(|(i, d)| { + let kind = &self.carts[i].kind; + (d, matches!(kind, CartKind::Chest | CartKind::Hopper)) + }); + let boat = self.boat_hit().map(|(i, d)| (d, self.boats[i].chest)); + let others = [ + self.mob_hit().map(|h| h.1), + self.armor_stand_hit().map(|h| h.1), + self.cushion_hit().map(|h| h.1), + self.painting_hit().map(|h| h.1), + self.frame_hit().map(|h| h.1), + self.dragon_hit().map(|h| h.1), + ]; + let nearest = cart + .into_iter() + .chain(boat) + .chain(others.into_iter().flatten().map(|d| (d, false))) + .min_by(|a, b| a.0.total_cmp(&b.0)); + if let Some((distance, menu)) = nearest + && self.before_block(distance) + { + return menu; + } + let Some(hit) = self.pick() else { + return false; + }; + let name = &*self + .res + .facts() + .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])) + .name; + let name = name.trim_start_matches("minecraft:"); + match name { + // BlockBehaviour.getMenuProvider and `instanceof Portal`. + "crafting_table" | "enchanting_table" | "anvil" | "chipped_anvil" | "damaged_anvil" + | "stonecutter" | "loom" | "cartography_table" | "grindstone" | "smithing_table" + | "barrel" | "furnace" | "blast_furnace" | "smoker" | "brewing_stand" | "hopper" + | "dispenser" | "dropper" | "crafter" | "lectern" | "beacon" | "nether_portal" + | "end_portal" | "end_gateway" => true, + // ChestBlock.getMenuProvider: none while a redstone conductor + // sits on top of either half (a sitting cat aside). + "chest" | "trapped_chest" => { + let key = (hit.pos[0], hit.pos[1], hit.pos[2]); + let blocked = |p: (i32, i32, i32)| { + let above = self.world.block(p.0, p.1 + 1, p.2); + self.res.behaviours().facts(above).flags + & horizon_world::level::data::state_flags::CONDUCTOR + != 0 + }; + !blocked(key) && self.chest_other_half(key).is_none_or(|o| !blocked(o)) + } + _ => name.ends_with("shulker_box"), + } + } /// `Attributes.ATTACK_SPEED` with the main-hand item's modifier. pub(super) fn main_hand_attack_speed(&self) -> f64 { horizon_client::attack_strength::BASE_ATTACK_SPEED @@ -445,9 +508,7 @@ impl HandWorld for GameHands<'_, '_> { true } fn main_hand_key(&mut self) -> String { - self.game - .held() - .map_or(String::new(), |s| format!("{} {:?}", s.item, s.extra)) + self.game.main_hand_key() } fn destroy_stage(&mut self, _: [i32; 3], _: Option) {} fn swing(&mut self, hand: Hand, animation: SwingAnimation) { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 7d81c971d..df40ff377 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -420,6 +420,8 @@ impl Game<'_> { s.flags.published.store(0, Ordering::Relaxed); } if let Some(mut host) = self.lan.take() { + // PlayerList.removeAll: the owner and every guest leave the game. + host.award_leave_game_to_all(); for g in &host.hub.guests { self.save_guest(&host, g); } diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index b6b7e2fb7..efb83e5db 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -129,6 +129,7 @@ pub(super) struct Host<'a> { banners: &'a horizon_client::banner::Banners, sprites: &'a HashMap, skins: &'a RefCell, + profiles: &'a RefCell, } impl SpecialHost for Host<'_> { fn banner_texture(&self, pattern: &str) -> Option { @@ -144,14 +145,14 @@ impl SpecialHost for Host<'_> { fn player_skin(&self, profile: &Value) -> Option { // SkullBlockRenderer.getPlayerSkin: SkinManager.getInsecureSkinInformation // accepts a texture property without a signature, unlike the tab list. - let url = horizon_client::skins::profile_skin_url(profile)?; - let location = - horizon_client::skins::skin_location(&horizon_client::skins::texture_hash(&url)?); - let _ = self - .skins - .borrow_mut() - .state(horizon_client::skins::Kind::Skin, &url); - self.sprites.contains_key(&location).then_some(location) + // A `Dynamic` profile (a name or id only) resolves through the + // services (`PlayerSkinRenderCache.getOrDefault`). + Some(horizon_client::skins::head_skin( + profile, + &mut self.profiles.borrow_mut(), + &mut self.skins.borrow_mut(), + |location| self.sprites.contains_key(location), + )) } } @@ -194,6 +195,7 @@ impl Game<'_> { banners: &self.res.stations().banners, sprites: &self.gui.atlas.sprites, skins: &self.skin_downloads, + profiles: &self.skin_profiles, } } /// The client level as item models read it: worked out once a frame (a @@ -296,8 +298,32 @@ impl Game<'_> { x, y, self.started.elapsed().as_secs_f32(), + self.settings.file.double("glintSpeed") as f32, + self.settings.file.double("glintStrength") as f32, ); } + /// The `GLINT_TEXTURING` inputs the atlas and options provide. + pub(super) fn glint(&self) -> Option { + self.gui + .atlas + .sprites + .get("misc/enchanted_glint_item") + .copied() + .map(|_| item_render::Glint { + speed: self.settings.file.double("glintSpeed") as f32, + alpha: self.settings.file.double("glintStrength") as f32, + millis: self.started.elapsed().as_secs_f32() * 1000.0, + scale: 0.5, + }) + } + /// The glint scroll phase shared by world items and armour + /// (`item_render::Glint::scroll_ticks`). + pub(super) fn glint_ticks(&self) -> f32 { + item_render::Glint::scroll_ticks( + self.started.elapsed().as_secs_f32() * 1000.0, + self.settings.file.double("glintSpeed") as f32, + ) + } /// Submit a resolved item under `pose` (camera-relative) at `light` /// (packed lightmap coordinates). pub(super) fn submit_item_world( @@ -311,6 +337,7 @@ impl Game<'_> { out, light, lights: Some(diffuse_lights(self.dim == Dim::Nether)), + glint: self.glint(), }; state.submit( &self.pack.item_renderer, @@ -332,6 +359,7 @@ impl Game<'_> { out, light, lights: None, + glint: self.glint(), }; state.submit( &self.pack.item_renderer, @@ -405,7 +433,12 @@ impl Game<'_> { ) { self.submit_item_world(&state, copy, vertex_light(packed), out); } - self.cull_entity_vertices(out, entity_start); + if self.entity_glowing(item.id) { + let rgb = super::glowing::team_color(self.mob_team(item.id)); + self.mark_outline(&out[entity_start..], rgb); + } else { + self.cull_entity_vertices(out, entity_start); + } } } } diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index c3ed75ebb..87f91895e 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -79,6 +79,7 @@ impl Game<'_> { if !self.creative { self.consume_held(); } + self.stats.custom("play_record", 1); self.world.block_entities.insert( (pos[0], pos[1], pos[2]), BlockEntity::Jukebox(Jukebox { @@ -90,6 +91,8 @@ impl Game<'_> { self.set_has_record(pos, true); self.start_song(pos, &song); self.jukebox_changed(pos); + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, stack); true } /// Level event 1010: the song from the jukebox, and the "Now Playing" overlay. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index a0f99bfca..38cb16fa1 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -92,6 +92,33 @@ pub(super) struct LanHost { states: lan::entity::States, } +impl LanHost { + /// `PlayerList.remove`: `player.awardStat(Stats.LEAVE_GAME)` before the + /// player is saved. Once per guest, however often they are saved. + pub(super) fn award_leave_game(&mut self, conn: u32) { + if let Some(play) = self.play.get_mut(&conn) + && !play.left_game + { + play.left_game = true; + play.stats.custom("leave_game", 1); + } + } + + /// `PlayerList.removeAll`: every player who joined leaves with the world. + pub(super) fn award_leave_game_to_all(&mut self) { + let conns: Vec = self + .hub + .guests + .iter() + .filter(|g| g.placed) + .map(|g| g.conn) + .collect(); + for conn in conns { + self.award_leave_game(conn); + } + } +} + /// The player who owns an integrated server's world: a guest whose state is /// the world's own player (`players/data/.dat`), as in /// single player. @@ -154,6 +181,136 @@ pub(super) fn baby_index(kind: &str) -> Option { } } +/// The variant and look entries of `mob_meta`'s mobs (registry holders, the +/// fish's, the bee's, the copper golem's weathering...), in a match of their +/// own: `mob_meta`'s arms hold these mobs' other entries. +fn mob_variant_meta( + m: &Mob, + hub: &Hub, + meta: &mut Vec<(u8, i32, Value)>, + defaults: &mut Vec<(u8, i32, Value)>, +) { + let (kind, e) = (m.kind.id.as_str(), &m.extra); + let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); + match kind { + // Axolotl.DATA_VARIANT (after AgeableMob's two). + "minecraft:axolotl" => { + if e.variant != 0 { + meta.push((18, serializer::INT, Value::Int(i32::from(e.variant)))); + } + } + // Frog.DATA_VARIANT_ID, Pig's, Cow's, Chicken's and ZombieNautilus's + // (after the entries of their parents): registry holders. + "minecraft:frog" + | "minecraft:pig" + | "minecraft:cow" + | "minecraft:chicken" + | "minecraft:zombie_nautilus" => { + let (index, serializer, registry) = match kind { + "minecraft:frog" => (18, serializer::FROG_VARIANT, "minecraft:frog_variant"), + "minecraft:pig" => (19, serializer::PIG_VARIANT, "minecraft:pig_variant"), + "minecraft:cow" => (18, serializer::COW_VARIANT, "minecraft:cow_variant"), + "minecraft:chicken" => { + (18, serializer::CHICKEN_VARIANT, "minecraft:chicken_variant") + } + _ => ( + 21, + serializer::ZOMBIE_NAUTILUS_VARIANT, + "minecraft:zombie_nautilus_variant", + ), + }; + // Each registry's default (`define(DATA_VARIANT_ID, ... TEMPERATE)`) + // stays out of the pairing data, as other default values do. + let name = horizon_client::mobs::finalize::variant_name(m.species(), e.variant); + let name = name.trim_start_matches("minecraft:"); + if let Some(v) = id(registry, name) + && name != "temperate" + { + meta.push((index, serializer, Value::Id(v))); + } + if let Some(v) = id(registry, "temperate") { + defaults.push((index, serializer, Value::Id(v))); + } + } + // Rabbit.DATA_TYPE_ID (after AgeableMob's two) and + // Parrot.DATA_VARIANT_ID (after TamableAnimal's two and its flags and + // owner). The fox's type goes with its flags (#2538). + "minecraft:rabbit" | "minecraft:parrot" => { + let index = if kind == "minecraft:parrot" { 20 } else { 18 }; + if e.variant != 0 { + meta.push((index, serializer::INT, Value::Int(i32::from(e.variant)))); + } + } + // Bee.DATA_FLAGS_ID (rolling 2, stung 4, nectar 8) and + // DATA_ANGER_END_TIME: the texture shows the nectar and the anger. + "minecraft:bee" => { + let bee = horizon_client::mobs::bee::get(m); + let flags = bee.map_or(0, |b| b.flags); + if flags != 0 { + meta.push((18, serializer::BYTE, Value::Byte(flags as i8))); + } + defaults.push((18, serializer::BYTE, Value::Byte(0))); + let anger_end = bee.map_or(-1, |b| b.anger_end); + if anger_end != -1 { + meta.push((19, serializer::LONG, Value::Long(anger_end))); + } + defaults.push((19, serializer::LONG, Value::Long(-1))); + } + // AbstractFish.FROM_BUCKET takes 16: Salmon.DATA_TYPE (small 0, + // medium 1, large 2; medium is the data's default, so always sent), + // Pufferfish.PUFF_STATE and TropicalFish.DATA_ID_TYPE_VARIANT: the + // pattern's packed id (size, then index << 8), base colour << 16 and + // pattern colour << 24. + "minecraft:salmon" => { + meta.push((17, serializer::INT, Value::Int(i32::from(e.variant.min(2))))); + } + "minecraft:pufferfish" => { + if e.size > 0 { + meta.push((17, serializer::INT, Value::Int(e.size))); + } + defaults.push((17, serializer::INT, Value::Int(0))); + } + "minecraft:tropical_fish" => { + let pattern = e.variant.min(11); + let packed = i32::from(pattern >= 6) + | i32::from(pattern % 6) << 8 + | i32::from(e.variant2 & 15) << 16 + | i32::from(e.variant3 & 15) << 24; + if packed != 0 { + meta.push((17, serializer::INT, Value::Int(packed))); + } + } + // CopperGolem.DATA_WEATHER_STATE: unaffected 0 to oxidized 3, and it + // goes back down when the golem is scraped. + "minecraft:copper_golem" => { + if e.variant != 0 { + meta.push(( + 16, + serializer::WEATHERING_COPPER_STATE, + Value::Id(i32::from(e.variant.min(3))), + )); + } + defaults.push((16, serializer::WEATHERING_COPPER_STATE, Value::Id(0))); + } + // Ghast.DATA_IS_CHARGING: the shooting texture. + "minecraft:ghast" => { + if e.flag { + meta.push((16, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(false))); + } + // WitherBoss.DATA_ID_INV (after the three head targets): the + // invulnerable ticks, the blinking texture and the growing scale. + "minecraft:wither" => { + if e.counter > 0 { + meta.push((19, serializer::INT, Value::Int(e.counter))); + } + defaults.push((19, serializer::INT, Value::Int(0))); + } + _ => {} + } +} + /// A mob's synched data as ServerEntity sends it (only the values that differ /// from the defaults the client constructs), with vanilla's entry indices: /// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses. @@ -162,12 +319,22 @@ fn mob_meta( m: &Mob, hub: &Hub, player_entity: Option, + game_time: i64, meta: &mut Vec<(u8, i32, Value)>, defaults: &mut Vec<(u8, i32, Value)>, ) { let kind = m.kind.id.as_str(); - if m.fire_ticks > 0 { - meta.push((0, serializer::BYTE, Value::Byte(1))); + // Entity.DATA_SHARED_FLAGS_ID: on fire 0x01, glowing 0x40 + // (LivingEntity.updateGlowingStatus). + let shared = i8::from(m.fire_ticks > 0) | i8::from(m.is_currently_glowing()) << 6; + if shared != 0 { + meta.push((0, serializer::BYTE, Value::Byte(shared))); + } + // Entity.DATA_POSE: the pose the species keeps in its own fields (a + // pose back at standing goes out by the entity's own default). + let pose = horizon_client::mobs::sync::pose_id(m); + if pose != 0 { + meta.push((6, serializer::POSE, Value::Id(i32::from(pose)))); } if let Some(name) = &m.custom_name { meta.push(( @@ -221,6 +388,7 @@ fn mob_meta( } let e = &m.extra; let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); + mob_variant_meta(m, hub, meta, defaults); match kind { "minecraft:guardian" | "minecraft:elder_guardian" => { // Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET. @@ -277,6 +445,18 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(0))); } + // Fox.DATA_TYPE_ID and DATA_FLAGS_ID (after AgeableMob's two; sleeping 32, ...). + "minecraft:fox" => { + if e.variant != 0 { + meta.push((18, serializer::INT, Value::Int(i32::from(e.variant)))); + } + defaults.push((18, serializer::INT, Value::Int(0))); + let flags = (e.ints[0] & 0xff) as u8 as i8; + if flags != 0 { + meta.push((19, serializer::BYTE, Value::Byte(flags))); + } + defaults.push((19, serializer::BYTE, Value::Byte(0))); + } "minecraft:cat" | "minecraft:wolf" => { // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. let flags = i8::from(e.sitting) | if e.tame { 4 } else { 0 }; @@ -305,6 +485,14 @@ fn mob_meta( meta.push((collar, serializer::INT, Value::Int(i32::from(e.color & 15)))); } defaults.push((collar, serializer::INT, Value::Int(red))); + // Wolf.DATA_ANGER_END_TIME: the game time the anger ends, -1 when calm. + if kind == "minecraft:wolf" { + if e.anger > 0 { + let end = game_time + i64::from(e.anger); + meta.push((22, serializer::LONG, Value::Long(end))); + } + defaults.push((22, serializer::LONG, Value::Long(-1))); + } } "minecraft:horse" | "minecraft:donkey" @@ -383,6 +571,29 @@ fn mob_meta( } defaults.push((17, serializer::BOOLEAN, Value::Bool(false))); } + // Panda: UNHAPPY_COUNTER, SNEEZE_COUNTER and EAT_COUNTER (after + // AgeableMob's two), MAIN_GENE_ID, HIDDEN_GENE_ID and DATA_ID_FLAGS; + // the client animates the states from them. + "minecraft:panda" => { + let (flags, counters) = horizon_client::mobs::panda::get(m) + .map_or((0, [0; 3]), |s| (s.flags, [s.unhappy, s.sneeze, s.eat])); + for (index, value) in (18..).zip(counters) { + if value != 0 { + meta.push((index, serializer::INT, Value::Int(value))); + } + defaults.push((index, serializer::INT, Value::Int(0))); + } + for (index, gene) in [(21, e.variant), (22, e.variant2)] { + if gene != 0 { + meta.push((index, serializer::BYTE, Value::Byte(gene as i8))); + } + defaults.push((index, serializer::BYTE, Value::Byte(0))); + } + if flags != 0 { + meta.push((23, serializer::BYTE, Value::Byte(flags as i8))); + } + defaults.push((23, serializer::BYTE, Value::Byte(0))); + } // PolarBear.DATA_STANDING_ID (after AgeableMob's two): the bear // rears up; the client animates it. "minecraft:polar_bear" => { @@ -398,6 +609,121 @@ fn mob_meta( } defaults.push((17, serializer::BYTE, Value::Byte(0))); } + // Warden.CLIENT_ANGER_LEVEL: the heartbeat's pace. + "minecraft:warden" => { + let anger = e.warden.as_ref().map_or(0, |w| w.client_anger); + if anger != 0 { + meta.push((16, serializer::INT, Value::Int(anger))); + } + defaults.push((16, serializer::INT, Value::Int(0))); + } + // Sniffer.DATA_STATE (after AgeableMob's two). + "minecraft:sniffer" => { + if e.variant != 0 { + meta.push(( + 18, + serializer::SNIFFER_STATE, + Value::Id(i32::from(e.variant)), + )); + } + defaults.push((18, serializer::SNIFFER_STATE, Value::Id(0))); + } + // Shulker.DATA_ATTACH_FACE_ID, DATA_PEEK_ID and DATA_COLOR_ID (16 + // for none). + "minecraft:shulker" => { + if e.variant3 != 0 { + meta.push((16, serializer::DIRECTION, Value::Id(i32::from(e.variant3)))); + } + defaults.push((16, serializer::DIRECTION, Value::Id(0))); + if e.counter != 0 { + meta.push((17, serializer::BYTE, Value::Byte(e.counter as i8))); + } + defaults.push((17, serializer::BYTE, Value::Byte(0))); + if e.color != 16 { + meta.push((18, serializer::BYTE, Value::Byte(e.color as i8))); + } + defaults.push((18, serializer::BYTE, Value::Byte(16))); + } + // Vex.DATA_FLAGS_ID: charging in bit 0 (the arms and the glowing + // texture). + "minecraft:vex" => { + if e.flag { + meta.push((16, serializer::BYTE, Value::Byte(1))); + } + defaults.push((16, serializer::BYTE, Value::Byte(0))); + } + // Creaking.CAN_MOVE, IS_ACTIVE and IS_TEARING_DOWN. + "minecraft:creaking" => { + if e.flag2 { + meta.push((16, serializer::BOOLEAN, Value::Bool(false))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(true))); + if e.flag { + meta.push((17, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((17, serializer::BOOLEAN, Value::Bool(false))); + if horizon_client::mobs::creaking::tearing_down(m) { + meta.push((18, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((18, serializer::BOOLEAN, Value::Bool(false))); + } + // Allay.DATA_DANCING and DATA_CAN_DUPLICATE (the held item is its + // main hand equipment). + "minecraft:allay" => { + if e.flag { + meta.push((16, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(false))); + if e.egg_time > 0 { + meta.push((17, serializer::BOOLEAN, Value::Bool(false))); + } + defaults.push((17, serializer::BOOLEAN, Value::Bool(true))); + } + // Axolotl.DATA_PLAYING_DEAD (after DATA_VARIANT). + "minecraft:axolotl" => { + if horizon_client::mobs::axolotl::is_playing_dead(m) { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } + // CopperGolem.COPPER_GOLEM_STATE (after DATA_WEATHER_STATE). + "minecraft:copper_golem" => { + if e.variant3 != 0 { + meta.push(( + 17, + serializer::COPPER_GOLEM_STATE, + Value::Id(i32::from(e.variant3)), + )); + } + defaults.push((17, serializer::COPPER_GOLEM_STATE, Value::Id(0))); + } + // Armadillo.ARMADILLO_STATE (after AgeableMob's two). + "minecraft:armadillo" => { + let state = horizon_client::mobs::armadillo::state(m); + if state != 0 { + meta.push((18, serializer::ARMADILLO_STATE, Value::Id(i32::from(state)))); + } + defaults.push((18, serializer::ARMADILLO_STATE, Value::Id(0))); + } + // Frog.DATA_TONGUE_TARGET_ID (after the variant): the entity id plus + // one, 0 for none. + "minecraft:frog" => { + if let Some(target) = e.frog.tongue_target { + let id = i32::try_from(target).map_or(0, |t| t + 1); + meta.push((19, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(id))); + } + defaults.push((19, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(0))); + } + // Goat.DATA_HAS_LEFT_HORN and DATA_HAS_RIGHT_HORN (after + // DATA_IS_SCREAMING_GOAT): both true by default. + "minecraft:goat" => { + for (index, lost) in [(19, e.lost_horns[0]), (20, e.lost_horns[1])] { + if lost { + meta.push((index, serializer::BOOLEAN, Value::Bool(false))); + } + defaults.push((index, serializer::BOOLEAN, Value::Bool(true))); + } + } // Enderman.DATA_CARRY_STATE. "minecraft:enderman" => { if let Some(state) = e.carried { @@ -410,6 +736,18 @@ fn mob_meta( } _ => {} } + // Camel.DASH and LAST_POSE_CHANGE_TICK (after AbstractHorse's flags). + if horizon_client::mobs::camel::is_camel(m.species()) { + if e.flag2 { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + let tick = horizon_client::mobs::camel::synced_pose_tick(m, game_time); + if tick != 0 { + meta.push((20, serializer::LONG, Value::Long(tick))); + } + defaults.push((20, serializer::LONG, Value::Long(0))); + } } /// What a client shakes a mob by: Entity.DATA_TICKS_FROZEN (7), whose full @@ -676,7 +1014,8 @@ impl Game<'_> { let host_uuid = host.unwrap_or(0); self.next_entity += 1; let host_entity = self.next_entity as i32; - let hub = Hub::new(lan, sync, encoder, config); + let mut hub = Hub::new(lan, sync, encoder, config); + hub.flat_world = self.world_flat; let port = hub.lan.port; self.world.block_log = Some(Vec::new()); self.world.light_log = Some(Default::default()); @@ -728,6 +1067,7 @@ impl Game<'_> { let Some(mut host) = self.lan.take() else { return; }; + host.award_leave_game_to_all(); for g in &host.hub.guests { self.save_guest(&host, g); } @@ -935,7 +1275,7 @@ impl Game<'_> { out.clear(); for m in self.mobs.iter().filter(|m| !m.removed) { // The lead's holder: the player the mob sees (a guest, else the - // host) or another mob. A fence knot isn't an entity here. + // host), another mob or a fence knot (game/lan_entities.rs). let player_entity = mob_players .get(&m.id) .and_then(|conn| hub.guest(*conn)) @@ -944,7 +1284,7 @@ impl Game<'_> { let leash = m.extra.leash.and_then(|h| match h { Holder::Player => player_entity, Holder::Mob(id) => Some(id as i32), - Holder::Knot(_) => None, + Holder::Knot(p) => self.knot_ids.get(&p).map(|&id| id as i32), }); let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str()); e.position = [m.position.x, m.position.y, m.position.z]; @@ -952,7 +1292,14 @@ impl Game<'_> { e.on_ground = m.on_ground; e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; e.needs_sync = m.needs_sync; - mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults); + mob_meta( + m, + hub, + player_entity, + self.world.game_time, + &mut e.meta, + &mut e.defaults, + ); mob_freeze_meta(m, &mut e.meta, &mut e.defaults); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); @@ -964,6 +1311,10 @@ impl Game<'_> { e.position = [d.position.x, d.position.y, d.position.z]; e.on_ground = d.on_ground; e.velocity = [d.velocity.x, d.velocity.y, d.velocity.z]; + // Entity.DATA_SHARED_FLAGS_ID: glowing 0x40 (the Glowing tag). + if self.entity_glowing(d.id) { + e.meta.push((0, serializer::BYTE, Value::Byte(0x40))); + } e.meta.push((8, serializer::ITEM_STACK, Value::Item(stack))); } for o in &self.orbs { @@ -1030,6 +1381,9 @@ impl Game<'_> { for m in &mut self.mobs { m.needs_sync = false; } + for p in &mut self.creatures.projectiles { + p.needs_sync = false; + } // `runBlockEvents`' broadcast precedes the tick's block changes // (`ChunkHolder.broadcastChanges` in `tick_level` below): the // guest re-runs a piston's `triggerEvent` while its level still @@ -1070,6 +1424,8 @@ impl Game<'_> { self.ui.rules.bool("player_movement_check"), self.ui.rules.bool("elytra_movement_check"), ); + host.hub + .set_immediate_respawn(self.ui.rules.bool("immediate_respawn")); // A server with several levels runs a pass for each // (`tick_server`): the network is read once, before the first. let pass = self.level_pass; @@ -1122,6 +1478,16 @@ impl Game<'_> { "INFO", &format!("System chat: {} joined the game", g.name), ); + } else if self.player.is_some() + && let Some(g) = host.hub.guest(conn) + && g.placed + { + // The host's chat hears of the newcomer as the guests do. + let who = self.player_text(&g.name, g.uuid); + self.system_message( + Text::translate("multiplayer.player.joined", &[who]) + .with_color(horizon_client::text::YELLOW), + ); } } HostEvent::Left(mut guest) => { @@ -1140,6 +1506,9 @@ impl Game<'_> { } } self.lan_crafting_left(&mut host, &mut guest); + if guest.placed { + host.award_leave_game(guest.conn); + } self.save_guest(&host, &guest); host.models.remove(&guest.conn); host.play.remove(&guest.conn); @@ -1153,6 +1522,13 @@ impl Game<'_> { "INFO", &format!("System chat: {} left the game", guest.name), ); + } else if self.player.is_some() && guest.placed { + // ServerGamePacketListenerImpl.removePlayerFromWorld. + let who = self.player_text(&guest.name, guest.uuid); + self.system_message( + Text::translate("multiplayer.player.left", &[who]) + .with_color(horizon_client::text::YELLOW), + ); } } HostEvent::Packet(conn, packet) => { @@ -1190,8 +1566,11 @@ impl Game<'_> { drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); - // A mace's wind burst from a guest's attack. + // A blast from a guest's attack, and a mace's wind burst. + self.flush_lan_explosions(); let _ = self.flush_wind_bursts(); + // Particles a guest's turn sent (sweep attack, damage indicator, a hook's splashes). + self.flush_lan_particles(); } fn lan_guest_joined( @@ -1553,6 +1932,14 @@ impl Game<'_> { .filter_map(|e| super::client_ambient::effect_particle(e.id, e.ambient)) .collect(); m.extra.effect_ambient = visible().all(|e| e.ambient); + // Entity.isInvisible: the invisibility effect hides the body (the + // model pass, the name tag rules and `trader::is_invisible` read it). + m.extra.effects.retain(|e| e.0 != "minecraft:invisibility"); + if let Some(e) = g.effects.get("invisibility") { + m.extra + .effects + .push(("minecraft:invisibility", e.duration, e.amplifier)); + } // Lying in its bed (LivingEntity.getBedOrientation). m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b)); // LivingEntity.updateSwingTime: the arm swing lan_swings started. @@ -1614,7 +2001,12 @@ impl Game<'_> { out, ); self.held_item_geometry(m, camera, alpha, packed, true, out); - if !m.glowing { + // LivingEntity.isCurrentlyGlowing: the guest's Glowing effect. + let guest = host.hub.guest(*conn); + if m.glowing || guest.is_some_and(|g| g.effects.get("glowing").is_some()) { + let team = guest.and_then(|g| self.score.board.players_team(&g.name)); + self.mark_outline(&out[entity_start..], super::glowing::team_color(team)); + } else { self.cull_entity_vertices(out, entity_start); } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ef177d26d..a6a683827 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -74,7 +74,12 @@ pub(super) struct GuestPlay { potions: super::potions::BodyPotions, /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. pub(super) stats: super::stats::Stats, + /// `Stats.LEAVE_GAME` is counted: a guest is saved more than once on the + /// way out, the statistic is awarded once (`LanHost::award_leave_game`). + pub(super) left_game: bool, last_inventory: u64, + /// `ServerPlayer.levitationStartPos` and `levitationStartTime`. + levitation: Option<([f64; 3], u64)>, /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). pub(super) portal: horizon_client::nether_portal::PortalState, /// `ServerPlayer.wonGame`: the End poem is showing, the player waits for @@ -158,6 +163,7 @@ pub(super) struct GuestSwap { host_ender: Option<(i32, i32, i32)>, adv_loaded: bool, last_inventory: u64, + levitation: Option<([f64; 3], u64)>, death_cause: Option, /// The guest's own damage record, in place while they act. combat: super::combat::CombatTracker, @@ -267,8 +273,10 @@ impl Game<'_> { } let mut play = host.play.remove(&conn).unwrap_or_default(); if fresh { - // A new body (joined, respawned, changed level): nothing on it yet. + // A new body (joined, respawned, changed level): nothing on it yet, + // its effects' modifiers and armor protection included. play.equipped = None; + play.potions = Default::default(); play.sculk = Default::default(); } let g = &mut host.hub.guests[i]; @@ -384,6 +392,7 @@ impl Game<'_> { std::mem::swap(&mut self.hook, &mut play.hook); let adv_loaded = std::mem::replace(&mut self.adv.loaded, true); let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory); + let levitation = std::mem::replace(&mut self.adv.levitation, play.levitation); let death_cause = std::mem::replace(&mut self.ui.death_cause, play.death_cause.take()); let acting = ( self.lan_acting.replace(conn), @@ -405,6 +414,12 @@ impl Game<'_> { self.apply_equipment(); play.equipped = Some(equipped); } + // The player's effects are on the new body before anything it does + // (the movement that brought it, a landing): vanilla keeps the same + // entity through a level change, with its attributes and effects. + if fresh { + self.apply_effect_status(); + } self.update_totem_ready(); Some(GuestSwap { conn, @@ -449,6 +464,7 @@ impl Game<'_> { host_ender, adv_loaded, last_inventory, + levitation, death_cause, acting, packets, @@ -508,6 +524,7 @@ impl Game<'_> { host_ender, adv_loaded, last_inventory, + levitation, death_cause, combat, acting, @@ -630,6 +647,7 @@ impl Game<'_> { std::mem::swap(&mut self.hook, &mut play.hook); self.adv.loaded = adv_loaded; play.last_inventory = std::mem::replace(&mut self.adv.last_inventory, last_inventory); + play.levitation = std::mem::replace(&mut self.adv.levitation, levitation); let stat_events = std::mem::take(&mut play.stats.events); let name = g.name.clone(); self.potions.swap_player(&mut g.effects, &mut play.potions); @@ -673,6 +691,13 @@ impl Game<'_> { g.sprinting = false; } m.sprinting = false; + // ServerPlayer.indicateDamage: the hit's direction to the player. + if let Some(yaw) = m.health.indicated_dir.take() { + g.send(&C::HurtAnimation(play::HurtAnimation { + id: g.entity_id, + yaw, + })); + } let teleported = std::mem::take(&mut m.teleported); let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum(); g.motion = Some(Box::new(m)); @@ -874,13 +899,17 @@ impl Game<'_> { } /// The guest's open container is closing (`AbstractContainerMenu.removed`): - /// it no longer counts among the openers of the lid. + /// it no longer counts among the openers of the lid, and the lid's close + /// sound is played for everyone around (`ChestBlockEntity.onClose`, a + /// `playSound` with no player), the guest included, once the last opener + /// has left. pub(super) fn guest_container_closed(&mut self, host: &mut LanHost, conn: u32) { if let Some(g) = host.hub.guest(conn) && let Some(pos) = g.menu.as_ref().and_then(|m| m.pos) && !g.spectator() + && self.container_openers_changed(pos, false) { - self.container_openers_changed(pos, false); + self.container_edge_sound(pos, false); } } @@ -974,6 +1003,20 @@ impl Game<'_> { // The pause between two blocks is the client's (MultiPlayerGameMode's // destroyDelay); the server digs from the START it receives. play.destroy_delay = 0; + // ServerPlayerGameMode.handleBlockBreakAction: a survival START + // attacks the block at once, so a tap released in the same tick + // still plays a note. The dig is marked begun for tick_mining. + let pos = a.pos; + self.as_guest(host, conn, |g| { + if g.may_build() && !g.creative { + let _ = g.attack_block(pos); + g.mining = Some(Mining { + pos, + progress: 0.0, + ticks: 0, + }); + } + }); } 1 => {} 3 => { @@ -1391,19 +1434,68 @@ impl Game<'_> { .unwrap_or_default(); host.hub.send_stats(conn, &stats); } + // handlePickItemFromBlock: a block within the block reach plus 1, its + // data only with infinite materials. S::PickItemFromBlock(p) => { - let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); - let item = self.res.facts().get(state).item.clone(); - let g = &mut host.hub.guests[gi]; - if g.creative() && &*item != "minecraft:air" { - let slot = g.selected; - g.inventory[slot] = Some(ItemStack::new(&item, 1)); - } + self.guest_pick_item(host, conn, |g| { + let eye = g.eye_position()?; + let d2: f64 = (0..3) + .map(|a| { + let lo = f64::from(p.pos[a]); + (eye[a] - eye[a].clamp(lo, lo + 1.0)).powi(2) + }) + .sum(); + let range = g.reach() + 1.0; + if d2 >= range * range { + return None; + } + g.picked_stack(p.pos, g.creative && p.include_data) + }); + } + // handlePickItemFromEntity. + S::PickItemFromEntity(p) => { + self.guest_pick_item(host, conn, |g| { + g.within_entity_range(p.id) + .then(|| g.entity_pick_result(p.id)) + .flatten() + }); } _ => {} } } + /// `ServerGamePacketListenerImpl.tryPickItem` for the guest: a matching stack + /// is selected, else a creative player gets the item; the held slot is sent + /// back and the changed slots follow with the tick's inventory changes. + fn guest_pick_item( + &mut self, + host: &mut LanHost, + conn: u32, + stack: impl FnOnce(&mut Self) -> Option, + ) { + let picked = self.as_guest(host, conn, |g| { + let stack = stack(g)?; + let infinite = g.creative; + horizon_client::pick_item::pick( + &mut g.inventory[..36], + &mut g.selected, + &stack, + infinite, + ); + Some(()) + }); + if picked.flatten().is_some() + && let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) + { + host.hub.send_to( + conn, + &C::SetHeldSlot(play::SetHeldSlot { + slot: g.selected as i32, + }), + ); + } + } + fn item_from_network( &self, host: &LanHost, @@ -1541,9 +1633,13 @@ impl Game<'_> { if let Some(victim) = Self::pvp_victim(host, conn, id) { if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) && self.pvp_land(host, victim, &strike) - && strike.stops_sprint() { - self.as_guest(host, conn, |g| g.stop_sprint_after_extra_knockback()); + self.as_guest(host, conn, |g| { + g.pvp_exhaustion(); + if strike.stops_sprint() { + g.stop_sprint_after_extra_knockback(); + } + }); } return; } @@ -1848,10 +1944,6 @@ impl Game<'_> { }; xp.respawn(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); (g.xp_level, g.xp_progress, g.xp_total) = (xp.level, xp.progress, xp.total); - // A new body: nothing given to the old one carries over. - if let Some(play) = host.play.get_mut(&conn) { - play.potions = Default::default(); - } let clock_rate = self.network_clock_rate(); let ctx = TickCtx { world: &mut self.world, @@ -2011,6 +2103,7 @@ impl Game<'_> { self.as_guest(host, conn, |g| { g.tick_fishing(); g.tick_maps(); + g.tick_lodestone_compasses(); g.count_tick_stats(sleeping); g.tick_advancements(); g.update_player_attributes(); @@ -2336,6 +2429,13 @@ impl Game<'_> { // ServerEntity.sendChanges sends it as it is after this travel. let marked = std::mem::take(&mut player.health.sync_velocity); let velocity = marked.then_some(player.velocity); + // Player.causeFallDamage: a fall of 2 blocks or more counts. + for event in &events { + if let MotionEvent::Fall(horizon_client::landing::FallEvent::Statistic(cm)) = event + { + game.stats.custom("fall_one_cm", *cm); + } + } game.record_combat(&events); game.wear_armor(&events); (events, velocity) diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index db6235c4d..461eaf5e1 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -127,9 +127,18 @@ impl Game<'_> { } let dropped = std::mem::take(&mut menu.dropped); let equipped = std::mem::take(&mut menu.equipped); + let brewed = std::mem::take(&mut menu.brewed); menu.drops.clear(); menu.crafted.clear(); store_player(menu, &mut host.hub.guests[gi]); + if !brewed.is_empty() { + let conn = host.hub.guests[gi].conn; + self.as_guest(host, conn, |g| { + for stack in &brewed { + g.trigger_brewed_potion(stack); + } + }); + } if !equipped.is_empty() { let conn = host.hub.guests[gi].conn; self.as_guest(host, conn, |g| { @@ -576,16 +585,18 @@ impl Game<'_> { /// A guest left: what their crafting grids and workstation held goes back into their /// inventory before it is saved (dropped where they stood if full). pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) { - let play = host.play.remove(&g.conn); + // The guest's play state stays: their statistics are awarded and saved + // after this (`HostEvent::Left`), which removes it. + let play = host.play.get_mut(&g.conn); let mut grid: Vec = g.craft_grid.iter_mut().filter_map(Option::take).collect(); g.craft_result = None; if let Some(play) = play { - if let Some((_, _, menu, _)) = play.crafting.table { + if let Some((_, _, menu, _)) = play.crafting.table.take() { grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); } // A workstation's inputs too. - if let Some(station) = &play.station { - grid.extend(super::lan_stations::station_inputs(station)); + if let Some(station) = play.station.take() { + grid.extend(super::lan_stations::station_inputs(&station)); } } if grid.is_empty() { diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 665710be2..d5317f88a 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -11,18 +11,6 @@ use horizon_client::lan::{ use horizon_protocol::entity_data::{Value, serializer}; use horizon_world::nbt::Tag; -/// `ArmorStand`'s default poses (head, body, left arm, right arm, left leg, -/// right leg), DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21), -/// under their `Pose` keys. -const STAND_POSES: [(&str, [f32; 3]); 6] = [ - ("Head", [0.0, 0.0, 0.0]), - ("Body", [0.0, 0.0, 0.0]), - ("LeftArm", [-10.0, 0.0, -10.0]), - ("RightArm", [-15.0, 0.0, 10.0]), - ("LeftLeg", [-1.0, 0.0, -1.0]), - ("RightLeg", [1.0, 0.0, 1.0]), -]; - fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> EntityState { EntityState { id: id as i32, @@ -61,28 +49,21 @@ fn vehicle_meta(hurt_time: i32, hurt_dir: i32, damage: f32) -> Vec<(u8, i32, Val meta } -/// An armor stand's pose from its compound (`ArmorStandPose`), each part -/// that differs from the default. -fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> { - let Some(pose) = raw.and_then(|t| t.get("Pose")) else { - return Vec::new(); - }; +/// An armor stand's pose (`ArmorStandPose`), each part that differs from the +/// default, as DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21). +fn stand_poses(a: &horizon_client::entities::ArmorStand) -> Vec<(u8, i32, Value)> { let mut meta = Vec::new(); - for (i, (key, default)) in STAND_POSES.iter().enumerate() { - let Some(Tag::List(values)) = pose.get(key) else { - continue; - }; - let mut r = *default; - for (k, v) in values.iter().take(3).enumerate() { - if let Tag::Float(bits) = v { - r[k] = f32::from_bits(*bits); - } - } - if r != *default { + for (i, (rotation, default)) in a + .pose + .iter() + .zip(horizon_client::entities::ArmorStand::DEFAULT_POSE) + .enumerate() + { + if *rotation != default { meta.push(( 16 + i as u8, serializer::ROTATIONS, - Value::Floats(r.to_vec()), + Value::Floats(rotation.to_vec()), )); } } @@ -185,7 +166,19 @@ impl Game<'_> { if flags != 0 { e.meta.push((15, serializer::BYTE, Value::Byte(flags))); } - e.meta.extend(stand_poses(self.persist.raw.get(&a.id))); + e.meta.extend(stand_poses(a)); + // A pose put back to its default (`/data`) is sent as that default. + e.defaults.push((15, serializer::BYTE, Value::Byte(0))); + for (i, default) in horizon_client::entities::ArmorStand::DEFAULT_POSE + .iter() + .enumerate() + { + e.defaults.push(( + 16 + i as u8, + serializer::ROTATIONS, + Value::Floats(default.to_vec()), + )); + } // Stored main hand, off hand, feet, legs, chest, head: the wire's slots 0 to 5. for (slot, item) in a.equipment.iter().enumerate() { if item.is_some() { @@ -225,6 +218,16 @@ impl Game<'_> { } out.push(e); } + for (p, &id) in &self.knot_ids { + // LeashFenceKnotEntity.getAddEntityPacket: the fence's block. + out.push(state( + id, + "minecraft:leash_knot", + p.map(f64::from), + 0.0, + false, + )); + } for p in &self.paintings { let mut e = state(p.id, "minecraft:painting", p.pos.map(f64::from), 0.0, false); // Direction.get2DDataValue (south 0, west 1, north 2, east 3) to its @@ -270,6 +273,24 @@ impl Game<'_> { /// Gives the entities Horizon keeps without an id one (`Entity.id`, from /// the same counter as the rest) before they are first tracked. pub(super) fn lan_assign_ids(&mut self) { + // LeashFenceKnotEntity: one per fence post with a lead on it + // (`notifyLeasheeRemoved` discards it once the last lead is gone). + let knots: Vec<[i32; 3]> = self + .mobs + .iter() + .filter(|m| !m.removed) + .filter_map(|m| match m.extra.leash { + Some(horizon_client::mobs::leash::Holder::Knot(p)) => Some(p), + _ => None, + }) + .collect(); + self.knot_ids.retain(|p, _| knots.contains(p)); + for p in knots { + self.knot_ids.entry(p).or_insert_with(|| { + self.next_entity += 1; + self.next_entity + }); + } let next = &mut self.next_entity; let mut give = |id: &mut u32| { if *id == 0 { @@ -342,6 +363,7 @@ impl Game<'_> { let mut e = state(p.id, kind, at(p.position), p.yaw, false); e.pitch = p.pitch; e.velocity = at(p.velocity); + e.needs_sync = p.needs_sync; // Projectile.getAddEntityPacket: the owner's id. e.data = match p.guest.and_then(|conn| hub.guest(conn)) { Some(g) => g.entity_id, @@ -466,10 +488,12 @@ impl Game<'_> { } out.push(e); } - // The dragon's breath clouds (AreaEffectCloud's DATA_RADIUS, + // The dragon's breath and lingering potion clouds (AreaEffectCloud's DATA_RADIUS, // DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the // client draws them from these (`tick_remote_clouds`). - let breath = self.network_particle( + // The hub is out of `self.lan` meanwhile, so it is passed in. + let breath = Self::hub_particle( + hub, &horizon_client::particles::ParticleOptions::simple( horizon_client::particles::ParticleType::DragonBreath, ), @@ -484,10 +508,14 @@ impl Game<'_> { for b in self.breath_clouds.iter().filter(|b| b.id != 0) { let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false); e.meta.push((8, serializer::FLOAT, Value::Float(b.radius))); - if b.age < 20 { + if b.waiting() { e.meta.push((9, serializer::BOOLEAN, Value::Bool(true))); } - if let Some(p) = &breath { + let particle = match &b.potion { + Some(p) => self.network_particle(&p.particle(), None), + None => breath.clone(), + }; + if let Some(p) = &particle { e.meta .push((10, serializer::PARTICLE, Value::Particle(p.clone()))); } @@ -527,11 +555,9 @@ mod tests { #[test] fn armor_stand_poses_send_only_what_differs() { - let tag = - horizon_world::nbt::parse_snbt("{Pose:{Head:[10f,20f,0f],LeftArm:[-10f,0f,-10f]}}") - .unwrap() - .0; - let meta = stand_poses(Some(&tag)); + let mut stand = horizon_client::entities::ArmorStand::new(1, Default::default(), 0.0); + stand.pose[0] = [10.0, 20.0, 0.0]; + let meta = stand_poses(&stand); assert_eq!( meta, vec![( @@ -540,6 +566,7 @@ mod tests { Value::Floats(vec![10.0, 20.0, 0.0]) )] ); - assert!(stand_poses(None).is_empty()); + let plain = horizon_client::entities::ArmorStand::new(1, Default::default(), 0.0); + assert!(stand_poses(&plain).is_empty()); } } diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index db042be43..42253afa8 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -5,7 +5,7 @@ //! (hits, pushes, fire, its projectiles) runs with that guest swapped in. use super::{Game, lan::LanHost}; use horizon_client::{ - mobs::{Mob, MobEvent, PlayerView, Who}, + mobs::{Mob, MobEvent, PlayerView, Species, Who}, projectiles::{Hit, Projectile}, }; use horizon_core::geometry::{Aabb, Vec3}; @@ -28,6 +28,22 @@ pub(super) fn player_for( ) -> Option { let targeting = m.ai.target == Some(Who::Player) || m.ai.last_hurt_by == Some(Who::Player) && m.age as i32 - m.ai.last_hurt_by_time <= 100; + // A tame wolf or cat sees its owner (`TamableAnimal.getOwner`), while they + // are in play, whoever is nearer. Not while it targets or was just hurt by + // a player: then `Who::Player` is that attacker, whoever it is, and the + // owner goals ignore it until the wolf lets go. + if !targeting + && matches!(m.species(), Species::Wolf | Species::Cat) + && m.extra.tame + && let Some(owner) = m.extra.owner + { + if host.is_some_and(|v| v.alive && v.uuid == owner) { + return None; + } + if let Some((conn, _)) = guests.iter().find(|(_, v)| v.alive && v.uuid == owner) { + return Some(*conn); + } + } choose(m.position, targeting, host, guests, bound) } @@ -65,11 +81,16 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool { matches!( e, MobEvent::AttackPlayer(..) + | MobEvent::AttackPlayerWithEffect { .. } | MobEvent::DamagePlayer { .. } | MobEvent::Push { target: Who::Player, .. } + | MobEvent::Knockback { + target: Who::Player, + .. + } | MobEvent::Ignite { target: Who::Player, .. @@ -353,22 +374,27 @@ mod tests { alive: true, creative, sneaking: false, + swimming: false, look: [0.0; 3], main_hand: None, off_hand: None, head: None, armor_cover: 0.0, + invisible: false, spectator: false, gold_armor: false, hurt_by: None, last_hurt: None, velocity: Vec3::ZERO, yaw: 0.0, + sprinting: false, + riding: false, hero: false, effects: Vec::new(), uuid: [0; 4], allies: Default::default(), remote: false, + passenger: false, } } diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 648cef962..d8c14e0b5 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -156,7 +156,7 @@ impl Game<'_> { /// `network_particle` for a hub that is out of `self.lan` meanwhile (a /// guest's turn). - fn hub_particle( + pub(super) fn hub_particle( hub: &Hub, options: &ParticleOptions, state: Option, @@ -247,14 +247,10 @@ impl Game<'_> { return; }; let (d, s) = (p.dist.map(f64::from), p.max_speed.map(f64::from)); - // ClientLevel.addParticle: the camera's 32 blocks unless the packet - // (`force`) or the type overrides the limiter. + // ClientLevel.addParticle: the camera's 32 blocks and the Particles + // option, unless the packet or the type overrides the limiter. let add = |particles: &mut horizon_client::particles::ParticleEngine, at, v| { - if p.override_limiter { - particles.create(&options, at, v); - } else { - particles.add(&options, at, v); - } + particles.add_with(&options, at, v, p.override_limiter, p.always_show); }; if p.count == 0 { add( @@ -318,16 +314,86 @@ impl Game<'_> { } } + /// `ServerLevel.sendParticles` for the players a server serves: one + /// `ClientboundLevelParticlesPacket` to each player in the level whose + /// block is within 32 blocks of `at`. The window's own player is not + /// sent it (the caller draws it in this window). While the host holds + /// the players (a guest's turn through `as_guest`, a host's hit on a + /// guest) the packet waits for the turn to end so that it reaches every + /// player, the guest too. + pub(super) fn lan_send_particles( + &mut self, + options: &ParticleOptions, + at: [f64; 3], + spread: [f64; 3], + speed: f64, + count: u32, + ) { + if self.lan.is_none() { + // The server is running (its sounds are captured for the guests). + if self.audio.capture.is_some() { + self.creatures + .lan_particles + .push((options.clone(), at, spread, speed, count)); + } + return; + } + let Some(particle) = self.network_particle(options, None) else { + return; + }; + let Some(host) = self.lan.as_ref() else { + return; + }; + let body = C::LevelParticles(play::LevelParticles { + particle, + override_limiter: false, + always_show: false, + pos: at, + dist: spread.map(|d| d as f32), + max_speed: [speed as f32; 3], + count: count as i32, + randomization: 0, + }) + .encode(); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + // BlockPos.closerToCenterThan(at, 32): from the centre of the + // player's block. + let d: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if d < 32.0 * 32.0 { + g.sender.send(body.clone()); + } + } + } + + /// The particles guests' turns put off. + pub(super) fn flush_lan_particles(&mut self) { + for (options, at, spread, speed, count) in std::mem::take(&mut self.creatures.lan_particles) + { + self.lan_send_particles(&options, at, spread, speed, count); + } + } + /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the /// motion a hurt player is sent), so the packet carries neither. pub(super) fn lan_explode( - &self, + &mut self, center: [f64; 3], small: bool, radius: f32, block_count: usize, ) { + // In a guest's turn (their hit on an end crystal or a minecart) the + // host holds the players (`as_guest`): the packet waits for the turn + // to end so that it reaches every player, the guest too. + if self.lan_acting.is_some() && self.lan.is_none() { + self.creatures + .lan_explosions + .push((center, small, radius, block_count)); + return; + } let emitter = if small { "minecraft:explosion" } else { @@ -341,6 +407,15 @@ impl Game<'_> { } } + /// The explosions guests' turns put off. + pub(super) fn flush_lan_explosions(&mut self) { + for (center, small, radius, block_count) in + std::mem::take(&mut self.creatures.lan_explosions) + { + self.lan_explode(center, small, radius, block_count); + } + } + /// A wind charge's burst (`AbstractWindCharge.explode`): gust emitters, /// no block particles, and for each player it pushed the push /// (`ServerExplosion.hitPlayers`), which only that client applies, as diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 65520221a..27c7ada1f 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -40,6 +40,8 @@ pub(super) struct Strike { /// `Player.attack`'s `magicBoost > 0`: the enchantments added damage. magic: bool, from: [f64; 3], + /// `getSecondsToDisableBlocking` of the attacker's weapon. + disable_blocking: f32, sweep: Option<[f64; 3]>, /// `causeExtraKnockback`: its strength and direction (the attacker's /// yaw), and whether the hit is a sprinting knockback attack. @@ -86,9 +88,11 @@ impl Game<'_> { }; if let Some(strike) = self.pvp_strike() && self.pvp_land(&mut host, Victim::Guest(conn), &strike) - && strike.stops_sprint() { - self.stop_sprint_after_extra_knockback(); + self.pvp_exhaustion(); + if strike.stops_sprint() { + self.stop_sprint_after_extra_knockback(); + } } self.lan = Some(host); true @@ -106,8 +110,18 @@ impl Game<'_> { .map(|g| Victim::Guest(g.conn)) } + /// `Player.attack`'s `causeFoodExhaustion(0.1F)`, charged to the attacker + /// (the host, or a guest swapped in) only once the hit hurt the victim. + pub(super) fn pvp_exhaustion(&mut self) { + if let Some(p) = self.player.as_mut() + && !self.creative + { + p.cause_food_exhaustion(0.1); + } + } + /// The attacker's side of `Player.attack` (the host, or a guest swapped - /// in): the damage, the charge reset, the exhaustion and the swing. + /// in): the damage, the charge reset and the swing. pub(super) fn pvp_strike(&mut self) -> Option { let p = self.player.as_ref()?; let from = [p.position.x, p.position.y, p.position.z]; @@ -116,12 +130,15 @@ impl Game<'_> { let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale); let (xd, zd) = self.extra_knockback_direction(); self.attack_ticks = 0; - if let Some(p) = self.player.as_mut() - && !self.creative - { - p.cause_food_exhaustion(0.1); - } self.swing_arm(); + // LivingEntity.getSecondsToDisableBlocking: the held weapon's value, + // none while another item is in use. + let disable_blocking = if self.using.is_some() { + 0.0 + } else { + self.attack_item_info() + .map_or(0.0, |i| i.disable_blocking_seconds) + }; Some(Strike { attacker: self.lan_acting, amount, @@ -129,6 +146,7 @@ impl Game<'_> { crit, magic, from, + disable_blocking, sweep, knockback: (strength, xd, zd), knockback_attack, @@ -243,7 +261,9 @@ impl Game<'_> { // Player.attack: the hurt (with its knockback away from the // attacker), then causeExtraKnockback along the attacker's yaw. let land = |g: &mut Self| { + g.combat.player_attacker = Some((s.from, s.disable_blocking)); let hurt = g.mob_hits_player(s.amount, s.from, "minecraft:player_attack"); + g.combat.player_attacker = None; let (strength, xd, zd) = s.knockback; if hurt && strength > 0.0 { g.knock_back_player(f64::from(strength), xd, zd); @@ -260,6 +280,30 @@ impl Game<'_> { } else { Default::default() }; + // ServerPlayer.awardKillScore: the blow that kills a player. + if hurt { + let died = match victim { + // A totem that fired is applied on the next tick_totem, so the + // victim is still at zero health but is not dying. + Victim::Host => self + .player + .as_ref() + .is_some_and(|p| p.health.dead_or_dying() && !p.health.totem_used), + Victim::Guest(conn) => host + .hub + .guest(conn) + .and_then(|g| g.motion.as_deref()) + .is_some_and(|p| p.health.dead_or_dying() && !p.health.totem_used), + }; + if died { + match s.attacker { + Some(conn) => { + self.as_guest(host, conn, |g| g.stats.custom("player_kills", 1)); + } + None => self.stats.custom("player_kills", 1), + } + } + } if hurt && (s.crit || s.magic) { let target = match victim { Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)), diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 418ed9c2a..cfd65403a 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -317,6 +317,8 @@ impl Game<'_> { self.as_guest(host, conn, |game| { game.give_levels(-need); game.stats.custom("enchant_item", 1); + // CriteriaTriggers.ENCHANTED_ITEM, with the levels it cost. + game.trigger_enchanted_item(&enchanted, need); }); host.hub.guests[gi].xp_seed = self.world.random.next_int(); let env = self.menu_env(); diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 7beeeba2f..0177a24b1 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -277,7 +277,12 @@ impl Game<'_> { g.carried = menu.carried.take(); } self.register_exploration_maps(made); - gm.merchant.session = self.merchant_apply(session, gm.merchant.mob); + let (session, traded) = self.merchant_apply(session, gm.merchant.mob); + gm.merchant.session = session; + if !traded.is_empty() { + // The guest's own statistic and advancements. + self.as_guest(host, conn, |g| g.merchant_traded(gm.merchant.mob, &traded)); + } self.drop_guest_items(host, gi, dropped); self.lan_send_offers(host, conn, &mut gm, false); self.lan_send_merchant_content(host, conn, &mut gm); diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index ca70351c6..877609d57 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -386,6 +386,8 @@ impl Game<'_> { layer: 0, color, light: packed, + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index dc815a39f..c658743f0 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,28 +1,34 @@ //! Level events whose client handler (`LevelEventHandler`) spawns particles //! on a block: bone meal's growth (1505), dragon egg teleportation (2015), a -//! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax -//! off (3004) and scraping (3005). +//! consumable's teleport (2017), an enderman's (2018), electric sparks (3002), +//! waxing (3003), wax off (3004) and scraping (3005), plus the smoke, drips, +//! egg and dragon fireball particles of 1501, 1502, 1504, 2006, 2009, 2012 +//! and 3009. use super::Game; use horizon_client::items::ItemStack; use horizon_client::particles::{self, ParticleOptions, ParticleType}; -use horizon_core::{position::BlockPos, random::RandomSource}; +use horizon_core::{geometry::trig, position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; +use horizon_world::registry::BlockStateId; impl Game<'_> { pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) { - self.particles - .block_teleportation(pos, data, [16, 8, 16], self.settings.particles); + self.particles.block_teleportation(pos, data, [16, 8, 16]); } /// Event 2016: `Shulker.teleportSomewhere`'s particles between the /// shell's old and new cells. pub(super) fn shulker_teleport_particles(&mut self, pos: [i32; 3], data: i32) { - self.particles - .block_teleportation(pos, data, [8, 8, 8], self.settings.particles); + self.particles.block_teleportation(pos, data, [8, 8, 8]); } /// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles. pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) { self.particles - .block_teleportation(pos, data, [127, 127, 127], self.settings.particles); + .block_teleportation(pos, data, [127, 127, 127]); + } + /// Event 2018: an enderman's portal trail. + pub(super) fn enderman_teleport_particles(&mut self, pos: [i32; 3], data: i32) { + self.particles + .enderman_teleportation(pos, data, self.settings.particles); } /// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client /// level's random. @@ -40,7 +46,7 @@ impl Game<'_> { // 3002 with an axis: a lightning rod; otherwise copper cleaned by lightning. match usize::try_from(data) { Ok(axis) if id == 3002 && axis < 3 => { - particles::along_axis(random, axis, p, |p, v| spawned.push((p, v))); + particles::along_axis(random, axis, p, (10, 19), |p, v| spawned.push((p, v))); } _ => particles::on_block_faces(random, p, |p, v| spawned.push((p, v))), } @@ -72,24 +78,42 @@ impl Game<'_> { } else { // ParticleUtils.spawnParticleInBlock: up to the // block's shape (a full block when air). - let inside = self.world.block(at[0], at[1], at[2]); - let height = if facts.is_air(inside) { - 1.0 - } else { - facts - .get(inside) - .outline - .iter() - .map(|b| b[4]) - .fold(0.0, f64::max) - }; - (at, count, 0.5, height, true) + (at, count, 0.5, self.block_shape_top(at), true) } } None if &*facts.get(state).name == "minecraft:water" => (p, count * 3, 3.0, 1.0, false), None => return, }; - let options = ParticleOptions::simple(ParticleType::HappyVillager); + self.spawn_particles(at, count, xz, height, floating, ParticleType::HappyVillager); + } + /// `BlockState.getShape(..).max(Y)` of the block at `at`, 1.0 for air. + fn block_shape_top(&self, at: [i32; 3]) -> f64 { + let facts = self.res.facts(); + let inside = self.world.block(at[0], at[1], at[2]); + if facts.is_air(inside) { + 1.0 + } else { + facts + .get(inside) + .outline + .iter() + .map(|b| b[4]) + .fold(0.0, f64::max) + } + } + /// `ParticleUtils.spawnParticles`: `count` slow particles spread over + /// `xz` blocks around `at` and `height` up, only above solid ground + /// unless floating ones are allowed. + fn spawn_particles( + &mut self, + at: [i32; 3], + count: i32, + xz: f64, + height: f64, + floating: bool, + ty: ParticleType, + ) { + let options = ParticleOptions::simple(ty); for _ in 0..count.max(0) { let r = self.particles.level_random(); let v = [0.0; 3].map(|_: f64| r.next_gaussian() * 0.02); @@ -108,6 +132,161 @@ impl Game<'_> { } } } + /// `LevelEventHandler` 2012 (a turtle egg laid on sand): + /// `ParticleUtils.spawnParticleInBlock` with happy villager sparks. + pub(super) fn turtle_egg_particles(&mut self, pos: BlockPos, count: i32) { + let at = [pos.x, pos.y, pos.z]; + let height = self.block_shape_top(at); + self.spawn_particles(at, count, 0.5, height, true, ParticleType::HappyVillager); + } + /// `LevelEventHandler` 3009 (a sniffer egg cracking on moss): + /// `spawnParticlesOnBlockFaces(.., EGG_CRACK, UniformInt.of(3, 6))`. + pub(super) fn sniffer_egg_crack_particles(&mut self, pos: BlockPos) { + let mut spawned = Vec::new(); + particles::on_block_faces_between( + self.particles.level_random(), + [pos.x, pos.y, pos.z], + 3, + 6, + |p, v| spawned.push((p, v)), + ); + let options = ParticleOptions::simple(ParticleType::EggCrack); + for (p, v) in spawned { + self.particles.add(&options, p, v); + } + } + /// `LevelEventHandler` 1501 (lava put out) and 2009 (a wet sponge dried): + /// eight puffs just above the block, drawn after the sound. + pub(super) fn puffs_above_block(&mut self, pos: BlockPos, ty: ParticleType) { + let options = ParticleOptions::simple(ty); + for _ in 0..8 { + let r = self.particles.level_random(); + let x = f64::from(pos.x) + r.next_double(); + let z = f64::from(pos.z) + r.next_double(); + self.particles + .add(&options, [x, f64::from(pos.y) + 1.2, z], [0.0; 3]); + } + } + /// `LevelEventHandler` 1502 (a redstone torch burning out): five smoke + /// puffs inside the block, drawn after the sound. + pub(super) fn torch_burnout_smoke(&mut self, pos: BlockPos) { + let options = ParticleOptions::simple(ParticleType::Smoke); + for _ in 0..5 { + let r = self.particles.level_random(); + let x = f64::from(pos.x) + r.next_double() * 0.6 + 0.2; + let y = f64::from(pos.y) + r.next_double() * 0.6 + 0.2; + let z = f64::from(pos.z) + r.next_double() * 0.6 + 0.2; + self.particles.add(&options, [x, y, z], [0.0; 3]); + } + } + /// `LevelEventHandler` 2006 (`DragonFireball.onHit`): 200 dragon breath + /// particles thrown outwards, then the explosion sound when `data` is 1. + pub(super) fn dragon_fireball_burst(&mut self, pos: BlockPos, data: i32) { + for _ in 0..200 { + let r = self.particles.level_random(); + let dist = r.next_float() * 4.0; + let angle = r.next_float() * std::f32::consts::TAU; + let vx = f64::from(trig::cos(f64::from(angle)) * dist); + let vy = 0.01 + r.next_double() * 0.5; + let vz = f64::from(trig::sin(f64::from(angle)) * dist); + let options = ParticleOptions { + scale: dist, + ..ParticleOptions::simple(ParticleType::DragonBreath) + }; + self.particles.add( + &options, + [ + f64::from(pos.x) + vx * 0.1, + f64::from(pos.y) + 0.3, + f64::from(pos.z) + vz * 0.1, + ], + [vx, vy, vz], + ); + } + if data == 1 { + let at = [pos.x, pos.y, pos.z].map(|v| f64::from(v) + 0.5); + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play( + "minecraft:entity.dragon_fireball.explode", + Some(at), + 1.0, + pitch, + ); + } + } + /// `SpeleothemBlock.isStalactite`: a speleothem whose tip points down. + fn is_stalactite(&self, state: BlockStateId) -> bool { + self.res.facts().get(state).has_class("SpeleothemBlock") + && self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("vertical_direction")) + .is_some_and(|d| d == "down") + } + /// `LevelEventHandler` 1504: `PointedDripstoneBlock.spawnDripParticle` at + /// the tip `pos`. The fluid above the stalactite's root picks the drip; + /// with none, the dimension's default (lava in the Nether). + pub(super) fn dripstone_drip_particle(&mut self, pos: BlockPos) { + let tip_state = self.world.block(pos.x, pos.y, pos.z); + if !self.is_stalactite(tip_state) { + return; + } + // findRootBlock: up through the same stalactite, at most 11 steps. + let tip_name = self.res.facts().get(tip_state).name.clone(); + let mut root = None; + for step in 1..11 { + let y = pos.y + step; + if !(horizon_client::chunk::MIN_Y + ..horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT) + .contains(&y) + { + break; + } + let state = self.world.block(pos.x, y, pos.z); + if self.res.facts().get(state).name != tip_name { + root = Some(y); + break; + } + if !self.is_stalactite(state) { + break; + } + } + let Some(root_y) = root else { + return; + }; + let above = self.world.block(pos.x, root_y + 1, pos.z); + let above_facts = self.res.facts().get(above); + let nether = self.dim == super::Dim::Nether; + let fluid = if &*above_facts.name == "minecraft:mud" && !nether { + horizon_client::blocks::Fluid::Water + } else { + above_facts.fluid + }; + let ty = match fluid { + horizon_client::blocks::Fluid::Water => ParticleType::DrippingDripstoneWater, + horizon_client::blocks::Fluid::Lava => ParticleType::DrippingDripstoneLava, + horizon_client::blocks::Fluid::None if nether => ParticleType::DrippingDripstoneLava, + horizon_client::blocks::Fluid::None => ParticleType::DrippingDripstoneWater, + }; + let offset = self + .pack + .context + .tables + .offset(tip_state, pos.x, pos.z) + .unwrap_or([0.0; 3]); + // The tip shape starts 5/16 up; the particle sits a pixel below that. + self.particles.add( + &ParticleOptions::simple(ty), + [ + f64::from(pos.x) + 0.5 + offset[0], + f64::from(pos.y) + 5.0 / 16.0 - 0.0625, + f64::from(pos.z) + 0.5 + offset[2], + ], + [0.0; 3], + ); + } /// `ServerLevel.globalLevelEvent`: heard by every player on the server /// (an end portal opening, the dragon's death roar): here, and sent to /// every guest whatever their dimension. diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index b0c10e34b..ab316c4c6 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -66,6 +66,8 @@ pub(super) struct Parked { tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, mobs: Vec, + /// The entity ids of the level's fence knots (`knot_ids`). + knot_ids: HashMap<[i32; 3], u32>, projectiles: Vec, dropped: Vec, orbs: Vec, @@ -170,6 +172,7 @@ impl Game<'_> { tnts: Vec::new(), hoppers: HashMap::new(), mobs: Vec::new(), + knot_ids: HashMap::new(), projectiles: Vec::new(), dropped: Vec::new(), orbs: Vec::new(), @@ -223,6 +226,7 @@ impl Game<'_> { swap(&mut self.tnts, &mut p.tnts); swap(&mut self.hoppers, &mut p.hoppers); swap(&mut self.mobs, &mut p.mobs); + swap(&mut self.knot_ids, &mut p.knot_ids); swap(&mut self.creatures.projectiles, &mut p.projectiles); swap(&mut self.dropped, &mut p.dropped); swap(&mut self.orbs, &mut p.orbs); diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 8a3ac2745..921244e6d 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -16,7 +16,7 @@ pub(super) struct Bolt { flashes: i32, seed: i64, visual_only: bool, - /// Mooshrooms switch colour once per bolt. + /// Mooshrooms and copper golems change once per bolt. converted: Vec, } impl Game<'_> { @@ -278,6 +278,13 @@ impl Game<'_> { } self.strike_rod(b.at); } + // LightningBolt.tick runs clearCopperOnLightningStrike for + // every server bolt, a skeleton trap's visual one included; + // a client's copy of a server bolt (spawn_remote_bolt) only + // flashes. + if self.remote.is_none() { + self.bolt_clear_copper(b.at); + } } b.life -= 1; if b.life < 0 { @@ -334,6 +341,16 @@ impl Game<'_> { self.level_event_at(3002, p, axis); } } + /// `LightningBolt.clearCopperOnLightningStrike` at the block the bolt struck. + fn bolt_clear_copper(&mut self, at: [f64; 3]) { + let p = BlockPos::new( + at[0].floor() as i32, + (at[1] - 1.0e-6).floor() as i32, + at[2].floor() as i32, + ); + self.with_level(|b, level, ticks| b.lightning_clear_copper(level, ticks, p)); + let _ = self.process_level_events(); + } /// `thunderHit` for entities within 3 blocks (up to 9 above). fn thunder_hit(&mut self, b: &mut Bolt) { let at = b.at; @@ -393,6 +410,17 @@ impl Game<'_> { continue; } Species::Creeper => m.extra.charged = true, + // CopperGolem.thunderHit (after Entity.thunderHit's fire and + // damage): once per bolt, an oxidized golem goes back one step + // and its weathering timer (or wax, -2) is reset to -1. + Species::CopperGolem if !b.converted.contains(&m.id) => { + b.converted.push(m.id); + if m.extra.variant > 0 { + m.extra.vector[0] = -1.0; + m.extra.variant = + horizon_client::mobs::copper_golem::weather_previous(m.extra.variant); + } + } _ => {} } // Entity.thunderHit: burning (8 seconds) and 5 lightning damage. diff --git a/crates/horizon-client/src/game/llamas.rs b/crates/horizon-client/src/game/llamas.rs index 1ce518f31..080343952 100644 --- a/crates/horizon-client/src/game/llamas.rs +++ b/crates/horizon-client/src/game/llamas.rs @@ -25,11 +25,13 @@ impl Game<'_> { }; let m = &mut self.mobs[index]; let mut used = false; + let mut loved = false; if item == "minecraft:hay_block" && m.extra.tame && m.extra.age == 0 && m.extra.in_love <= 0 { m.extra.in_love = 600; m.extra.love_player = true; used = true; + loved = true; } if m.health < m.attrs.max_health { m.health = (m.health + heal).min(m.attrs.max_health); @@ -57,6 +59,10 @@ impl Game<'_> { if !used { return false; } + // Animal.setInLove: entity event 18. + if loved { + self.mob_event_particles(self.mobs[index].id, 18); + } self.llama_sound(index, "entity.llama.eat", 1.0); self.consume_held(); true diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs index 34c968980..80f09a331 100644 --- a/crates/horizon-client/src/game/mace.rs +++ b/crates/horizon-client/src/game/mace.rs @@ -37,6 +37,41 @@ pub(super) fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool { || m.species() == Species::Allay && m.extra.tame } +/// A smash's knockback on the players, put off while a guest's turn holds +/// the other players. +pub(super) struct SmashPush { + center: Vec3, + heavy: f64, + attacker: Option, + team: Option, +} +/// `MaceItem.getKnockbackPower` and the push of one entity at `at`, `heavy` +/// being 2 after a fall of more than five blocks. +fn smash_push(center: Vec3, heavy: f64, at: Vec3, velocity: &mut Vec3, resistance: f64) { + let d = [at.x - center.x, at.y - center.y, at.z - center.z]; + let distance_sqr = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + if distance_sqr > KNOCKBACK_RADIUS.powi(2) { + return; + } + let length = distance_sqr.sqrt(); + let power = + (KNOCKBACK_RADIUS - length) * f64::from(KNOCKBACK_POWER) * heavy * (1.0 - resistance); + if power <= 0.0 { + return; + } + // Vec3.normalize: a vector shorter than 1e-5 has no direction. + let (x, z) = if length < f64::from(1.0e-5f32) { + (0.0, 0.0) + } else { + (d[0] / length * power, d[2] / length * power) + }; + *velocity = Vec3::new( + velocity.x + x, + velocity.y + f64::from(KNOCKBACK_POWER), + velocity.z + z, + ); +} + impl Game<'_> { fn holds_mace(&self) -> bool { self.inventory[self.selected] @@ -220,44 +255,75 @@ impl Game<'_> { ]; self.level_event_at(2013, on_pos, 750); let heavy = if fall > HEAVY_THRESHOLD { 2.0 } else { 1.0 }; - // getKnockbackPower and the push of one entity at `at`. - let push = |at: Vec3, velocity: &mut Vec3, resistance: f64| { - let d = [at.x - center.x, at.y - center.y, at.z - center.z]; - let distance_sqr = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; - if distance_sqr > KNOCKBACK_RADIUS.powi(2) { - return; - } - let length = distance_sqr.sqrt(); - let power = (KNOCKBACK_RADIUS - length) - * f64::from(KNOCKBACK_POWER) - * heavy - * (1.0 - resistance); - if power <= 0.0 { - return; - } - // Vec3.normalize: a vector shorter than 1e-5 has no direction. - let (x, z) = if length < f64::from(1.0e-5f32) { - (0.0, 0.0) - } else { - (d[0] / length * power, d[2] / length * power) - }; - *velocity = Vec3::new( - velocity.x + x, - velocity.y + f64::from(KNOCKBACK_POWER), - velocity.z + z, - ); - }; let player = self.level.player_uuid.or(Some([0, 0, 0, 1])); for m in self .mobs .iter_mut() .filter(|m| m.id != id && m.alive() && !m.removed && !ally_of_player(m, player)) { - push(m.position, &mut m.velocity, m.attrs.knockback_resistance); + smash_push( + center, + heavy, + m.position, + &mut m.velocity, + m.attrs.knockback_resistance, + ); } for s in self.armor_stands.iter_mut().filter(|s| !s.marker) { - push(s.position, &mut s.velocity, 0.0); + smash_push(center, heavy, s.position, &mut s.velocity, 0.0); } + // The host and the LAN guests are living entities too. A guest's turn + // holds the other players (`as_guest`): the push waits for it to end. + let push = SmashPush { + center, + heavy, + attacker: self.lan_acting, + team: self.player_team().cloned(), + }; + if self.lan_acting.is_some() { + self.creatures.smash_pushes.push(push); + } else { + self.smash_push_players(&push); + } + } + /// `MaceItem.knockback` on the players but the attacker: the host unless + /// it attacked, and every guest but the attacker. + fn smash_push_players(&mut self, push: &SmashPush) { + if push.attacker.is_some() { + self.smash_push_player(push); + } + self.each_guest_hit_except(push.attacker, |g| g.smash_push_player(push)); + } + /// The pushes guests' smashes put off. + pub(super) fn flush_smash_pushes(&mut self) { + for push in std::mem::take(&mut self.creatures.smash_pushes) { + self.smash_push_players(&push); + } + } + /// `MaceItem.knockback` on the player here (the host, or the guest swapped + /// in): not a spectator, an ally of the attacker (`isAlliedTo`: the same + /// team) or a creative player flying. + fn smash_push_player(&mut self, push: &SmashPush) { + if self.spectator() + || horizon_client::scoreboard::teams_allied(push.team.as_ref(), self.player_team()) + { + return; + } + let creative = self.creative; + let Some(p) = self.player.as_mut() else { + return; + }; + if creative && p.flying { + return; + } + let resistance = p.attribute("minecraft:knockback_resistance").unwrap_or(0.0); + smash_push( + push.center, + push.heavy, + p.position, + &mut p.velocity, + resistance, + ); } /// `ServerPlayer.checkFallDamage` after a smash on a grounded target: /// the landing block's particles, 50 for every block fallen (200 at most). diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index bb936744b..0abf36a73 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -41,6 +41,8 @@ enum Kind { Crafter, /// `BrewingStandBlockEntity` (a `WorldlyContainer`). Brewing, + /// `ChiseledBookShelfBlockEntity`: books only, one to a slot. + Bookshelf, /// `ComposterBlock.getContainer` at this level (a `WorldlyContainerHolder` /// without a block entity): input below 7, empty at 7, bone meal at 8. Composter(i32), @@ -82,7 +84,7 @@ impl View { } } -fn dir_from_name(name: &str) -> Option { +pub(super) fn dir_from_name(name: &str) -> Option { Some(match name { "down" => Direction::Down, "up" => Direction::Up, @@ -169,6 +171,7 @@ impl Containers<'_> { (BlockEntity::Furnace(_), _) => Kind::Furnace, (BlockEntity::Crafter(_), _) => Kind::Crafter, (BlockEntity::Brewing(_), _) => Kind::Brewing, + (BlockEntity::ChiseledBookshelf(_), _) => Kind::Bookshelf, (_, "minecraft:hopper") => Kind::Hopper, _ => Kind::Generic, }; @@ -250,6 +253,16 @@ impl Containers<'_> { _ => false, }; } + if view.kind == Kind::Bookshelf { + // ListBackedContainer.canPlaceItem: `acceptsItemType` (the books) + // and a free slot, as `getMaxStackSize` is 1. + return self + .items + .item_tags + .get("minecraft:bookshelf_books") + .is_some_and(|m| m.contains(&*stack.item)) + && self.get(view, slot).is_none(); + } if view.kind == Kind::Brewing { // BrewingStandBlockEntity.canPlaceItem return match slot { @@ -399,6 +412,45 @@ pub(super) fn container_signal( .map_or(0, |v| c.signal(&v)) } +/// `ChiseledBookShelfBlock.getAnalogOutputSignal` and +/// `ShelfBlock.getAnalogOutputSignal`, from the block entity Horizon keeps as +/// it was loaded; `None` for any other block. `direction` points from the +/// block to the comparator. +pub(super) fn shelf_signal( + world: &World, + registry: &'static horizon_world::registry::BlockRegistry, + state: BlockStateId, + pos: BlockPos, + direction: Direction, +) -> Option { + let info = registry.state(state)?; + let chiseled = info.name == "minecraft:chiseled_bookshelf"; + if !chiseled && !info.name.ends_with("_shelf") { + return None; + } + if chiseled { + // The last slot touched, plus one (`lastInteractedSlot` starts at -1). + return Some(match world.block_entities.get(&(pos.x, pos.y, pos.z)) { + Some(BlockEntity::ChiseledBookshelf(b)) => b.last_slot + 1, + _ => 0, + }); + } + let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]); + // Only read from the back: a bit for each of the three slots in use. + let facing = info.properties.get("facing").and_then(|f| dir_from_name(f)); + if facing.map(Direction::opposite) != Some(direction) { + return Some(0); + } + let items = horizon_client::save::decode_items(tag.as_ref().and_then(|t| t.get("Items")), 3); + Some( + items + .iter() + .enumerate() + .map(|(slot, item)| i32::from(item.is_some()) << slot) + .sum(), + ) +} + impl Game<'_> { fn containers(&self) -> Containers<'_> { Containers { @@ -433,6 +485,7 @@ impl Game<'_> { if pos.1 == super::minecarts::CART_KEY_Y { return; } + self.chiseled_bookshelf_synced(pos); // A double chest's other half changes with it. let halves: Vec = std::iter::once(pos) .chain(self.chest_other_half(pos)) @@ -595,27 +648,41 @@ impl Game<'_> { self.container_changed(pos); } } - /// `HopperBlockEntity.ejectItems`. + /// `HopperBlockEntity.ejectItems`: into the block container in front, else + /// a container entity there (`getContainerAt`). fn hopper_eject(&mut self, pos: Pos, hopper: &View) -> bool { let state = self.world.block(pos.0, pos.1, pos.2); let c = self.containers(); let Some(facing) = c.prop(state, "facing").and_then(dir_from_name) else { return false; }; - let Some(target) = c.view(offset(pos, facing), false) else { + let front = offset(pos, facing); + let face = facing.opposite(); + if let Some(target) = c.view(front, false) { + return self.eject_into(pos, hopper, &target, face); + } + let Some(id) = self.entity_container_at([ + f64::from(front.0) + 0.5, + f64::from(front.1) + 0.5, + f64::from(front.2) + 0.5, + ]) else { return false; }; - let face = facing.opposite(); - if c.is_full(&target, face) { + self.with_entity_container(id, |g, target| g.eject_into(pos, hopper, target, face)) + .unwrap_or(false) + } + /// The rest of `HopperBlockEntity.ejectItems`: one item into `target`. + fn eject_into(&mut self, pos: Pos, hopper: &View, target: &View, face: Direction) -> bool { + if self.containers().is_full(target, face) { return false; } for slot in 0..hopper.len() { let Some(one) = self.take_one(hopper, slot) else { continue; }; - match self.add_item(Some(pos), &target, one, Some(face)) { + match self.add_item(Some(pos), target, one, Some(face)) { None => { - self.view_changed(&target); + self.view_changed(target); return true; } Some(rest) => self.put_back(hopper, slot, rest), @@ -626,46 +693,13 @@ impl Game<'_> { /// `HopperBlockEntity.suckInItems`: from the container above, or item entities. fn hopper_suck(&mut self, pos: Pos, hopper: &View) -> bool { let above = (pos.0, pos.1 + 1, pos.2); - let c = self.containers(); - if let Some(source) = c.view(above, false) { - if let Kind::Composter(level) = source.kind { - if level != 8 { - return false; - } - // tryTakeInItemFromSlot on the OutputContainer: removeItem calls - // its setChanged, which empties the composter, and so does the - // second setChanged after the move or, when the hopper has no - // room, the setItem putting the bone meal back into the detached - // container (whose bone meal is lost with it). - let bone_meal = c.bone_meal.clone(); - let at = BlockPos::new(above.0, above.1, above.2); - self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); - let moved = self.add_item(None, hopper, bone_meal, None).is_none(); - self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); - self.world.modified.insert((above.0 >> 4, above.2 >> 4)); - return moved; - } - let source_hopper = (source.kind == Kind::Hopper).then_some(above); - for slot in source.slots_for_face(Some(Direction::Down)) { - let c = self.containers(); - let Some(stack) = c.get(&source, slot) else { - continue; - }; - if !c.can_take(&source, slot, stack, Direction::Down) { - continue; - } - let Some(one) = self.take_one(&source, slot) else { - continue; - }; - match self.add_item(source_hopper, hopper, one, None) { - None => { - self.view_changed(&source); - return true; - } - Some(rest) => self.put_back(&source, slot, rest), - } - } - return false; + let at = [ + f64::from(pos.0) + 0.5, + f64::from(pos.1) + 1.5, + f64::from(pos.2) + 0.5, + ]; + if let Some(took) = self.suck_from_container(above, at, hopper) { + return took; } let above_state = self.world.block(above.0, above.1, above.2); let blocked = self.res.facts().get(above_state).full_collision @@ -695,6 +729,168 @@ impl Game<'_> { { return false; } + self.suck_item_entities(hopper, min, max) + } + /// The container half of `HopperBlockEntity.suckInItems`: one item from the + /// container at `above`, through its bottom face; with no block container + /// there, from a container entity whose box meets the one around `at` + /// (`getSourceContainerOrHandler`). `None` when there is no container. + fn suck_from_container(&mut self, above: Pos, at: [f64; 3], hopper: &View) -> Option { + let c = self.containers(); + let Some(source) = c.view(above, false) else { + let id = self.entity_container_at(at)?; + return self + .with_entity_container(id, |g, source| g.suck_from_slots(None, source, hopper)); + }; + if let Kind::Composter(level) = source.kind { + if level != 8 { + return Some(false); + } + // tryTakeInItemFromSlot on the OutputContainer: removeItem calls + // its setChanged, which empties the composter, and so does the + // second setChanged after the move or, when the hopper has no + // room, the setItem putting the bone meal back into the detached + // container (whose bone meal is lost with it). + let bone_meal = c.bone_meal.clone(); + let at = BlockPos::new(above.0, above.1, above.2); + self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); + let moved = self.add_item(None, hopper, bone_meal, None).is_none(); + self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); + self.world.modified.insert((above.0 >> 4, above.2 >> 4)); + return Some(moved); + } + let source_hopper = (source.kind == Kind::Hopper).then_some(above); + Some(self.suck_from_slots(source_hopper, &source, hopper)) + } + /// `HopperBlockEntity.tryTakeInItemFromSlot` over the `DOWN` face of `source`. + fn suck_from_slots( + &mut self, + source_hopper: Option, + source: &View, + hopper: &View, + ) -> bool { + for slot in source.slots_for_face(Some(Direction::Down)) { + let c = self.containers(); + let Some(stack) = c.get(source, slot) else { + continue; + }; + if !c.can_take(source, slot, stack, Direction::Down) { + continue; + } + let Some(one) = self.take_one(source, slot) else { + continue; + }; + match self.add_item(source_hopper, hopper, one, None) { + None => { + self.view_changed(source); + return true; + } + Some(rest) => self.put_back(source, slot, rest), + } + } + false + } + /// `HopperBlockEntity.getEntityContainer`: one of the alive container + /// entities (`EntitySelector.CONTAINER_ENTITY_SELECTOR`: chest and hopper + /// minecarts, chest boats) whose box meets the 1x1x1 box around `at`, + /// picked at random. + fn entity_container_at(&mut self, at: [f64; 3]) -> Option { + let meets = |b: horizon_core::geometry::Aabb| { + let (lo, hi) = (b.min_position(), b.max_position()); + lo.x < at[0] + 0.5 + && hi.x > at[0] - 0.5 + && lo.y < at[1] + 0.5 + && hi.y > at[1] - 0.5 + && lo.z < at[2] + 0.5 + && hi.z > at[2] - 0.5 + }; + let mut found: Vec = self + .carts + .iter() + .filter(|c| { + matches!( + c.kind, + super::minecarts::CartKind::Chest | super::minecarts::CartKind::Hopper + ) && meets(c.bounds()) + }) + .map(|c| c.id) + .collect(); + found.extend( + self.boats + .iter() + .filter(|b| b.chest && meets(b.bounds())) + .map(|b| b.id), + ); + if found.is_empty() { + return None; + } + let pick = self + .world + .random + .next_int_bound(found.len() as i32) + .unwrap_or(0); + found.get(pick as usize).copied() + } + /// Runs `f` on a container entity's items as a container, under the + /// placeholder key its menu uses (the open menu's copy when it is open), + /// then hands the items back to the entity. + fn with_entity_container( + &mut self, + id: u32, + f: impl FnOnce(&mut Self, &View) -> R, + ) -> Option { + let mut items = if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + std::mem::take(&mut c.items) + } else { + std::mem::take(&mut self.boats.iter_mut().find(|b| b.id == id)?.items) + }; + let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, id as i32); + let (view, open) = self.lend_items(key, &mut items); + let result = f(self, &view); + self.reclaim_items(key, open, &mut items); + if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + c.items = items; + } else if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) { + b.items = items; + } + Some(result) + } + /// A vehicle's slots as a container under its placeholder `key`. When its + /// menu is open the placeholder is the live copy and stays as it is. + /// Returns the view and whether the menu was open. + fn lend_items(&mut self, key: Pos, items: &mut Vec>) -> (View, bool) { + let open = self.world.block_entities.contains_key(&key); + if !open { + let slots = BlockEntity::Chest(std::mem::take(items)); + self.world.block_entities.insert(key, slots); + } + let size = self + .world + .block_entities + .get(&key) + .map_or(0, |e| e.slots().len()); + let view = View { + parts: vec![(key, size)], + kind: Kind::Generic, + }; + (view, open) + } + /// Gives `lend_items`' slots back to the vehicle, so its own items stay + /// the one source of truth: a menu copy that is still around (open, or + /// left by a guest's close) gets the changed items copied to `items`. + fn reclaim_items(&mut self, key: Pos, open: bool, items: &mut Vec>) { + let slots = if open { + self.world.block_entities.get(&key).cloned() + } else { + self.world.block_entities.remove(&key) + }; + if let Some(BlockEntity::Chest(slots)) = slots { + *items = slots; + } + } + /// The item half of `HopperBlockEntity.suckInItems` (`getItemsAtAndAbove`): + /// adds the item entities that meet the box, until one is taken whole. + fn suck_item_entities(&mut self, hopper: &View, min: [f64; 3], max: [f64; 3]) -> bool { let mut i = 0; while i < self.dropped.len() { let b = self.dropped[i].bounds(); @@ -719,6 +915,44 @@ impl Game<'_> { } false } + /// `MinecartHopper.tick`'s `tryConsumeItems` (`suckInItems`) for an enabled + /// hopper minecart: one item from the container above, else the item + /// entities over it or touching it, each tick without a cooldown. + pub(super) fn hopper_cart_suck(&mut self, cart: &mut super::minecarts::Minecart) { + // The cart's slots are edited as a container under the placeholder key + // its menu uses; when that menu is open the placeholder is the live copy. + let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, cart.id as i32); + let (view, open) = self.lend_items(key, &mut cart.items); + let p = cart.position; + // getLevelY is the cart's y + 0.5, so the container is the block at + // y + 1.5, and Hopper.SUCK_AABB (moved by getLevel - 0.5) starts 11/16 + // above the cart. + let above = ( + p.x.floor() as i32, + (p.y + 1.5).floor() as i32, + p.z.floor() as i32, + ); + let at = [p.x, p.y + 1.5, p.z]; + let took = match self.suck_from_container(above, at, &view) { + Some(took) => took, + None => self.suck_item_entities( + &view, + [p.x - 0.5, p.y + 11.0 / 16.0, p.z - 0.5], + [p.x + 0.5, p.y + 2.0, p.z + 0.5], + ), + }; + if !took { + // The cart's own box, inflated by 0.25 sideways. + let b = cart.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + self.suck_item_entities( + &view, + [lo.x - 0.25, lo.y, lo.z - 0.25], + [hi.x + 0.25, hi.y, hi.z + 0.25], + ); + } + self.reclaim_items(key, open, &mut cart.items); + } // ---- dispensers and droppers ---- diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index eb8c3687b..e2680ec84 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -721,6 +721,93 @@ impl Game<'_> { self.swing_arm(); true } + /// `CompassItem.useOn`: a compass used on a lodestone locks onto it (a + /// single one in survival changes in place, else one is split off). + pub(super) fn use_lodestone_compass(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool { + if &*stack.item != "minecraft:compass" { + return false; + } + let [x, y, z] = hit.pos; + if self + .res + .facts() + .get(self.world.block(x, y, z)) + .name + .as_ref() + != "minecraft:lodestone" + { + return false; + } + let at = [x, y, z].map(|v| f64::from(v) + 0.5); + self.audio + .play("minecraft:item.lodestone_compass.lock", Some(at), 1.0, 1.0); + let target = Tag::compound([( + "target", + Tag::compound([ + ("dimension", Tag::String(self.dimension_id().into())), + ("pos", Tag::IntArray(vec![x, y, z])), + ]), + )]); + if !self.creative && stack.count == 1 { + if let Some(held) = self.held_mut() { + held.data_mut() + .set_other("minecraft:lodestone_tracker", Some(target)); + } + } else { + let mut locked = stack.clone(); + locked.count = 1; + locked + .data_mut() + .set_other("minecraft:lodestone_tracker", Some(target)); + self.consume_held(); + self.give_or_drop_stack(locked); + } + self.stats.add("used", &stack.item, 1); + self.swing_arm(); + true + } + /// `CompassItem.inventoryTick` / `LodestoneTracker.tick`: a compass whose + /// lodestone is gone loses its target. A target in an unloaded chunk waits. + pub(super) fn tick_lodestone_compasses(&mut self) { + let dim = self.dimension_id(); + let gone = |game: &Self, stack: &ItemStack| -> bool { + let Some(tracker) = stack + .data() + .and_then(|d| d.other("minecraft:lodestone_tracker")) + else { + return false; + }; + let (Some(target), true) = ( + tracker.get("target"), + horizon_client::save::number(tracker.get("tracked")).is_none_or(|v| v != 0), + ) else { + return false; + }; + let Some(Tag::IntArray(pos)) = target.get("pos") else { + return false; + }; + let [x, y, z] = [pos[0], pos[1], pos[2]]; + horizon_client::save::text(target.get("dimension")).as_deref() == Some(dim) + && game.world.chunks.contains_key(&(x >> 4, z >> 4)) + && game + .res + .facts() + .get(game.world.block(x, y, z)) + .name + .as_ref() + != "minecraft:lodestone" + }; + for slot in (0..self.inventory.len()).chain([super::shield::OFFHAND_SLOT]) { + if self.stack_in(slot).is_some_and(|s| gone(self, s)) + && let Some(s) = self.stack_in_mut(slot) + { + s.data_mut().set_other( + "minecraft:lodestone_tracker", + Some(Tag::Compound(Default::default())), + ); + } + } + } fn give_or_drop_stack(&mut self, stack: ItemStack) { if let Some(rest) = self.give(stack) && let Some(eye) = self.eye_position() @@ -781,9 +868,8 @@ impl Game<'_> { (d * 2.0 + 0.5) as i8 } }; - let y = f64::from(yaw); - let adjusted = if y < 0.0 { y - 8.0 } else { y + 8.0 }; - let rot = ((adjusted * 16.0 / 360.0) as i32 & 15) as u8; + // calculateRotation: the arrow spins in the Nether. + let rot = decoration_rotation(nether, game_time, f64::from(yaw)); let sprite = if inside { Some("map/decorations/player") } else if dx.abs() < 320.0 && dz.abs() < 320.0 { @@ -1143,6 +1229,8 @@ impl Game<'_> { layer: 0, color: 0xFFFF_FFFF, light, + + glint_uv: [0.0, 0.0], }); } }; @@ -1194,6 +1282,8 @@ impl Game<'_> { layer: 0, color: 0xFFFF_FFFF, light, + + glint_uv: [0.0, 0.0], }); } }; @@ -1266,6 +1356,8 @@ impl Game<'_> { layer: 0, color: 0xFFFF_FFFF, light, + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 2ef4b8e8e..9dead141c 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -9,7 +9,7 @@ use horizon_client::{ blocks::Fluid, collisions::SceneCollisions, containers::BlockEntity, - items::ItemStack, + items::{ItemStack, Items}, mesher::Vertex, mobs::{Part, anim::Poses}, particles::{ParticleOptions, ParticleType}, @@ -73,7 +73,7 @@ pub(super) struct Minecart { pub yaw: f32, pub previous_yaw: f32, pub flipped: bool, - on_ground: bool, + pub(super) on_ground: bool, horizontal_collision: bool, fall_distance: f64, pub hurt_time: i32, @@ -201,6 +201,17 @@ impl Minecart { fn horizontal(&self) -> f64 { self.velocity.x.hypot(self.velocity.z) } + /// `AbstractContainerMenu.getRedstoneSignalFromContainer` of `slots`. + fn container_signal(slots: &[Option], items: &Items) -> i32 { + let mut total = 0.0f32; + for s in slots.iter().flatten() { + let max = items.get(&s.item).map_or(64, |i| i.max_stack).min(64); + total += s.count as f32 / max as f32; + } + total /= slots.len().max(1) as f32; + // Mth.lerpDiscrete(total, 0, 15) + (total * 14.0).floor() as i32 + i32::from(total > 0.0) + } } pub(super) struct CartModels { pub models: HashMap, @@ -547,7 +558,6 @@ impl Game<'_> { // applyGravity c.velocity.y -= if self.cart_in_water(c) { 0.005 } else { 0.04 }; let pos = self.rail_block(c.position); - let fall_speed = c.velocity; if let Some(rail) = self.rail(pos[0], pos[1], pos[2]) { self.move_along_track(c, pos, &rail, intent); if &*rail.name == "minecraft:activator_rail" { @@ -589,22 +599,26 @@ impl Game<'_> { } } CartKind::Tnt => { - let speed = fall_speed.x * fall_speed.x + fall_speed.z * fall_speed.z; + // MinecartTNT.tick: the fuse and the collision check are separate. if c.fuse > 0 { c.fuse -= 1; let at = [c.position.x, c.position.y + 0.5, c.position.z]; self.particles .add(&ParticleOptions::simple(ParticleType::Smoke), at, [0.0; 3]); - } else if c.fuse == 0 || (c.horizontal_collision && speed >= 0.01) { + } else if c.fuse == 0 { + // explode(horizontalDistanceSqr()): a rising cart's + // vertical speed adds nothing. let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; - let speed = if c.fuse == 0 && c.velocity.y > 0.0 { - c.velocity.y * c.velocity.y - } else { - speed - }; self.explode_cart(c, speed); return false; } + if c.horizontal_collision { + let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; + if speed >= f64::from(0.01_f32) { + self.explode_cart(c, speed); + return false; + } + } } _ => {} } @@ -648,51 +662,9 @@ impl Game<'_> { // The cart is the explosion's source: it is gone before the blast // looks for entities, so it can't hit itself. self.carts.retain(|x| x.id != c.id); - let _ = self.server_explode(at, power, BlockInteraction::Destroy, false); - } - /// `MinecartHopper.suckInItems`: items above, into the five slots. - fn hopper_cart_pickup(&mut self, c: &mut Minecart) { - if !c.enabled { - return; - } - let p = c.position; - let zone = Aabb::new( - Vec3::new(p.x - 0.5, p.y - 0.5 + 0.0, p.z - 0.5), - Vec3::new(p.x + 0.5, p.y + 1.5, p.z + 0.5), - ); - let mut i = 0; - while i < self.dropped.len() { - let e = &self.dropped[i]; - if e.pickup_delay > 0 || !zone.contains(e.position) { - i += 1; - continue; - } - let mut stack = e.stack.clone(); - for slot in c.items.iter_mut() { - match slot { - None => { - *slot = Some(stack.clone()); - stack.count = 0; - } - Some(s) if s.same_item_same_components(&stack) => { - let max = self.res.items().get(&s.item).map_or(64, |i| i.max_stack); - let moved = stack.count.min(max.saturating_sub(s.count)); - s.count += moved; - stack.count -= moved; - } - _ => {} - } - if stack.count == 0 { - break; - } - } - if stack.count == 0 { - self.dropped.remove(i); - } else { - self.dropped[i].stack = stack; - i += 1; - } - } + let _ = self.with_hive_emptying_blast(|g| { + g.server_explode(at, power, BlockInteraction::Destroy, false) + }); } /// `AbstractMinecart.push` from each player walking into a cart /// (`LivingEntity.pushEntities`): the window's player and every server @@ -826,8 +798,8 @@ impl Game<'_> { } let mut c = self.carts[i].clone(); let alive = self.tick_cart(&mut c, [0.0; 2]); - if c.kind == CartKind::Hopper { - self.hopper_cart_pickup(&mut c); + if c.kind == CartKind::Hopper && c.enabled { + self.hopper_cart_suck(&mut c); } let Some(i) = self.carts.iter().position(|c| c.id == id) else { continue; @@ -945,7 +917,7 @@ impl Game<'_> { } true } - /// `getDismountLocationForPassenger`: beside the cart (across its motion), else on top. + /// `getDismountLocationForPassenger`: beside the cart (across its facing), else on top. pub(super) fn dismount_cart(&mut self, i: usize) { self.riding = None; let c = &self.carts[i]; @@ -955,17 +927,25 @@ impl Game<'_> { c.position.z.floor() as i32, ); let mut target = None; + // DismountHelper.offsetsForDirection of the cart's facing + // (Direction.fromYRot of its yaw): right, left, back right, back left, + // forward right, forward left, back, forward. + let step = |q: i32| [(0, 1), (-1, 0), (0, -1), (1, 0)][(q & 3) as usize]; + let facing = (f64::from(c.yaw) / 90.0 + 0.5).floor() as i32; + let (fx, fz) = step(facing); + let (rx, rz) = (-fz, fx); + let offsets = [ + (rx, rz), + (-rx, -rz), + (rx - fx, rz - fz), + (-rx - fx, -rz - fz), + (fx + rx, fz + rz), + (fx - rx, fz - rz), + (-fx, -fz), + (fx, fz), + ]; 'search: for dy in [0, 1, -1] { - for (dx, dz) in [ - (1, 0), - (-1, 0), - (0, 1), - (0, -1), - (1, 1), - (-1, -1), - (1, -1), - (-1, 1), - ] { + for (dx, dz) in offsets { let (x, y, z) = (bx + dx, by + dy, bz + dz); let below = self.res.facts().get(self.world.block(x, y - 1, z)); let here = self.res.facts().get(self.world.block(x, y, z)); @@ -1049,6 +1029,22 @@ impl Game<'_> { } best } + /// Each cart's kind and comparator signal, for the detector rail + /// (`DetectorRailBlock.getAnalogOutputSignal`). A cart whose menu is open + /// counts the items in that menu. + pub(super) fn cart_signals(&self) -> Vec<(CartKind, i32)> { + self.carts + .iter() + .map(|c| { + let key = (i32::MAX - 15, CART_KEY_Y, c.id as i32); + let slots = match self.world.block_entities.get(&key) { + Some(BlockEntity::Chest(open)) => open, + _ => &c.items, + }; + (c.kind, Minecart::container_signal(slots, self.res.items())) + }) + .collect() + } /// `interact`: ride, open, fuel or ignite the cart under the crosshair. pub(super) fn interact_cart(&mut self) -> bool { let Some((i, d)) = self.cart_hit() else { @@ -1066,10 +1062,8 @@ impl Game<'_> { } self.riding = Some(self.carts[i].id); } + // AbstractMinecartContainer.interact: no sneak check. CartKind::Chest | CartKind::Hopper => { - if sneaking { - return false; - } let c = self.carts[i].clone(); let key = (i32::MAX - 15, CART_KEY_Y, c.id as i32); self.world @@ -1296,6 +1290,7 @@ impl Game<'_> { layer: 0, color, light, + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index a0ce5e9db..118b3cc8d 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -204,6 +204,8 @@ impl Game<'_> { layer: overlay, color, light, + + glint_uv: [0.0, 0.0], }); } } @@ -384,13 +386,15 @@ impl Game<'_> { owner.use_item_remaining_ticks = 72_000 - mob.extra.using_item; owner.crossbow_charge_duration = 25; } - let context = if left { - horizon_assets::item_model::DisplayContext::ThirdPersonLeftHand - } else { - horizon_assets::item_model::DisplayContext::ThirdPersonRightHand + use horizon_assets::item_model::DisplayContext as Context; + // PandaHoldsItemLayer shows the item as it lies on the ground. + let (context, ordinal) = match (mob.species(), left) { + (Species::Panda, _) => (Context::Ground, 7), + (_, true) => (Context::ThirdPersonLeftHand, 1), + (_, false) => (Context::ThirdPersonRightHand, 2), }; // `updateForLiving`: seeded by the entity id plus the context ordinal. - let seed = mob.id as i32 + if left { 1 } else { 2 }; + let seed = mob.id as i32 + ordinal; let state = self.resolve_item(&stack, context, Some(&owner), seed); if lit { self.submit_item_world(&state, t, light, out); diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index fa0052bc5..0084bfa2f 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -228,10 +228,12 @@ impl Game<'_> { return false; } let mut used = false; + let mut loved = false; if love && m.extra.tame && m.extra.age == 0 && m.extra.in_love <= 0 { m.extra.in_love = 600; m.extra.love_player = true; used = true; + loved = true; } if m.health < m.attrs.max_health && heal > 0.0 { m.health = (m.health + heal).min(m.attrs.max_health); @@ -251,6 +253,7 @@ impl Game<'_> { // eating(): the mouth opens and the horse eats. m.anim.v[2] = 1.0; let at = m.center(); + let id = m.id; let sound = match m.species() { Species::Camel => "minecraft:entity.camel.eat", Species::CamelHusk => "minecraft:entity.camel_husk.eat", @@ -260,16 +263,17 @@ impl Game<'_> { }; let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; self.audio.play(sound, Some(at), 1.0, pitch); + // Animal.setInLove: entity event 18. + if loved { + self.mob_event_particles(id, 18); + } self.consume_held(); true } /// `LocalPlayer.aiStep`'s riding jump: the bar charges while jump is /// held; on release, the jump's strength (0 when there is none). pub(super) fn charge_mount_jump(&mut self, i: usize, keys: Keys) -> f32 { - // PlayerRideableJumping: horses, camels and nautili (the dash). - let saddled = self.mobs[i].extra.saddled - && (equine::is_equine(self.mobs[i].species()) - || horizon_client::mobs::nautilus::is_nautilus(self.mobs[i].species())); + let saddled = self.mobs[i].extra.saddled && Self::jumps(self.mobs[i].species()); let mut jump = 0.0; if saddled { let st = &mut self.mount; @@ -465,21 +469,28 @@ impl Game<'_> { m.extra.owner = owner; m.persistent = true; // AbstractHorse.tameWithName: entity event 7, spawnTamingParticles(true). - self.particles_around_mob( - mob, - "heart", - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(mob, 7); } } - MobEvent::Buck { mob } if self.riding == Some(mob) => self.dismount_mount(), + MobEvent::Buck { mob } => { + if self.riding == Some(mob) { + self.dismount_mount(); + } + // RunAroundLikeCrazyGoal.tick: entity event 6, smoke. + self.mob_event_particles(mob, 6); + } _ => {} } } - /// `Player.jumpableVehicle`: a saddled mount that jumps. + /// `PlayerRideableJumping`: horses, camels and nautili (the dash). + fn jumps(species: Species) -> bool { + equine::is_equine(species) || horizon_client::mobs::nautilus::is_nautilus(species) + } + /// `Player.jumpableVehicle`: a saddled mount that jumps (not a pig or a + /// strider, which a saddle only steers). pub(super) fn jumpable_mount(&self) -> bool { self.mount_index() - .is_some_and(|i| self.mobs[i].extra.saddled) + .is_some_and(|i| self.mobs[i].extra.saddled && Self::jumps(self.mobs[i].species())) } /// `willPrioritizeJumpInfo`: charging a jump or recharging. pub(super) fn mount_jumping(&self) -> bool { @@ -504,8 +515,13 @@ impl Game<'_> { let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); if jump_bar { - // JumpableVehicleBar: the cooldown shows while the jump recharges. - let cooldown = i32::from(self.mount.jump_ticks < 0); + // JumpableVehicleBar: `getJumpCooldown`, which only the camel's and + // the nautilus' dash have; a horse always shows the progress. + let cooldown = i32::from( + self.mount.jump_ticks < 0 + && (matches!(m.species(), Species::Camel | Species::CamelHusk) + || horizon_client::mobs::nautilus::is_nautilus(m.species())), + ); let draws = horizon_client::hud_overlays::jump_bar(w, h, cooldown, self.mount.jump_scale); horizon_client::hud_layout::paint(batch, atlas, &draws); diff --git a/crates/horizon-client/src/game/moving_pistons.rs b/crates/horizon-client/src/game/moving_pistons.rs index 17247850e..e1bdf89d0 100644 --- a/crates/horizon-client/src/game/moving_pistons.rs +++ b/crates/horizon-client/src/game/moving_pistons.rs @@ -14,7 +14,9 @@ impl Game<'_> { out: &mut Vec, ) { let partial = alpha as f32; - for &(p, piston) in &self.world.moving_pistons { + let mut states = self.world.moving_pistons.clone(); + states.extend(self.world.moving_piston_fallback.iter().copied()); + for (p, piston) in states { let Some((block, base)) = self.moving_piston_blocks(piston, partial) else { continue; }; diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 6b5324e3a..3ecd2d245 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -379,6 +379,7 @@ impl Game<'_> { layer, color, light, + glint_uv: [0.0, 0.0], }); } }; diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 0035f5082..5afa72416 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -504,7 +504,8 @@ impl<'a> Game<'a> { m.position.z.floor() as i32, ], is_mob: true, - persistent: m.persistent, + persistent: m.persistent + || horizon_client::mobs::ai::requires_custom_persistence(m), }) .collect(); let players = players diff --git a/crates/horizon-client/src/game/nautili.rs b/crates/horizon-client/src/game/nautili.rs index e7f16ca18..5e384db98 100644 --- a/crates/horizon-client/src/game/nautili.rs +++ b/crates/horizon-client/src/game/nautili.rs @@ -85,13 +85,8 @@ impl Game<'_> { m.ai.target = None; } let sound = nautilus::eat_sound(m); - let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). - self.particles_around_mob( - self.mobs[index].id, - kind, - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 }); self.nautilus_sound(index, sound); if tamed { let view = self.mob_entity(&self.mobs[index]); @@ -145,6 +140,8 @@ impl Game<'_> { let sound = nautilus::eat_sound(m); self.use_nautilus_food(item); self.nautilus_sound(index, sound); + // Animal.setInLove: entity event 18. + self.mob_event_particles(self.mobs[index].id, 18); return true; } false diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index c8142284a..95c38d9d1 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -662,6 +662,17 @@ impl Game<'_> { ); } } + /// `Entity.setPortalCooldown` on an entity that has just spawned in a + /// portal: it stands in the portal for 300 ticks without going through. + pub(super) fn set_portal_cooldown(&mut self, id: u32) { + self.portals.entities.insert( + id, + PortalState { + cooldown: ENTITY_DELAY, + process: None, + }, + ); + } /// `canUsePortal(false)` of a mob: alive, riding nothing, not asleep, /// not carrying the player, and not a boss that never travels. fn mob_can_use_portal(&self, m: &horizon_client::mobs::Mob) -> bool { diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 89d7738f8..013b94de2 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -1,14 +1,23 @@ //! Resource pack selection bound to the game: the pack screen lists, and a //! full resource reload after a change, while playing. -use super::Game; +use super::{ + Game, PackResources, Resources, UiResources, build_renderer, prepare_renderer_textures, +}; use horizon_client::{ + assets::Assets, + gfx::PreparedTextures, hud::HudAtlas, lang, pack_screen::{self, Compat, PackInfo, Source as PackSource}, packs::{self, Pack, Position}, + streaming::WorkerContext, text::{Style, Text}, }; -use std::path::{Path, PathBuf}; +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, + sync::Arc, +}; /// Where overlay roots are built (beside options.txt). pub fn cache_dir() -> PathBuf { @@ -98,7 +107,7 @@ pub(super) fn pack_infos(vanilla: &Path) -> Vec { infos } impl Game<'_> { - fn vanilla_root(&self) -> PathBuf { + pub(super) fn vanilla_root(&self) -> PathBuf { if self.ui.vanilla_root.as_os_str().is_empty() { self.options.resources.clone() } else { @@ -138,35 +147,36 @@ impl Game<'_> { self.ui.options.resource_error = Some(e.to_string()); } } - /// Reload from the selected packs and the server's. - pub(super) fn reload_selected_packs(&mut self) -> horizon_client::Result<()> { + /// The CPU half of the reload, safe on a worker (`PackReload` runs it): + /// `apply_staged_pack` finishes the GPU half and the swap. + pub(super) fn stage_selected_packs(&mut self) -> horizon_client::Result { let vanilla = self.vanilla_root(); if self.ui.vanilla_root.as_os_str().is_empty() { self.ui.vanilla_root = vanilla.clone(); } - let server = &self.server_packs.active; - let root = startup_root(&vanilla, &self.settings.resource_packs, server)?; - let root = - super::mods::content_root(&root, &self.settings.mods.enabled, &self.options.dev_mods); - self.reload_resources(&root) + stage_pack( + &vanilla, + &self.settings.resource_packs, + &self.server_packs.active, + &self.settings.mods.enabled, + &self.options.dev_mods, + &self.pack.assets, + &self.res, + &self.pack.context, + self.settings.force_unicode, + self.settings.japanese_glyphs, + &super::Progress::new(), + ) } - fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { - let render = std::sync::Arc::new(self.pack.assets.reload(root)?); - let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?; - atlas.font.uniform = self.settings.force_unicode; - atlas.font.japanese = self.settings.japanese_glyphs; - let gui = super::UiResources { - atlas, - panorama: std::sync::Arc::new(horizon_client::gfx::panorama::Faces::load(root)), - }; - let pack = super::PackResources::load( + /// The render-thread half: the renderer on the new pack's textures, then + /// the swap (`ReloadInstance`'s application listeners). + pub(super) fn apply_staged_pack(&mut self, staged: StagedPack) -> horizon_client::Result<()> { + let StagedPack { root, - self.pack.assets.clone(), - render, - self.res.facts(), - self.pack.context.biomes.clone(), - self.pack.context.light.clone(), - )?; + gui, + pack, + textures, + } = staged; // Keep the working GPU resources, and hand its window surface over. if let Some(renderer) = &mut self.renderer { renderer.release_surface(); @@ -174,7 +184,17 @@ impl Game<'_> { let renderer = match self .window .clone() - .map(|window| self.renderer_for(window, &pack, &gui)) + .map(|window| { + build_renderer( + window, + self.options.offscreen, + &pack, + &gui, + self.renderer.as_ref(), + Some(textures), + self.settings.horizon.api, + ) + }) .transpose() { Ok(renderer) => renderer, @@ -190,18 +210,18 @@ impl Game<'_> { } }; // Everything loaded: switch over. - self.waypoint_styles = horizon_client::locator_bar::WaypointStyles::load(root); - self.armor_stand_assets.reload_trims(root); + self.waypoint_styles = horizon_client::locator_bar::WaypointStyles::load(&root); + self.armor_stand_assets.reload_trims(&root); self.random_tick_sections.clear(); self.portals.sections.clear(); - self.options.resources = root.to_path_buf(); + self.options.resources = root.clone(); let context = pack.context.clone(); self.pack = pack; self.gui = gui; // The atlas's sprites moved: the particle engine re-reads every rect // and the packs' sprite sets, or every particle draws a stale region. self.particles - .reload(root, &self.gui.atlas.sprites, &self.gui.atlas.translucent); + .reload(&root, &self.gui.atlas.sprites, &self.gui.atlas.translucent); horizon_client::ui_theme::reset_atlas(); // Villager hats come from the pack's texture metadata (shared data, swapped in place). *self @@ -210,11 +230,11 @@ impl Game<'_> { .villager_hats .write() .unwrap_or_else(std::sync::PoisonError::into_inner) = - horizon_client::mobs::villager_hats::VillagerHats::load(root); - horizon_client::ui::load_metadata(root); - lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code())); + horizon_client::mobs::villager_hats::VillagerHats::load(&root); + horizon_client::ui::load_metadata(&root); + lang::set(lang::Language::load(&[&root], &lang::code())); self.refresh_remote_language(); - self.audio.reload(root); + self.audio.reload(&root); self.clear_lod(); self.streaming.reload_resources(&mut self.world, context); self.pending_uploads.clear(); @@ -229,4 +249,66 @@ impl Game<'_> { self.creative_screen.forget_items(); Ok(()) } + /// `Minecraft.reloadResourcePacks`: the reload staged on the spot, then + /// applied (`PackReload` runs the same two phases across frames). + pub(super) fn reload_selected_packs(&mut self) -> horizon_client::Result<()> { + let staged = self.stage_selected_packs()?; + self.apply_staged_pack(staged) + } +} + +/// The CPU half of `reload_selected_packs` (`PackReload` runs it on a +/// worker; `apply_staged_pack` does the GPU half and the swap): the overlay +/// root, the models and sprites, the menu bundle, the pack's tables and its +/// CPU mip chains. +pub(super) fn stage_pack( + vanilla_root: &Path, + selected: &[String], + server: &[Pack], + mods_enabled: &BTreeSet, + dev_mods: &[PathBuf], + assets: &Arc, + res: &Resources, + context: &WorkerContext, + force_unicode: bool, + japanese: bool, + progress: &super::Progress, +) -> horizon_client::Result { + let root = startup_root(vanilla_root, selected, server)?; + let root = super::mods::content_root(&root, mods_enabled, dev_mods); + progress.set(1); + let render = Arc::new(assets.reload(&root)?); + let mut atlas = HudAtlas::build_over(&root, vanilla_root)?; + atlas.font.uniform = force_unicode; + atlas.font.japanese = japanese; + let gui = UiResources { + atlas, + panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(&root)), + }; + progress.set(2); + let pack = PackResources::load( + &root, + assets.clone(), + render, + res.facts(), + context.biomes.clone(), + context.light.clone(), + )?; + let textures = prepare_renderer_textures(&pack); + progress.set(3); + Ok(StagedPack { + root, + gui, + pack, + textures, + }) +} + +/// Everything a pack reload builds on the CPU (`apply_staged_pack` finishes +/// it on the render thread). +pub(super) struct StagedPack { + pub root: PathBuf, + pub gui: UiResources, + pub pack: PackResources, + pub textures: PreparedTextures, } diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 1b839f5b0..d0e984c29 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -307,6 +307,8 @@ impl Game<'_> { layer: 0, color, light: packed, + + glint_uv: [0.0, 0.0], }); } }; diff --git a/crates/horizon-client/src/game/pandas.rs b/crates/horizon-client/src/game/pandas.rs new file mode 100644 index 000000000..f89feca05 --- /dev/null +++ b/crates/horizon-client/src/game/pandas.rs @@ -0,0 +1,165 @@ +//! Pandas on the game side: the food they find on the ground and pick up +//! (`Mob.aiStep`, `Panda.pickUpItem`), the bamboo a player gives them +//! (`Panda.mobInteract`), the start a sneeze gives the grown pandas about, +//! and the crumbs and the sneeze a window draws. +use super::{ + Game, + pickups::{Collector, Taken}, +}; +use horizon_client::{ + items::ItemStack, + mobs::{Species, panda}, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::geometry::Vec3; + +impl Game<'_> { + /// `Panda.canPickUpAndEat`'s tag. + fn panda_eats_from_ground(&self, item: &str) -> bool { + self.res + .items() + .item_tags + .get("minecraft:panda_eats_from_ground") + .is_some_and(|tag| tag.contains(item)) + } + /// A panda takes what lies at its feet when its mouth is free, and + /// looks for food within 6 and 8 blocks for `PandaSitGoal`. + pub(super) fn tick_pandas(&mut self) { + let griefing = self.ui.rules.bool("mob_griefing"); + for i in 0..self.mobs.len() { + let m = &self.mobs[i]; + if m.species() != Species::Panda || !m.alive() { + continue; + } + let id = m.id; + let wants = |g: &Self, e: &horizon_client::entities::ItemEntity| { + e.pickup_delay == 0 && g.panda_eats_from_ground(&e.stack.item) + }; + // Mob.aiStep: the items within the box grown by (1, 0, 1). + if griefing && m.can_pick_up_loot() && m.extra.main_hand.is_none() { + let reach = m.bounds().inflate(Vec3::new(1.0, 0.0, 1.0)); + let taken = self + .dropped + .iter() + .position(|e| wants(self, e) && reach.intersects(e.bounds())); + if let Some(j) = taken { + let e = self.dropped.remove(j); + self.add_pickup(Taken::Item(Box::new(e.clone())), Collector::Mob(id)); + panda::hold(&mut self.mobs[i], &e.stack.item, e.stack.count, true); + } + } + let m = &self.mobs[i]; + let area = |r: f64| m.bounds().inflate(Vec3::new(r, r, r)); + let (near, wide) = (area(6.0), area(8.0)); + let food_near = self + .dropped + .iter() + .any(|e| wants(self, e) && near.intersects(e.bounds())); + let food_at = self + .dropped + .iter() + .find(|e| wants(self, e) && wide.intersects(e.bounds())) + .map(|e| [e.position.x, e.position.y, e.position.z]); + panda::set_food(&mut self.mobs[i], food_near, food_at); + } + } + /// `Panda.mobInteract` for a click with `item`; whether the click is taken. + pub(super) fn interact_panda(&mut self, index: usize, item: &str) -> bool { + let creative = self.creative; + let m = &mut self.mobs[index]; + if panda::scared(m) { + return false; + } + if panda::get_up(m) { + return true; + } + if !m.kind.food.iter().any(|f| f == item) { + return false; + } + if m.ai.target.is_some() { + panda::got_bamboo(m); + } + let at = [m.position.x, m.position.y, m.position.z]; + let mut dropped = None; + if m.is_baby() { + // ageUp((int) (-getAge() / 20 * 0.1F), true). + let seconds = ((-m.extra.age / 20) as f32 * 0.1) as i32; + horizon_client::mobs::ai::age_up(m, seconds, true); + } else if m.extra.age == 0 && m.extra.in_love <= 0 { + m.extra.in_love = 600; + m.extra.love_player = true; + } else { + if panda::is_sitting(m) || m.fluids.in_water { + return false; + } + panda::try_to_sit(m); + panda::start_eating(m); + // What it held falls, unless the player has infinite materials. + if let Some(held) = m.extra.main_hand.clone() + && !creative + { + dropped = Some(ItemStack::new(&held, panda::held_count(m))); + } + panda::hold(m, item, 1, false); + } + self.consume_held(); + if let Some(stack) = dropped { + self.spawn_item(stack, at, [0.0, 0.2, 0.0], 10); + } + true + } + /// `Panda.afterSneeze`: the grown pandas within 10 blocks of a cub jump. + pub(super) fn panda_sneezed(&mut self, id: u32) { + let Some(area) = self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| m.bounds().inflate(Vec3::new(10.0, 10.0, 10.0))) + else { + return; + }; + for m in &mut self.mobs { + if m.species() == Species::Panda + && !m.is_baby() + && m.on_ground + && !m.fluids.in_water + && panda::can_perform_action(m, panda::scared(m)) + && area.intersects(m.bounds()) + { + // LivingEntity.jumpFromGround. + m.needs_sync = true; + let power = f64::from(m.jump_power()); + if power > 1.0e-5 { + m.velocity.y = power.max(m.velocity.y); + } + } + } + } + /// What a window draws of its pandas: the crumbs of a bite + /// (`addEatingParticles`) and the sneeze's particle. + pub(super) fn panda_effects(&mut self) { + let mut bites = Vec::new(); + let mut sneezes = Vec::new(); + for m in self + .mobs + .iter_mut() + .filter(|m| m.species() == Species::Panda) + { + let (crumbs, sneeze) = panda::effects(m); + if let (Some(crumbs), Some(item)) = (crumbs, m.extra.main_hand.clone()) { + bites.push((item, crumbs)); + } + sneezes.extend(sneeze); + } + for (item, crumbs) in bites { + let options = self.item_particle(&ItemStack::new(&item, 1)); + for (at, velocity) in crumbs { + self.particles.add(&options, at, velocity); + } + } + let options = ParticleOptions::simple(ParticleType::Sneeze); + for (at, velocity) in sneezes { + self.particles.add(&options, at, velocity); + } + } +} diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index caf49883b..2c4cd1571 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -218,11 +218,20 @@ impl Game<'_> { _ => None, }) }); - // A living mount at the default scale and camera distance. + // Camera.setup: the living mount's scale and camera distance + // attributes (the happy ghast's is 8, the default 4). let mount = self .riding .and_then(|id| self.mobs.iter().find(|m| m.id == id)) - .map(|_| (1.0, 4.0)); + .map(|m| { + let attribute = |name: &str, default: f64| { + m.kind.attributes.get(name).copied().unwrap_or(default) + }; + ( + attribute("minecraft:scale", 1.0) as f32, + attribute("minecraft:camera_distance", 4.0), + ) + }); // AbstractBoat.positionRider turns a passenger by the boat's // deltaRotation after its yRotO was saved, and LocalPlayer.getViewYRot // interpolates a passenger's yaw: the boat's turn is spread over the @@ -443,6 +452,7 @@ impl Game<'_> { let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); + let start = out.len(); horizon_client::mobs::render::render_with( m, alpha as f32, @@ -456,6 +466,15 @@ impl Game<'_> { self.player_elytra_geometry(m, camera, alpha as f32, packed, out); self.spin_attack_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); + // LivingEntity.isCurrentlyGlowing: the Glowing effect. A server's client is + // in its team by its profile name. + if self.potions.effects.get("glowing").is_some() { + let team = match &self.remote { + Some(r) => self.score.board.players_team(&r.profile_name), + None => self.player_team(), + }; + self.mark_outline(&out[start..], super::glowing::team_color(team)); + } } /// `extractEntityInInventoryFollowsMouse`: the player in the box /// `[x0, x1) x [y0, y1)`, `size` pixels per block, turned toward the @@ -710,6 +729,8 @@ mod preview_tests { color: u32::MAX, light: 0, normal: [0; 4], + + glint_uv: [0.0, 0.0], }) }; // A shield and arm can intersect: neither average depth orders both ends. diff --git a/crates/horizon-client/src/game/pick_entity.rs b/crates/horizon-client/src/game/pick_entity.rs new file mode 100644 index 000000000..5efc54d44 --- /dev/null +++ b/crates/horizon-client/src/game/pick_entity.rs @@ -0,0 +1,98 @@ +//! Pick Block on an entity (`Minecraft.pickBlockOrEntity`'s entity case and +//! `ServerGamePacketListenerImpl.handlePickItemFromEntity`): the client aims, +//! the server answers with `Entity.getPickResult`. +use super::Game; +use horizon_client::items::ItemStack; + +impl Game<'_> { + /// The entity the crosshair hits before any block, as `Entity.getId`; an + /// entity with nothing to pick (a projectile, a player, the dragon) is + /// `Some(None)`. `None` when the view hits a block or nothing. + pub(super) fn pick_entity_hit(&self) -> Option> { + let mut best: Option<(f64, Option)> = None; + let mut offer = |distance: f64, id: Option| { + if self.before_block(distance) && best.is_none_or(|b| distance < b.0) { + best = Some((distance, id)); + } + }; + if let Some(hit) = self.remote_object_hit(true) { + offer(hit.distance, Some(hit.id)); + } + if let Some((i, d)) = self.mob_hit() { + offer(d, Some(self.mobs[i].id as i32)); + } + if let Some((_, d)) = self.guest_hit() { + offer(d, None); + } + if let Some((_, d)) = self.redirectable_hit() { + offer(d, None); + } + if let Some((_, d)) = self.dragon_hit() { + offer(d, None); + } + best.map(|b| b.1) + } + + /// `Entity.getPickResult` of the entity `id`: a mob's spawn egg, the item + /// of a boat, minecart, armor stand, cushion, painting, item frame (the + /// framed item when it holds one) or end crystal. + pub(super) fn entity_pick_result(&self, id: i32) -> Option { + let id = u32::try_from(id).ok()?; + let item = if let Some(m) = self.mobs.iter().find(|m| m.id == id) { + // Mob.getPickResult: SpawnEggItem.byId. + let egg = format!("{}_spawn_egg", m.kind.id); + return self.res.items().get(&egg).map(|_| ItemStack::new(&egg, 1)); + } else if let Some(b) = self.boats.iter().find(|b| b.id == id) { + b.entity_type() + } else if let Some(c) = self.carts.iter().find(|c| c.id == id) { + c.kind.id().to_owned() + } else if self.armor_stands.iter().any(|a| a.id == id) { + "minecraft:armor_stand".to_owned() + } else if let Some(c) = self.cushions.iter().find(|c| c.id == id) { + c.item() + } else if let Some(f) = self.item_frames.iter().find(|f| f.id == id) { + // ItemFrame.getPickResult: what it frames, else the frame itself. + return Some( + f.item + .clone() + .unwrap_or_else(|| ItemStack::new(f.kind(), 1)), + ); + } else if self.paintings.iter().any(|p| p.id == id) { + "minecraft:painting".to_owned() + } else if self.crystals.iter().any(|c| c.id == id) { + "minecraft:end_crystal".to_owned() + } else { + return None; + }; + Some(ItemStack::new(&item, 1)) + } + + /// `Player.isWithinEntityInteractionRange(entity, 3.0)`: the entity's box + /// within the interaction range plus 3 of the eyes. + pub(super) fn within_entity_range(&self, id: i32) -> bool { + let Some(eye) = self.eye_position() else { + return false; + }; + let mob = u32::try_from(id) + .ok() + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|m| m.bounds()); + let Some(b) = self + .object_target(id) + .map(|(lo, hi, _)| (lo, hi)) + .or_else(|| { + mob.or_else(|| self.tracked_special_box(id)).map(|b| { + let (lo, hi) = (b.min_position(), b.max_position()); + ([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]) + }) + }) + else { + return false; + }; + let d2: f64 = (0..3) + .map(|a| (eye[a] - eye[a].clamp(b.0[a], b.1[a])).powi(2)) + .sum(); + let range = if self.creative { 5.0 } else { 3.0 } + 3.0; + d2 < range * range + } +} diff --git a/crates/horizon-client/src/game/piston_push.rs b/crates/horizon-client/src/game/piston_push.rs new file mode 100644 index 000000000..6bbf1cb39 --- /dev/null +++ b/crates/horizon-client/src/game/piston_push.rs @@ -0,0 +1,573 @@ +//! `PistonMovingBlockEntity.moveCollidedEntities` and `moveStuckEntities` for +//! the entities the game moves itself: the players and the mobs. +//! +//! The geometry is in [`horizon_world::piston_push`]; this file supplies the +//! bodies and applies the movement the way `Entity.move(MoverType.PISTON, …)` +//! does: limited to 0.51 blocks per tick per axis (`Entity.limitPistonMovement`), +//! then run through the block collision scan, so a pushed entity stops at a +//! wall instead of passing through it. +//! +use super::Game; +use horizon_client::collisions::{EntityCollisions, SceneCollisions, with_piston_noclip}; +use horizon_core::geometry::{Aabb, Direction, Vec3, border::BorderGeometry}; +use horizon_core::position::BlockPos; +use horizon_world::{ + block_collision_scan::BlockCollisionWorld, level::pistons::MovingPiston, + piston_movement::PistonMovement, piston_push, world_movement::EntityMovementWorld, +}; + +/// What one piston asks for this tick: where it is, its state, and the progress +/// `moveCollidedEntities` runs at (before the tick stores it). +pub(super) type Push = (BlockPos, MovingPiston, f32); + +/// Which entity was pushed, so its storage can be reached after the world +/// borrow ends. +#[derive(Clone, Copy, Hash, PartialEq, Eq)] +enum Target { + Player, + Guest(u32), + Mob(usize), + Item(usize), + Boat(usize), + Cart(usize), + ArmorStand(usize), +} + +/// `Entity.getStepHeight` of each body, read before the push. +struct StepHeights { + player: f32, + guests: std::collections::HashMap, +} + +/// What the push needs from one entity. +#[derive(Clone, Copy)] +struct Body { + bounds: Aabb, + position: Vec3, + on_ground: bool, + step_height: f32, + /// Standing on the piston's own block (`Entity.isSupportedBy`). + supported: bool, +} + +impl Game<'_> { + /// Push whatever this tick's moving pistons ran into, in the order the + /// pistons ticked: vanilla pushes from each block entity's own tick. + pub(super) fn push_piston_entities(&mut self, pushes: Vec) { + let mut accumulators = std::collections::HashMap::new(); + for push in pushes { + self.push_for_piston(push, &mut accumulators); + } + } + + fn push_for_piston( + &mut self, + (pos, piston, new_progress): Push, + accumulators: &mut std::collections::HashMap, + ) { + let delta_progress = f64::from(new_progress - piston.progress); + if delta_progress <= 0.0 { + return; + } + let Some(bindings) = self.collision.pistons() else { + return; + }; + let Ok(state) = bindings.collision_related_state(piston.shape_state()) else { + return; + }; + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + let Ok(shape) = self + .collision + .collision_shape(&mut scene, state, [pos.x, pos.y, pos.z]) + else { + return; + }; + if shape.is_empty() { + return; + } + let movement = piston.movement_direction(); + let boxes: Vec = shape.boxes().to_vec(); + let facts = self.res.facts(); + let slime = &*facts.get(piston.moved_state).name == "minecraft:slime_block"; + let honey = &*facts.get(piston.moved_state).name == "minecraft:honey_block"; + // `moveStuckEntities` asks the moved state's own top for its box. + let sticky_top = if honey { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + self.collision + .collision_shape(&mut scene, piston.moved_state, [pos.x, pos.y, pos.z]) + .ok() + .and_then(|s| s.bounds()) + .map_or(0.0, |b| b.max_position().y) + } else { + 0.0 + }; + + let steps = self.push_step_heights(); + let search = shape.bounds().map(|bounds| { + piston_push::movement_search_area( + piston_push::move_by_position_and_progress(pos, bounds, piston.shape_state()), + movement, + delta_progress, + ) + }); + let targets = self.push_targets(); + for &target in &targets { + let Some(body) = self.push_body(target, pos, &steps) else { + continue; + }; + let amount = piston_push::collided_amount( + &boxes, + pos, + piston.shape_state(), + new_progress, + movement, + body.bounds, + ); + if slime && search.is_some_and(|area| area.intersects(body.bounds)) { + self.bounce(target, movement); + } + if amount > 0.0 { + let step = piston_push::step_vector(movement); + let before = body.bounds; + self.move_pushed( + target, + before, + [body.position.x, body.position.z], + body.step_height, + body.on_ground, + step.scale(amount), + movement, + accumulators, + ); + // `fixEntityWithinPistonBase`: a retracting source piston drags + // an entity that is still inside its own block. + if !piston.extending + && piston.source + && let Some(after) = self.push_body(target, pos, &steps) + && let Some(fix) = piston_push::fix_within_piston_base( + pos, + after.bounds, + movement, + delta_progress, + ) + { + let back = piston_push::step_vector(movement.opposite()); + self.move_pushed( + target, + after.bounds, + [after.position.x, after.position.z], + after.step_height, + after.on_ground, + back.scale(fix), + movement, + accumulators, + ); + } + } + } + // Vanilla selects honey passengers after all collided entities have moved. + if honey && movement.normal()[1] == 0 { + let area = piston_push::sticky_area(pos, piston.shape_state(), sticky_top); + for target in targets { + let Some(body) = self.push_body(target, pos, &steps) else { + continue; + }; + if piston_push::sticky_entity_selected( + area, + body.bounds, + horizon_world::level::data::PushReaction::PushPull, + body.on_ground, + body.supported, + body.position, + ) { + self.move_pushed( + target, + body.bounds, + [body.position.x, body.position.z], + body.step_height, + body.on_ground, + piston_push::step_vector(movement).scale(delta_progress), + movement, + accumulators, + ); + } + } + } + } + + /// `Entity.getStepHeight` for each body, read once: the attribute lookup + /// needs the mutable body, and the push only needs the number. + fn push_step_heights(&mut self) -> StepHeights { + let player = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:step_height").ok()) + .map_or(0.6, |v| v as f32); + let mut guests = std::collections::HashMap::new(); + if let Some(host) = self.lan.as_mut() { + for g in &mut host.hub.guests { + let step = g + .motion + .as_mut() + .and_then(|m| m.attribute("minecraft:step_height").ok()) + .map_or(0.6, |v| v as f32); + guests.insert(g.conn, step); + } + } + StepHeights { player, guests } + } + + /// The entities a moving block can run into: the window's player, the LAN + /// guests in the level, then the mobs. + fn push_targets(&self) -> Vec { + let mut targets = Vec::new(); + if self.player.is_some() { + targets.push(Target::Player); + } + if let Some(host) = self.lan.as_ref() { + targets.extend( + host.hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| Target::Guest(g.conn)), + ); + } + targets.extend((0..self.mobs.len()).map(Target::Mob)); + targets.extend((0..self.dropped.len()).map(Target::Item)); + targets.extend((0..self.boats.len()).map(Target::Boat)); + targets.extend((0..self.carts.len()).map(Target::Cart)); + targets.extend((0..self.armor_stands.len()).map(Target::ArmorStand)); + targets + } + + /// What the push needs from one entity, or `None` when it is not pushed: + /// removed, dead, a spectator, or an armor-stand marker. + fn push_body(&self, target: Target, pos: BlockPos, steps: &StepHeights) -> Option { + let at = [pos.x, pos.y, pos.z]; + match target { + Target::Player => { + let p = self.player.as_ref()?; + if p.spectator { + return None; + } + Some(Body { + bounds: p.bounds(), + position: p.position, + on_ground: p.ground.on_ground, + step_height: steps.player, + supported: p.ground.supporting_block == Some(pos), + }) + } + Target::Guest(conn) => { + let host = self.lan.as_ref()?; + let g = host.hub.guests.iter().find(|g| g.conn == conn)?; + if g.dead || g.game_mode == 3 { + return None; + } + let p = g.position; + Some(Body { + bounds: Aabb::new( + Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3), + Vec3::new(p[0] + 0.3, p[1] + 1.8, p[2] + 0.3), + ), + position: Vec3::new(p[0], p[1], p[2]), + on_ground: g.on_ground, + step_height: steps.guests.get(&conn).copied().unwrap_or(0.6), + supported: g + .motion + .as_ref() + .is_some_and(|m| m.ground.supporting_block == Some(pos)), + }) + } + Target::Mob(i) => { + let m = &self.mobs[i]; + if m.removed || !m.alive() { + return None; + } + Some(Body { + bounds: m.bounds(), + position: m.position, + on_ground: m.on_ground, + step_height: m.kind.step_height as f32, + supported: m.supporting == Some(at), + }) + } + Target::Item(i) => { + let entity = &self.dropped[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::Boat(i) => { + let entity = &self.boats[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::Cart(i) => { + let entity = &self.carts[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::ArmorStand(i) => { + let entity = &self.armor_stands[i]; + if entity.marker { + return None; + } + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + } + } + + /// `Entity.move(MoverType.PISTON, movement)` for one pushed entity: the + /// per-tick piston limit, then the block and world border collision scan. + fn move_pushed( + &mut self, + target: Target, + before: Aabb, + at: [f64; 2], + step_height: f32, + on_ground: bool, + movement: Vec3, + piston_direction: Direction, + accumulators: &mut std::collections::HashMap, + ) { + let Some(limited) = self.limit_piston(target, movement, accumulators) else { + return; + }; + // `limitPistonMovement` returns zero once the tick's budget is spent. + if limited == Vec3::ZERO { + return; + } + let resolved = with_piston_noclip(piston_direction, || { + pushed_movement( + SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }, + self.border.geometry(), + at, + before, + limited, + step_height, + on_ground, + ) + .unwrap_or(Vec3::ZERO) + }); + if resolved.length_squared() <= 1.0e-7 + && limited.length_squared() - resolved.length_squared() >= 1.0e-7 + { + return; + } + self.apply_push(target, resolved); + } + + /// `Entity.limitPistonMovement`: each axis may travel at most 0.51 blocks + /// per game tick, and a move touches only its first non-zero axis. + fn limit_piston( + &mut self, + target: Target, + movement: Vec3, + accumulators: &mut std::collections::HashMap, + ) -> Option { + let time = self.world.game_time; + let limit = |state: &mut PistonMovement| state.limit(movement, || Ok::(time)).ok(); + match target { + Target::Player => { + let p = self.player.as_mut()?; + limit(&mut p.piston) + } + Target::Guest(conn) => { + let host = self.lan.as_mut()?; + let g = host.hub.guests.iter_mut().find(|g| g.conn == conn)?; + limit(&mut g.motion.as_deref_mut()?.piston) + } + Target::Mob(i) => limit(&mut self.mobs[i].piston), + _ => limit(accumulators.entry(target).or_default()), + } + } + + fn apply_push(&mut self, target: Target, movement: Vec3) { + match target { + Target::Player => { + if let Some(p) = self.player.as_mut() { + p.position = p.position.add_vector(movement); + } + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_mut() + && let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + { + // The body and the hub's copy of its position move together: + // `leave_guest` writes the body back over the hub's. + for (slot, delta) in g.position.iter_mut().zip(movement.components()) { + *slot += delta; + } + if let Some(m) = g.motion.as_deref_mut() { + m.position = m.position.add_vector(movement); + } + } + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + m.position = m.position.add_vector(movement); + } + Target::Item(i) => { + self.dropped[i].position = self.dropped[i].position.add_vector(movement) + } + Target::Boat(i) => self.boats[i].position = self.boats[i].position.add_vector(movement), + Target::Cart(i) => self.carts[i].position = self.carts[i].position.add_vector(movement), + Target::ArmorStand(i) => { + self.armor_stands[i].position = self.armor_stands[i].position.add_vector(movement) + } + } + } + + /// `causeBounce`: a slime block sets the velocity along the movement axis. + fn bounce(&mut self, target: Target, movement: Direction) { + match target { + Target::Player => { + if let Some(p) = self.player.as_mut() { + p.velocity = piston_push::bounce_velocity(movement, p.velocity); + } + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + m.velocity = piston_push::bounce_velocity(movement, m.velocity); + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_mut() + && let Some(guest) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + && let Some(motion) = guest.motion.as_deref_mut() + { + motion.velocity = piston_push::bounce_velocity(movement, motion.velocity); + } + } + Target::Item(i) => { + self.dropped[i].velocity = + piston_push::bounce_velocity(movement, self.dropped[i].velocity) + } + Target::Boat(i) => { + self.boats[i].velocity = + piston_push::bounce_velocity(movement, self.boats[i].velocity) + } + Target::Cart(i) => { + self.carts[i].velocity = + piston_push::bounce_velocity(movement, self.carts[i].velocity) + } + Target::ArmorStand(i) => { + self.armor_stands[i].velocity = + piston_push::bounce_velocity(movement, self.armor_stands[i].velocity) + } + } + } +} + +/// `Entity.move(MoverType.PISTON, movement)` for a pushed body: the movement +/// it makes. The world's blocks stop it, and so does the world border: +/// `Entity.collectCollidersIgnoringWorldBorder` adds the border's walls when +/// the body is inside close to the border, as ordinary movement does. +fn pushed_movement( + blocks: W, + border: &BorderGeometry, + at: [f64; 2], + before: Aabb, + movement: Vec3, + step_height: f32, + on_ground: bool, +) -> horizon_client::Result +where + W: BlockCollisionWorld + EntityMovementWorld, +{ + EntityCollisions::with_border(blocks, border, at).resolve( + before, + movement, + step_height, + on_ground, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::collisions::EmptyCollisions; + + /// A border 10 wide around the origin: its wall's inner face is at x = 5. + fn border() -> BorderGeometry { + BorderGeometry::new([0.0, 0.0], 10.0, 29_999_984).expect("a border") + } + + /// `Entity.collectCollidersIgnoringWorldBorder`: the border's walls stop a + /// pushed body that is inside close to the border. + #[test] + fn a_pushed_body_stops_at_the_world_border() { + // A body 0.6 wide, 0.4 blocks short of the wall, pushed east into it. + let before = Aabb::new(Vec3::new(4.0, 0.0, 0.0), Vec3::new(4.6, 1.8, 0.6)); + let border = border(); + let moved = pushed_movement( + EmptyCollisions, + &border, + [4.3, 0.3], + before, + Vec3::new(0.51, 0.0, 0.0), + 0.0, + false, + ) + .expect("the push resolves"); + // The wall stops the body 0.4 blocks short of the whole push. + assert!( + (moved.x - 0.4).abs() < 1.0e-9, + "the body was not stopped by the border: {moved:?}" + ); + } + + /// Away from the border, the same push moves the whole way. + #[test] + fn a_pushed_body_moves_whole_away_from_the_border() { + let before = Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.6, 1.8, 0.6)); + let border = border(); + let moved = pushed_movement( + EmptyCollisions, + &border, + [0.3, 0.3], + before, + Vec3::new(0.51, 0.0, 0.0), + 0.0, + false, + ) + .expect("the push resolves"); + assert!( + (moved.x - 0.51).abs() < 1.0e-9, + "the body did not move the whole push: {moved:?}" + ); + } +} diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 5e4c70172..b8971046d 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -2,7 +2,12 @@ //! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`), //! filling glass bottles (`BottleItem`), the per-tick effect application, //! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`). -use super::{Game, Screen, item_draw::owner_at}; +use super::{ + Game, Screen, + dragon::{Breath, FightPlayer, FightWho}, + item_draw::owner_at, + remote_projectiles::cloud_client_tick, +}; use horizon_assets::item_model::DisplayContext; use horizon_client::{ block_entity_render::vertex_light, @@ -12,9 +17,13 @@ use horizon_client::{ hud_layout, hud_overlays, inventory_effects, items::ItemStack, mesher::Vertex, + particles::{ParticleOptions, ParticleType}, text::Text, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + random::{LegacyRandom, RandomSource}, +}; /// A thrown splash or lingering potion in flight. #[derive(Clone, Debug)] @@ -31,8 +40,37 @@ pub(super) struct ThrownPotion { /// for a dispenser's). owner: Option, } +/// `AreaEffectCloud` wait time set by `ThrownLingeringPotion.onHitAsPotion`. +pub(super) const LINGERING_WAIT: i32 = 10; +/// `AreaEffectCloud.DEFAULT_REAPPLICATION_DELAY`. +const REAPPLICATION_DELAY: i32 = 20; +/// An entity a cloud has affected (`AreaEffectCloud.victims`). +#[derive(Clone, Copy, PartialEq)] +enum Victim { + Mob(u32), + Player(FightWho), +} +/// What a lingering potion's `AreaEffectCloud` applies: the potion's effects +/// (at the lingering item's 0.25 duration scale) and who it has affected. +pub(super) struct PotionCloud { + effects: &'static [(&'static str, i32, i32)], + /// The potion's colour (`PotionContents.getColor`). + color: u32, + /// Each victim and the tick it can be affected again. + victims: Vec<(Victim, i32)>, + /// Who its instant damage names (`indirectMagic(cloud, owner)`): the + /// thrower, else the cloud. + source: Text, +} +impl PotionCloud { + /// `AreaEffectCloud.updateParticle`: an entity effect in the potion's colour. + pub(super) fn particle(&self) -> ParticleOptions { + let c = |shift: u32| (self.color >> shift & 255) as f32 / 255.0; + ParticleOptions::colored(ParticleType::EntityEffect, [c(16), c(8), c(0), 1.0]) + } +} /// A mob's effect ids carry the `minecraft:` namespace. -fn mob_effect_id(id: &str) -> Option<&'static str> { +pub(super) fn mob_effect_id(id: &str) -> Option<&'static str> { use std::{collections::HashMap, sync::OnceLock}; static IDS: OnceLock> = OnceLock::new(); let id = id.trim_start_matches("minecraft:"); @@ -48,7 +86,187 @@ fn mob_effect_id(id: &str) -> Option<&'static str> { .get(id) .copied() } +/// `LivingEntity.canBeAffected` with the mob overrides (`WitherBoss` and +/// `WitherSkeleton` shrug off wither, `Spider` and `AbstractNautilus` poison, +/// `Parched` weakness): the immune-to-infested and immune-to-oozing tags +/// decide first, then the tag of mobs that ignore poison and regeneration. +fn mob_can_be_affected( + tags: &std::collections::HashMap>, + kind: &str, + effect: &str, +) -> bool { + let effect = effect.trim_start_matches("minecraft:"); + let kind = kind.trim_start_matches("minecraft:"); + let overridden = match kind { + "wither" | "wither_skeleton" => effect == "wither", + "spider" | "cave_spider" | "nautilus" | "zombie_nautilus" => effect == "poison", + "parched" => effect == "weakness", + _ => false, + }; + if overridden { + return false; + } + let in_tag = |tag: &str| { + tags.get(tag) + .is_some_and(|t| t.contains(&format!("minecraft:{kind}"))) + }; + if in_tag("minecraft:immune_to_infested") { + effect != "infested" + } else if in_tag("minecraft:immune_to_oozing") { + effect != "oozing" + } else { + !in_tag("minecraft:ignores_poison_and_regen") + || (effect != "regeneration" && effect != "poison") + } +} impl Game<'_> { + /// `LivingEntity.triggerOnDeathMobEffects` (`onMobRemoved` with the reason + /// KILLED) for what Oozing, Weaving and Wind Charged do when their bearer + /// dies. `bearer` is the dying mob's id, `player` whether it is a player, + /// `random` the dying mob's own (`mob.getRandom()`; the world's for the + /// player). + pub(super) fn effects_on_death( + &mut self, + effects: &[&str], + bounds: Aabb, + player: bool, + bearer: Option, + mut random: Option<&mut LegacyRandom>, + ) { + let feet = bounds.bottom_center(); + if effects.contains(&"oozing") { + // OozingMobEffect.numberOfSlimesToSpawn: two, fewer when the + // slimes close by already fill the cramming limit. + let limit = self.ui.rules.int("max_entity_cramming"); + let mut count = 2; + if limit >= 1 { + let near = bounds.inflate(Vec3::new(2.0, 2.0, 2.0)); + let nearby = self + .mobs + .iter() + .filter(|m| { + m.species() == horizon_client::mobs::Species::Slime + && Some(m.id) != bearer + && m.bounds().intersects(near) + }) + .count() + .min(limit as usize) as i32; + count = (limit - nearby).clamp(0, count); + } + for _ in 0..count { + // spawnSlimeOffspring: a size 2 slime half a block up. + if let Some(id) = self.spawn_mob_for( + "minecraft:slime", + [feet.x, feet.y + 0.5, feet.z], + false, + true, + ) && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + horizon_client::mobs::cube::set_size(m, 2); + } + } + } + if effects.contains(&"weaving") && (player || self.ui.rules.bool("mob_griefing")) { + self.spawn_cobwebs_around( + [ + feet.x.floor() as i32, + feet.y.floor() as i32, + feet.z.floor() as i32, + ], + random.as_deref_mut(), + ); + } + if effects.contains(&"wind_charged") { + // A burst centred at half the height, radius 3 to 5. + let center = [feet.x, feet.y + bounds.size().y / 2.0, feet.z]; + let r = random.unwrap_or(&mut self.world.random); + let radius = 3.0 + r.next_float() * 2.0; + let _ = self.wind_burst(center, radius, 1.0, false, false); + } + } + /// `WeavingMobEffect.spawnCobwebsRandomlyAround`: two or three cobwebs in + /// free spaces with a solid floor, picked among 15 random blocks within one + /// block of `pos`. + fn spawn_cobwebs_around(&mut self, pos: [i32; 3], mut random: Option<&mut LegacyRandom>) { + let r = random.as_deref_mut().unwrap_or(&mut self.world.random); + let wanted = 2 + r.next_int_bound(2).unwrap_or(0) as usize; + let mut chosen: Vec<[i32; 3]> = Vec::new(); + for _ in 0..15 { + let r = random.as_deref_mut().unwrap_or(&mut self.world.random); + let at = [ + pos[0] - 1 + r.next_int_bound(3).unwrap_or(0), + pos[1] - 1 + r.next_int_bound(3).unwrap_or(0), + pos[2] - 1 + r.next_int_bound(3).unwrap_or(0), + ]; + let facts = self.res.facts(); + let here = facts.get(self.world.block(at[0], at[1], at[2])); + let below = facts.get(self.world.block(at[0], at[1] - 1, at[2])); + if !chosen.contains(&at) + && here.replaceable + && below.sturdy_full & (1 << Direction::Up as u8) != 0 + { + chosen.push(at); + if chosen.len() >= wanted { + break; + } + } + } + for at in chosen { + if self.set_state_named(at, "minecraft:cobweb", &[]).is_ok() { + self.level_event_at(3018, at, 0); + } + } + } + /// `InfestedMobEffect.onMobHurt` for the player: from half its height up, + /// along where it looks. + pub(super) fn player_infested(&mut self) { + if let Some(p) = self.player.as_ref() { + let at = [ + p.position.x, + p.position.y + f64::from(p.dimensions.height) / 2.0, + p.position.z, + ]; + let look = super::view_vector(self.yaw, self.pitch); + self.infested_hurt(at, look, None); + } + } + /// A living mob's own random (`Entity.random`), else the world's. + fn bearer_random(&mut self, bearer: Option) -> &mut LegacyRandom { + match bearer.and_then(|id| self.mobs.iter().position(|m| m.id == id)) { + Some(i) => &mut self.mobs[i].random, + None => &mut self.world.random, + } + } + /// `InfestedMobEffect.onMobHurt`: a 10% chance of one or two silverfish at + /// `at` (half the bearer's height up), thrown along its look direction. + /// The draws are the bearer's (`mob.getRandom()`): `bearer` is the mob, + /// none for the player (the world's random). + pub(super) fn infested_hurt(&mut self, at: [f64; 3], look: [f64; 3], bearer: Option) { + if self.bearer_random(bearer).next_float() > 0.1 { + return; + } + let count = 1 + self.bearer_random(bearer).next_int_bound(2).unwrap_or(0); + for _ in 0..count { + // Mth.randomBetween(-PI / 2, PI / 2), then the look direction + // scaled by (0.3, 0.45, 0.3) and turned about the y axis. + let half = std::f32::consts::FRAC_PI_2; + let angle = self.bearer_random(bearer).next_float() * (2.0 * half) - half; + let (sin, cos) = angle.sin_cos(); + let (x, z) = (look[0] * 0.3, look[2] * 0.3); + let velocity = Vec3::new( + f64::from(x as f32 * cos + z as f32 * sin), + look[1] * 0.3 * 1.5, + f64::from(-x as f32 * sin + z as f32 * cos), + ); + if let Some(id) = self.spawn_mob_for("minecraft:silverfish", at, false, true) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + m.velocity = velocity; + } + self.audio + .play("minecraft:entity.silverfish.hurt", Some(at), 1.0, 1.0); + } + } /// A splash potion, lingering potion or experience bottle in flight (the /// player's throws and dispensers both end up here). pub(super) fn launch_thrown( @@ -391,6 +609,7 @@ impl Game<'_> { self.tick_mob_effects(); if running { self.tick_thrown_potions(); + self.tick_potion_clouds(); } } /// `LivingEntity.tickEffects` (server side) for `self.player`, the local @@ -401,13 +620,37 @@ impl Game<'_> { return; }; if player.health.dead_or_dying() { - // LivingEntity.die → removeAllEffects. + // LivingEntity.die → removeAllEffects. Vanilla runs the effects + // that act on death (`onMobRemoved`) when the dead player is + // removed, up to 20 ticks later; here it is as the effects go. + let w = f64::from(player.dimensions.width) / 2.0; + let bounds = Aabb::new( + Vec3::new( + player.position.x - w, + player.position.y, + player.position.z - w, + ), + Vec3::new( + player.position.x + w, + player.position.y + f64::from(player.dimensions.height), + player.position.z + w, + ), + ); + let ids: Vec<&'static str> = self.potions.effects.list.iter().map(|e| e.id).collect(); self.potions.effects.clear(); + if !ids.is_empty() { + self.effects_on_death(&ids, bounds, true, None, None); + } } // The omens act from inside the effect tick (BadOmenMobEffect, // RaidOmenMobEffect). + let absorption_empty = self + .player + .as_ref() + .is_some_and(|p| p.health.absorption() <= 0.0); let mut effects = std::mem::take(&mut self.potions.effects); - let (actions, raid_omen_added) = effects.tick_with(&mut |e| self.omen_tick(e)); + let (actions, raid_omen_added) = + effects.tick_with(&mut |e| self.omen_tick(e), absorption_empty); self.potions.effects = effects; if raid_omen_added { self.raid_omen_added(); @@ -548,29 +791,176 @@ impl Game<'_> { let state = self.world .block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - if self.res.facts().get(state).full_collision - || self.mobs.iter().any(|m| { - m.alive() - && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 - && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 - && p.y >= m.position.y - && p.y <= m.position.y + m.kind.height - }) - { - hit = Some(p); + let mob = self.mobs.iter().find(|m| { + m.alive() + && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 + && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 + && p.y >= m.position.y + && p.y <= m.position.y + m.kind.height + }); + if self.res.facts().get(state).full_collision || mob.is_some() { + hit = Some((p, mob.map(|m| m.position))); break; } } - if let Some(p) = hit { - landed.push((t.stack.clone(), p, t.owner.clone())); + if let Some((p, mob)) = hit { + landed.push((t.stack.clone(), p, mob, t.owner.clone())); return false; } t.position = next; t.age < 1200 && t.position.y > -128.0 }); self.potions.thrown = thrown; - for (stack, at, owner) in landed { - self.splash(&stack, at, owner); + for (stack, at, mob, owner) in landed { + self.splash(&stack, at, mob, owner); + } + } + /// `AreaEffectCloud.tick` for the lingering potions' clouds: the client + /// tick's particles, then the server tick. + fn tick_potion_clouds(&mut self) { + if self.breath_clouds.iter().all(|c| c.potion.is_none()) { + return; + } + let players: Vec = self + .fight_players() + .into_iter() + .filter(|p| p.alive) + .collect(); + let mut clouds = std::mem::take(&mut self.breath_clouds); + clouds.retain_mut(|c| c.potion.is_none() || self.tick_potion_cloud(c, &players)); + self.breath_clouds.append(&mut clouds); + } + /// `AreaEffectCloud.serverTick` for a lingering potion's cloud: after its + /// wait it shrinks, and every 5 ticks it affects the living entities in + /// its box and radius that were not affected in the last 20 ticks, each + /// taking some of its radius. False once it is gone. + fn tick_potion_cloud(&mut self, c: &mut Breath, players: &[FightPlayer]) -> bool { + c.age += 1; + let Some(potion) = c.potion.as_mut() else { + return true; + }; + if c.age - LINGERING_WAIT >= c.duration { + return false; + } + let waiting = c.age < LINGERING_WAIT; + cloud_client_tick( + &mut self.particles, + c.at, + c.radius, + waiting, + &potion.particle(), + ); + if waiting { + return true; + } + // setRadiusPerTick(-radius / duration). + c.radius += -3.0 / 600.0; + if c.radius < 0.5 { + return false; + } + if c.age % 5 != 0 { + return true; + } + potion.victims.retain(|(_, until)| c.age < *until); + let r = f64::from(c.radius); + let area = Aabb::new( + Vec3::new(c.at[0] - r, c.at[1], c.at[2] - r), + Vec3::new(c.at[0] + r, c.at[1] + 0.5, c.at[2] + r), + ); + let mut inside = Vec::new(); + for p in players.iter().filter(|p| p.bounds.intersects(area)) { + inside.push((Victim::Player(p.who), p.position.x, p.position.z)); + } + let effects = potion.effects; + let tags = &self.res.stations().enchantments.entity_tags; + // Only mobs that at least one of the cloud's effects can affect are + // taken (`allEffects.stream().anyMatch(entity::canBeAffected)`), so + // the others neither become victims nor use up its radius. + for m in self.mobs.iter().filter(|m| { + m.alive() + && m.bounds().intersects(area) + && effects + .iter() + .any(|(id, ..)| mob_can_be_affected(tags, &m.kind.id, id)) + }) { + inside.push((Victim::Mob(m.id), m.position.x, m.position.z)); + } + for (victim, x, z) in inside { + let (dx, dz) = (x - c.at[0], z - c.at[2]); + if potion.victims.iter().any(|(v, _)| *v == victim) + || dx * dx + dz * dz > f64::from(c.radius * c.radius) + { + continue; + } + potion.victims.push((victim, c.age + REAPPLICATION_DELAY)); + self.cloud_affect(victim, effects, c.at, &potion.source); + // setRadiusOnUse(-0.5). + c.radius -= 0.5; + if c.radius < 0.5 { + return false; + } + } + true + } + /// What a cloud puts on one entity: instant effects at half strength + /// (`applyInstantaneousEffect` with 0.5), the others for their duration + /// at the lingering item's 0.25 scale (`PotionContents.forEachEffect`). + fn cloud_affect( + &mut self, + victim: Victim, + effects: &'static [(&'static str, i32, i32)], + at: [f64; 3], + source: &Text, + ) { + let scaled = |duration: i32| ((f64::from(duration) * 0.25) as i32).max(1); + match victim { + Victim::Player(who) => self.as_fight_player(who, |g| { + for (id, duration, amp) in effects { + let Some(e) = brewing::effect(id) else { + continue; + }; + if e.instant { + if let Some(a) = horizon_client::effects::instant(id, *amp, 0.5) { + g.apply_indirect_effect_action(a, source); + } + } else { + g.add_player_effect(EffectInstance::new(e.id, scaled(*duration), *amp)); + } + } + }), + Victim::Mob(mob) => { + let Some(i) = self.mobs.iter().position(|m| m.id == mob) else { + return; + }; + // Undead invert healing and harming. + let tags = &self.res.stations().enchantments.entity_tags; + let inverted = tags + .get("minecraft:inverted_healing_and_harm") + .is_some_and(|t| t.contains(&self.mobs[i].kind.id)); + for (id, duration, amp) in effects { + let m = &mut self.mobs[i]; + match *id { + "instant_damage" | "instant_health" => { + let amount = + |base: i32| (0.5 * f64::from(base << amp) + 0.5) as i32 as f32; + if (*id == "instant_damage") != inverted { + m.hurt(amount(6), Some(at), &mut self.world.random); + } else { + m.health = (m.health + amount(4)).min(m.kind.max_health); + } + } + _ => { + // `LivingEntity.addEffect` refuses what the mob + // cannot be affected by. + if mob_can_be_affected(tags, &m.kind.id, id) + && let Some(name) = mob_effect_id(id) + { + m.add_effect(name, scaled(*duration), *amp); + } + } + } + } + } } } /// `ThrowableProjectile.tick`'s `applyGravity` and `applyInertia`, which @@ -672,12 +1062,23 @@ impl Game<'_> { self.submit_item_world(&state, pose, vertex_light(light), out); } } + /// `HealOrHarmMobEffect.applyInstantaneousEffect` with a source (a + /// potion or a cloud): indirectMagic, not plain magic. + fn apply_indirect_effect_action(&mut self, a: EffectAction, source: &Text) { + let a = match a { + EffectAction::Hurt("minecraft:magic", amount) => { + self.note_direct_entity("minecraft:indirect_magic", source.clone()); + EffectAction::Hurt("minecraft:indirect_magic", amount) + } + a => a, + }; + self.apply_effect_action(a); + } /// A splash potion's effects on the player in place, by their distance. fn splash_on_player( &mut self, effects: &'static [(&'static str, i32, i32)], at: Vec3, - scale: f64, source: &Text, ) { if let Some(p) = self.player.as_ref() { @@ -694,22 +1095,10 @@ impl Game<'_> { let instant = brewing::effect(id).is_some_and(|e| e.instant); if instant { if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { - // HealOrHarmMobEffect.applyInstantaneousEffect with - // a source: indirectMagic, not plain magic. - let a = match a { - EffectAction::Hurt("minecraft:magic", amount) => { - self.note_direct_entity( - "minecraft:indirect_magic", - source.clone(), - ); - EffectAction::Hurt("minecraft:indirect_magic", amount) - } - a => a, - }; - self.apply_effect_action(a); + self.apply_indirect_effect_action(a, source); } } else { - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + let d = (intensity * f64::from(*duration) + 0.5) as i32; if d > 20 && let Some(e) = brewing::effect(id) { @@ -720,8 +1109,9 @@ impl Game<'_> { } } } - /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). - fn splash(&mut self, stack: &ItemStack, at: Vec3, owner: Option) { + /// `ThrownSplashPotion.onHitAsPotion`, or `ThrownLingeringPotion.onHitAsPotion` + /// for a lingering potion; `mob` is where it hit a mob. + fn splash(&mut self, stack: &ItemStack, at: Vec3, mob: Option, owner: Option) { let block = [at.x, at.y, at.z].map(|v| v.floor() as i32); if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level @@ -745,23 +1135,41 @@ impl Game<'_> { let color = brewing::potion_color(stack.potion()); 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) = potion else { return; }; + if lingering { + // The cloud sits at the mob it hit (its feet), else the impact; + // radius 3, wait 10, 600 ticks, shrinking to nothing, and a + // potion with no effects leaves none. + if !def.effects.is_empty() { + let at = mob.unwrap_or(at); + self.breath_clouds.push(Breath { + id: 0, + at: [at.x, at.y, at.z], + radius: 3.0, + age: 0, + duration: 600, + from_dragon: false, + potion: Some(PotionCloud { + effects: def.effects, + color, + victims: Vec::new(), + source: owner.unwrap_or_else(|| { + Text::translate("entity.minecraft.area_effect_cloud", &[]) + }), + }), + }); + } + return; + } // Every player in range (`ThrownSplashPotion.applySplash` over // `LivingEntity`s, the players among them). - // Instant damage is indirectMagic(potion or cloud, owner), which the - // death message names by the owner, else by the potion or cloud. - let source = owner.unwrap_or_else(|| { - let entity = if lingering { - "entity.minecraft.area_effect_cloud" - } else { - "entity.minecraft.splash_potion" - }; - Text::translate(entity, &[]) - }); - self.for_each_player(|g| g.splash_on_player(def.effects, at, scale, &source)); + // Instant damage is indirectMagic(potion, owner), which the death + // message names by the owner, else by the potion. + let source = + owner.unwrap_or_else(|| Text::translate("entity.minecraft.splash_potion", &[])); + self.for_each_player(|g| g.splash_on_player(def.effects, at, &source)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); @@ -784,7 +1192,7 @@ impl Game<'_> { _ => { // `Potion.applySplash`: timed effects last in // proportion to how close the mob was. - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + let d = (intensity * f64::from(*duration) + 0.5) as i32; if d > 20 && let Some(name) = mob_effect_id(id) { @@ -807,9 +1215,28 @@ impl Game<'_> { } } } - /// `Hud.extractEffects`: icons top-right, beneficial row then harmful row. + /// `Screen.showsActiveEffects`: the survival and creative inventories + /// draw their own effect list when `EffectsInInventory.canSeeEffects` + /// (32 or more pixels right of the screen). + fn screen_shows_active_effects(&self, batch: &HudBatch) -> bool { + let (ox, image_width) = match self.screen { + Screen::Inventory + if self.container.is_none() && self.craft_size == 2 && !self.mount_active() => + { + (self.inventory_origin(batch).0, 176) + } + Screen::Creative => ( + Self::creative_origin(batch).0, + horizon_client::creative::Creative::WIDTH as i32, + ), + _ => return false, + }; + batch.width as i32 - (ox as i32 + image_width + 2) >= 32 + } + /// `Hud.extractEffects`: icons top-right, beneficial row then harmful row; + /// every screen but the inventories keeps them. pub(super) fn draw_effect_icons(&self, batch: &mut HudBatch) { - if self.screen != Screen::Playing || self.potions.effects.list.is_empty() { + if self.potions.effects.list.is_empty() || self.screen_shows_active_effects(batch) { return; } let icons: Vec = self diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index c51fbdc0b..f7525c953 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -762,7 +762,7 @@ impl Game<'_> { } positions.push((m.id, m.position, s.active_raid)); } - let banners: Vec<(usize, Vec3)> = self + let banners: Vec<(usize, u32, Vec3)> = self .dropped .iter() .enumerate() @@ -771,7 +771,7 @@ impl Game<'_> { && e.stack.data().is_some_and(|d| d.ominous_banner) && e.pickup_delay == 0 }) - .map(|(i, e)| (i, e.position)) + .map(|(i, e)| (i, e.id, e.position)) .collect(); let mut taken: Vec = Vec::new(); let mut collectors: Vec<(usize, u32)> = Vec::new(); @@ -821,14 +821,11 @@ impl Game<'_> { if !alive { continue; } - // Raider.updateNoActionTime adds two per tick, and a raider - // fighting a player or golem in a raid is never idle. - if s.raid_id.is_some() { - m.ai.no_action_time = if target_player || target_golem { - 0 - } else { - m.ai.no_action_time + 1 - }; + // Raider.aiStep: a raider fighting a player or golem in a raid is + // never idle. The per-tick growth (+1 serverAiStep, +2 + // Raider.updateNoActionTime) is added by the mob's own step. + if s.raid_id.is_some() && (target_player || target_golem) { + m.ai.no_action_time = 0; } // Raider.aiStep: join the raid the raider stands in. if s.raid_id.is_none() @@ -858,20 +855,33 @@ impl Game<'_> { && raids.get(id).is_some_and(|r| r.leader(s.wave).is_none()) && !leaders.contains(&(id, s.wave)) { + let in_reach = |(i, _, p): &&(usize, u32, Vec3)| { + !taken.contains(i) + && (p.x - position.x).abs() <= range + && (p.z - position.z).abs() <= range + && (p.y - position.y).abs() <= 8.0 + }; + let by_distance = |a: &&(usize, u32, Vec3), b: &&(usize, u32, Vec3)| { + a.2.distance_squared(position) + .total_cmp(&b.2.distance_squared(position)) + }; + // The unreachable cache only picks the navigation target; + // a banner next to the raider is still picked up. let near = banners .iter() - .filter(|(i, p)| { - !taken.contains(i) - && (p.x - position.x).abs() <= range - && (p.z - position.z).abs() <= range - && (p.y - position.y).abs() <= 8.0 + .filter(in_reach) + .filter(|(_, item, _)| { + !s.unreachable_banners + .iter() + .any(|&(b, until)| b == *item && now < until) }) - .min_by(|a, b| { - a.1.distance_squared(position) - .total_cmp(&b.1.distance_squared(position)) - }); - if let Some((i, p)) = near { + .min_by(by_distance); + let nearest = banners.iter().filter(in_reach).min_by(by_distance); + let adjacent = + nearest.filter(|(_, _, p)| p.distance_squared(position) < 1.414 * 1.414); + if let Some((i, item, p)) = adjacent.or(near) { s.banner_at = Some([p.x, p.y, p.z]); + s.banner_item = *item; if p.distance_squared(position) < 1.414 * 1.414 { // pickUpItem: the banner becomes the wave's leader. taken.push(*i); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 588fbfdeb..343763c43 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -119,7 +119,7 @@ pub(super) struct Remote { pub(super) entity_id: i32, /// The item the player's use began with (`LivingEntity.useItem`). pub(super) use_item: Option>, - dimension: DimensionType, + pub(super) dimension: DimensionType, /// What chunk packets decode with (the dimension's height and sky, the /// biome registry); replaced whenever one of them changes. pub(super) chunk_format: Arc, @@ -186,11 +186,16 @@ pub(super) struct Remote { online_mode: bool, /// Player entities in the level: entity id to profile UUID. level_players: HashMap, + /// Entities with shared flag 6 (`Entity.isCurrentlyGlowing` on a client); mobs keep + /// theirs in `Mob::glowing`. + glowing: std::collections::HashSet, /// The local player's profile UUID (always in the level). profile: u128, /// The local player's profile name: its score holder and team member. pub(super) profile_name: String, destroying: Option<([i32; 3], u8, f32)>, + /// `MultiPlayerGameMode.destroyingItem`: the held item key the break began with. + destroying_item: String, destroy_delay: u32, input: horizon_client::interaction_input::InteractionInput, /// Keys whose presses send a packet (swap hands, drop, a mount's @@ -199,7 +204,11 @@ pub(super) struct Remote { pub(super) pending_keys: Vec, stop_mining: bool, placing: Option<([i32; 3], u64)>, + /// `CommonPlayerSpawnInfo.isFlat`: the level is a superflat one. + pub(super) flat: bool, death_message: Option, + /// `LocalPlayer.showDeathScreen`: off with `immediate_respawn`. + show_death_screen: bool, player_type: Option>, /// Inventory as last synchronised, for creative-mode slot updates. synced: Vec>, @@ -483,15 +492,19 @@ impl Game<'_> { listed: Default::default(), online_mode: false, level_players: HashMap::new(), + glowing: Default::default(), profile: 0, profile_name: String::new(), destroying: None, + destroying_item: String::new(), destroy_delay: 0, input: Default::default(), pending_keys: Vec::new(), stop_mining: false, placing: None, + flat: false, death_message: None, + show_death_screen: true, player_type, synced: vec![None; 36], decode_errors: 0, @@ -1011,6 +1024,7 @@ impl Game<'_> { r.chunk_format = Arc::new(r.chunk_format.with_dimension(&dimension)); r.dimension = dimension; r.game_mode = spawn.game_type; + r.flat = spawn.flat; r.loaded_sent = false; // A replacement LocalPlayer has a fresh sendPosition baseline. r.position_sender = Default::default(); @@ -1430,6 +1444,13 @@ impl Game<'_> { { return; } + // So does a firework rocket: its own tick flies it on. + if path.is_some() + && let Some(f) = self.rockets.iter_mut().find(|f| f.id == id as u32) + { + f.position = Vec3::new(position[0], position[1], position[2]); + return; + } // A dragon fireball keeps Entity's NO_OP InterpolationHandler too: // the server's position replaces its own at once. if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { @@ -1488,7 +1509,9 @@ impl Game<'_> { self.remove_remote_dragon(id); self.remove_remote_object(id as u32); self.remove_remote_projectile(id as u32); + self.persist.uuids.remove(&(id as u32)); if let Some(r) = self.remote.as_mut() { + r.glowing.remove(&id); r.entities.remove(&id); r.lerps.remove(&id); r.stepped.remove(&id); @@ -1631,6 +1654,41 @@ impl Game<'_> { } } + /// `ClientPacketListener.handleUpdateAttributes` for a mob: its maximum + /// health (the hearts drawn over its mount) takes the server's value, from + /// `AttributeInstance.calculateValue`. + fn remote_mob_attributes(&mut self, id: i32, values: &[play::AttributeSnapshot]) { + let catalog = &self.motion.attributes; + let Some(max_health) = catalog.id("minecraft:max_health") else { + return; + }; + let Some(s) = values + .iter() + .find(|s| s.attribute == max_health.registry_id()) + else { + return; + }; + let amounts = |op: i32| { + s.modifiers + .iter() + .filter(move |m| m.operation == op) + .map(|m| m.amount) + }; + let base = s.base + amounts(0).sum::(); + let mut value = base + amounts(1).map(|a| base * a).sum::(); + for amount in amounts(2) { + value *= 1.0 + amount; + } + let value = catalog.attribute(max_health).definition.sanitize(value); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + horizon_client::mobs::finalize::set_base( + m, + horizon_client::mobs::finalize::Attr::MaxHealth, + value, + ); + } + } + fn handle_packet(&mut self, packet: C) -> Result<()> { match packet { // ClientCommonPacketListenerImpl.handlePing runs on the game @@ -1651,6 +1709,7 @@ impl Game<'_> { r.online_mode = p.online_mode; r.entity_id = p.player_id; r.view_distance = p.chunk_radius; + r.show_death_screen = p.show_death_screen; } self.streaming.radius = self.settings.render_distance.min(p.chunk_radius + 1).max(2); @@ -1805,6 +1864,11 @@ impl Game<'_> { r.level_players.remove(&p.id); } } + // Entity.getTeam: a mob is on a team by its UUID. + self.persist.uuids.insert( + p.id as u32, + horizon_client::lan::playerdata::uuid_ints(p.uuid), + ); self.spawn_entity(p.id, &kind, p.position, rotation); // Entity.recreateFromPacket: setDeltaMovement(packet.getMovement()). self.remote_motion(p.id, p.velocity); @@ -1896,7 +1960,8 @@ impl Game<'_> { } C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers), // ClientPacketListener.handleEntityLinkPacket: who holds a mob's - // lead (this player, another player or a mob), for the rope. + // lead (this player, another player, a mob or a fence knot), for + // the rope. C::SetEntityLink(p) => { let me = self.remote.as_ref().map(|r| r.entity_id); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.source as u32) { @@ -1904,7 +1969,12 @@ impl Game<'_> { m.extra.leash = match p.dest { 0 => None, d if Some(d) == me => Some(Holder::Player), - d => Some(Holder::Mob(d as u32)), + d => match self.remote_knots.get(&(d as u32)) { + Some(&block) => Some(Holder::Knot(block)), + // Not a known knot yet: kept by id until the knot + // arrives (game/remote_objects.rs). + None => Some(Holder::Mob(d as u32)), + }, }; } } @@ -1923,7 +1993,10 @@ impl Game<'_> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { for (index, _, value) in &p.values { match (index, value) { - (0, Value::Byte(flags)) => m.invisible = flags & 0x20 != 0, + (0, Value::Byte(flags)) => { + m.invisible = flags & 0x20 != 0; + m.glowing = flags & 0x40 != 0; + } (2, Value::OptText(name)) => { let text = name.as_ref().map(horizon_client::entity_nbt::name_text); m.custom_name = @@ -1940,6 +2013,15 @@ impl Game<'_> { } } } + if let Some((_, _, Value::Byte(flags))) = p.values.iter().find(|v| v.0 == 0) + && let Some(r) = self.remote.as_mut() + { + if flags & 0x40 != 0 { + r.glowing.insert(p.id); + } else { + r.glowing.remove(&p.id); + } + } self.remote_mob_data(p.id, &p.values); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) && m.species() == horizon_client::mobs::Species::Creeper @@ -2164,8 +2246,9 @@ impl Game<'_> { } C::HurtAnimation(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + // Player.animateHurt: the tilt turns around the yaw. if let Some(pl) = self.player.as_mut() { - pl.health.animate_hurt(); + pl.health.animate_hurt_dir(p.yaw); } } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { m.hurt_time = 10; @@ -2202,6 +2285,10 @@ impl Game<'_> { { m.health = 0.0; } + // The events that start a mob's animation (the warden's). + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + horizon_client::mobs::sync::entity_event(m, p.event as u8); + } // LivingEntity.handleEntityEvent 60: the poof as the dead body goes. if p.event == 60 && let Some(m) = self.mobs.iter().find(|m| m.id == p.id as u32) @@ -2212,6 +2299,37 @@ impl Game<'_> { if p.event == super::totem::TOTEM_EVENT { self.remote_totem(p.id); } + // Mob.handleEntityEvent 20: the spawn poof. + if p.event == 20 && self.mobs.iter().any(|m| m.id == p.id as u32) { + self.poof_particles(p.id as u32); + } + // Villager 12, 13 and 14, TamableAnimal and AbstractHorse 6 and + // 7, Animal and Allay 18: the particles about the mob. + if matches!(p.event, 6 | 7 | 12 | 13 | 14 | 18) { + self.entity_event_particles(p.id as u32, p.event); + } + // Snowball and ThrownEgg.handleEntityEvent 3: the crumbs where + // the projectile is (the server removes it right after). + if p.event == 3 { + let crumbs = self + .creatures + .projectiles + .iter() + .find(|pr| pr.id == p.id as u32) + .and_then(|pr| { + let item = match pr.kind { + horizon_client::projectiles::ProjectileKind::Snowball => { + "minecraft:snowball" + } + horizon_client::projectiles::ProjectileKind::Egg => "minecraft:egg", + _ => return None, + }; + Some(([pr.position.x, pr.position.y, pr.position.z], item)) + }); + if let Some((at, item)) = crumbs { + self.item_burst(at, item); + } + } if p.event == super::combat::DROWN_EVENT { self.remote_drown(p.id); } @@ -2262,6 +2380,7 @@ impl Game<'_> { } self.apply_remote_health(); } + C::UpdateAttributes(p) => self.remote_mob_attributes(p.id, &p.values), C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -2286,7 +2405,11 @@ impl Game<'_> { pl.health.flash_health_change(p.health); } self.apply_remote_health(); - if p.health <= 0.0 && self.screen != Screen::Dead && self.player.is_some() { + // The death screen opens (or the respawn is asked for) with the + // death packet when the rule hides it. + let shown = self.remote.as_ref().is_none_or(|r| r.show_death_screen); + if p.health <= 0.0 && shown && self.screen != Screen::Dead && self.player.is_some() + { self.screen = Screen::Dead; self.ui.death_time = 0; self.capture(false); @@ -2302,11 +2425,16 @@ impl Game<'_> { r.death_message = Some(message); } // ClientPacketListener.handlePlayerCombatKill: the death - // screen, whatever health was last sent. + // screen, whatever health was last sent, or `respawn()` at + // once when it is hidden. if me && self.screen != Screen::Dead && self.player.is_some() { - self.screen = Screen::Dead; - self.ui.death_time = 0; - self.capture(false); + if self.remote.as_ref().is_none_or(|r| r.show_death_screen) { + self.screen = Screen::Dead; + self.ui.death_time = 0; + self.capture(false); + } else { + self.respawn_player()?; + } } } C::TrackedWaypoint(p) => self.handle_waypoint(&p), @@ -2382,6 +2510,12 @@ impl Game<'_> { r.game_mode = mode; } } + // IMMEDIATE_RESPAWN: LocalPlayer.setShowDeathScreen. + 11 => { + if let Some(r) = self.remote.as_mut() { + r.show_death_screen = p.param == 0.0; + } + } 7 => { self.world.weather.rain_level = (p.param, p.param); self.world.weather.raining = p.param > 0.0; @@ -2422,6 +2556,20 @@ impl Game<'_> { r.state_id = p.state; } let stack = self.to_stack(&p.item); + // ClientPacketListener.handleContainerSetSlot: a hotbar slot that + // gains items squeezes for 5 ticks. + if p.container == 0 + && (36..=45).contains(&p.slot) + && let Some(new) = &stack + { + let (pop, old) = match p.slot { + 45 => (9, self.offhand.as_ref()), + s => (s as usize - 36, self.inventory[s as usize - 36].as_ref()), + }; + if old.is_none_or(|old| old.count < new.count) { + self.hotbar_pop[pop] = 5; + } + } self.set_menu_slot(p.container, i32::from(p.slot), stack); self.remote_synced(); } @@ -2899,7 +3047,7 @@ impl Game<'_> { resolved.push((uuid, skin)); } } - resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.show_skin(skin)); + resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.again_skin(skin)); let Some((level, skins, own)) = self.remote.as_mut().map(|r| { r.skins = resolved.into_iter().collect(); ( @@ -2938,11 +3086,9 @@ impl Game<'_> { .iter() .filter(|m| &*m.kind.id == "minecraft:mannequin" && m.profile.is_some()) .map(|m| { - let t = m - .profile - .as_ref() - .and_then(|p| p.properties.iter().find(|p| p.name == "textures")); - let textures = t.map_or_else(Default::default, |t| { + let profile = m.profile.as_ref(); + let t = profile.and_then(|p| p.properties.iter().find(|p| p.name == "textures")); + let textures = if let Some(t) = t { let signature = if t.signature.is_some() { horizon_client::skins::Signature::Signed } else { @@ -2953,7 +3099,30 @@ impl Game<'_> { signature, &horizon_client::skins::TEXTURE_URIS, ) - }); + } else { + // `ResolvableProfile.resolveProfile`: no `textures` and + // only a name or an id resolves through the services. + let key = profile.and_then(|p| match (&p.name, p.uuid) { + (Some(name), None) => { + Some(horizon_client::skins::NameOrId::Name(name.clone())) + } + (None, Some(id)) => Some(horizon_client::skins::NameOrId::Id(id)), + _ => None, + }); + key.and_then(|key| match self.skin_profiles.borrow_mut().state(&key) { + horizon_client::skins::Resolve::Done(Some(profile)) => { + profile.textures().map(|(value, signature)| { + horizon_client::skins::unpack( + &value, + signature, + &horizon_client::skins::TEXTURE_URIS, + ) + }) + } + _ => None, + }) + .unwrap_or_default() + }; (m.id, textures) }) .collect(); @@ -2968,7 +3137,7 @@ impl Game<'_> { resolved.push((id, skin)); } for (id, skin) in resolved { - let skin = skin.filter(|s| !s.starts_with("skins/") || self.show_skin(s)); + let skin = skin.filter(|s| !s.starts_with("skins/") || self.again_skin(s)); if let Some(mob) = self .mobs .iter_mut() @@ -3018,6 +3187,10 @@ impl Game<'_> { self.skin_slots.push(e); true } + /// `show_skin`, or — its slot evicted — the image queued for upload again. + fn again_skin(&mut self, location: &str) -> bool { + self.show_skin(location) || self.skin_downloads.borrow_mut().again(location) + } /// ChatType decoration: `chat.translation_key` with sender/content parameters. /// ChatType.Bound.decorate: the chat type's translation, with the /// sender, the target and the message as its parameters, in its style. @@ -3121,6 +3294,8 @@ impl Game<'_> { p.velocity = v; } else if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { b.velocity = v; + } else if let Some(r) = self.rockets.iter_mut().find(|r| r.id == id as u32) { + r.velocity = v; } else if let Some(p) = self .remote .as_mut() @@ -3234,6 +3409,15 @@ impl Game<'_> { fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; + // AbstractSignEditScreen.tick: the editor closes once its sign is removed. + if let Some(edit) = &self.sign_edit + && !matches!( + self.world.block_entities.get(&edit.pos), + Some(BlockEntity::Sign(_)) + ) + { + self.close_sign_editor(); + } self.track_experience_display(); // Leaving a slot clears its bundle's selection here and on the server. self.tick_bundle_hover(); @@ -3278,10 +3462,15 @@ impl Game<'_> { // a client. Ticking it after the keybinds keeps a held use from // trying again a tick before the server's entry ends. self.cooldowns.tick(); + // Inventory.tick's ItemStack.inventoryTick: the pop time runs down. + for pop in &mut self.hotbar_pop { + *pop = pop.saturating_sub(1); + } // ClientLevel.tick: the border's size change. self.border.tick(); self.player_border(); self.tick_remote_entities(running); + self.tick_remote_guardian_eyes(running); // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells, // and the moving pistons a block event's client-side moveBlocks made // (their progress advances between the server's block updates). @@ -3289,6 +3478,8 @@ impl Game<'_> { self.with_level(|b, level, ticks| { b.client_tick_block_entities(level, ticks); }); + let pushes = std::mem::take(&mut self.block_ticks.piston_pushes); + self.push_piston_entities(pushes); self.sync_moving_pistons(); self.tick_hand(); self.tick_particles(); @@ -3417,12 +3608,10 @@ impl Game<'_> { let feet = [player.position.x, player.position.y, player.position.z]; for event in events { match event { - horizon_client::motion::MotionEvent::Emission { - state, in_water, .. - } => { + horizon_client::motion::MotionEvent::Emission { state, muffled, .. } => { let sounds = self.res.facts().get(state).sounds.clone(); // Player.playStepSound: muffled under the swim sound in water. - let (volume, pitch) = if in_water { + let (volume, pitch) = if muffled { (sounds.volume * 0.05, sounds.pitch * 0.8) } else { (sounds.volume * 0.15, sounds.pitch) @@ -3583,6 +3772,43 @@ impl Game<'_> { } /// ClientLevel.tickEntities; a frozen level only ticks the players /// (`TickRateManager.isEntityFrozen`). + /// `GuardianRenderer.getEntityToLookAt`: a guardian's eye follows its + /// synched attack target, else the camera. + fn tick_remote_guardian_eyes(&mut self, running: bool) { + use horizon_client::mobs::{Species, Who, guardian}; + if !running { + return; + } + let camera = self.player.as_ref().map(|p| { + [ + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height), + p.position.z, + ] + }); + let looks: Vec<_> = self + .mobs + .iter() + .enumerate() + .filter(|(_, m)| { + matches!(m.species(), Species::Guardian | Species::ElderGuardian) && m.alive() + }) + .filter_map(|(i, m)| { + let look = match m.ai.target.filter(|_| m.extra.flag) { + Some(Who::Mob(id)) => self + .mobs + .iter() + .find(|t| t.id == id) + .map(|t| [t.position.x, t.eye_y(), t.position.z]), + _ => camera, + }; + look.map(|look| (i, look)) + }) + .collect(); + for (i, look) in looks { + guardian::look_at(&mut self.mobs[i], look); + } + } fn tick_remote_entities(&mut self, running: bool) { if running { self.tick_text_displays(); @@ -3591,22 +3817,25 @@ impl Game<'_> { // server never sends the fluid contact, and the renderers read it (cod, salmon and // tropical fish lie on their side without `in_water`, #1591). // A frozen level ticks only the players, as below. - let fluids: Vec<_> = { + let (fluids, thundering): (Vec<_>, bool) = { let w = self.mob_world_base(&[]); let players = self.remote.as_ref().map(|r| &r.level_players); - self.mobs + let fluids = self + .mobs .iter() .map(|m| { (running || players.is_some_and(|p| p.contains_key(&(m.id as i32)))) .then(|| w.fluids(m.bounds(), m.eye_y())) }) - .collect() + .collect(); + (fluids, w.thundering) }; for (m, fluids) in self.mobs.iter_mut().zip(fluids) { if let Some(fluids) = fluids { m.fluids = fluids; } } + let game_time = self.world.game_time; let Some(r) = self.remote.as_mut() else { return; }; @@ -3681,6 +3910,10 @@ impl Game<'_> { m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32; *steps -= 1; } + // Fox.tick: the head tilt and crouch follow the synched flags. + if m.species() == horizon_client::mobs::Species::Fox { + horizon_client::mobs::fox::client_tick(m); + } // Chicken.aiStep: the wings follow the server's on-ground flag. if m.species() == horizon_client::mobs::Species::Chicken { horizon_client::mobs::farm::chicken_flap(m); @@ -3730,6 +3963,11 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Bat { horizon_client::mobs::bat::setup_animation_states(m); } + // The animation states a server computes in its own `ai_step`. + horizon_client::mobs::sync::client_tick(m, game_time); + if m.species() == horizon_client::mobs::Species::Panda { + horizon_client::mobs::panda::client_tick(m, thundering); + } } for o in self.orbs.iter_mut().filter(|_| running) { o.previous = o.position; @@ -3933,6 +4171,8 @@ impl Game<'_> { } } + /// `MultiPlayerGameMode.stopDestroyBlock`: aborts the break and starts + /// the attack strength again. pub(super) fn stop_remote_mining(&mut self) { if let Some((pos, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) { self.send(S::PlayerAction(play::PlayerAction { @@ -3941,6 +4181,7 @@ impl Game<'_> { direction: 0, sequence: 0, })); + self.reset_attack_strength(); } } @@ -3994,11 +4235,11 @@ impl Game<'_> { } else { self.destroy_progress(hit.pos) }; - let same = self - .remote - .as_ref() - .and_then(|r| r.destroying) - .is_some_and(|(p, _, _)| p == hit.pos); + // sameDestroyTarget: the same block and still the item the break began with. + let held = self.main_hand_key(); + let same = self.remote.as_ref().is_some_and(|r| { + r.destroying.is_some_and(|(p, _, _)| p == hit.pos) && r.destroying_item == held + }); if start && same { return; } @@ -4025,6 +4266,7 @@ impl Game<'_> { } if let Some(r) = self.remote.as_mut() { r.destroying = Some((hit.pos, face, 0.0)); + r.destroying_item = held; } // startDestroyBlock plays the first hit and crack itself; the // server's level events 2019 and 2020 do the rest. @@ -4331,6 +4573,16 @@ impl Game<'_> { if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { return (false, DryUse::default()); } + // BeehiveBlock.useItemOn: shears or a glass bottle on a full hive + // (honey level 5) is SUCCESS, so the click ends after UseItemOn and + // no UseItem follows (the server does the harvest, see `use_beehive`). + if held.is_some_and(|s| matches!(&*s.item, "minecraft:shears" | "minecraft:glass_bottle")) + && self + .hive_state(hit.pos) + .is_some_and(|(honey, _)| honey == Some(5)) + { + return (true, DryUse::default()); + } use horizon_core::geometry::Direction; let face = match hit.face { [0, 1, 0] => Direction::Up, @@ -5394,6 +5646,11 @@ impl Game<'_> { batch.text(atlas, message, (w - tw) / 2.0, 85.0, u32::MAX, true); } } + /// Shared flag 6 of an entity on a server's client (`None` without a server). + pub(super) fn remote_glowing(&self, id: u32) -> Option { + let r = self.remote.as_ref()?; + Some(r.glowing.contains(&(id as i32))) + } /// Status for `horizon-ctl status`. /// The other players' entities in the level and their names (from the /// player list). @@ -5771,7 +6028,16 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_ self.0.remote_use(); } fn pick(&mut self) { - if let Some(hit) = self.0.pick() { + // Minecraft.pickBlockOrEntity: an entity before the block is asked + // for (`handlePickItemFromEntity`), else the block. + if let Some(entity) = self.0.pick_entity_hit() { + if let Some(id) = entity { + self.0.send(S::PickItemFromEntity(play::PickItemFromEntity { + id, + include_data: self.0.has_control_down(), + })); + } + } else if let Some(hit) = self.0.pick() { self.0.send(S::PickItemFromBlock(play::PickItemFromBlock { pos: hit.pos, include_data: self.0.has_control_down(), diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index d6e4372f6..55ba7f997 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,10 +4,12 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, Who, bat, tame}; +use horizon_client::mobs::{ + Mob, Species, Who, armadillo, bat, bee, camel, creaking, finalize, panda, sniffer, sync, tame, +}; use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_protocol::entity_data::{Particle, ParticleData, Value}; -use horizon_protocol::registry::Builtin; +use horizon_protocol::registry::{Builtin, Dynamic}; /// The values `apply` takes from one SetEntityData packet, by vanilla's entry /// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses). @@ -27,6 +29,8 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti // client, which draws the flames. A client doesn't count the // fire down: the flag goes off when the server's fire is out. (0, Value::Byte(flags)) => m.fire_ticks = i32::from(flags & 1), + // Entity.DATA_POSE: the pose the species animates by. + (6, Value::Id(pose)) => sync::set_pose(m, (*pose).clamp(0, 17) as u8), // LivingEntity.DATA_LIVING_ENTITY_FLAGS: using an item 1, in the // off hand 2. The flag starts and stops the use; the client ticks // the count itself (a bow's pull follows it). @@ -70,10 +74,23 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti Who::Mob(*target as u32) }); } + // Panda: the counters, the two genes and DATA_ID_FLAGS (after + // AgeableMob's two entries). + (Species::Panda, 18, Value::Int(n)) => panda::set_unhappy(m, *n), + (Species::Panda, 19, Value::Int(n)) => panda::set_sneeze(m, *n), + (Species::Panda, 20, Value::Int(n)) => panda::set_eat(m, *n), + (Species::Panda, 21, Value::Byte(gene)) => m.extra.variant = (*gene).clamp(0, 6) as u8, + (Species::Panda, 22, Value::Byte(gene)) => m.extra.variant2 = (*gene).clamp(0, 6) as u8, + (Species::Panda, 23, Value::Byte(flags)) => panda::set_flags(m, *flags as u8), // PolarBear.DATA_STANDING_ID: the client animates the rearing. (Species::PolarBear, 18, Value::Bool(standing)) => m.extra.flag = *standing, // Bat.DATA_ID_FLAGS: resting in bit 0. (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), + // Fox.DATA_TYPE_ID and DATA_FLAGS_ID. + (Species::Fox, 18, Value::Int(variant)) => { + m.extra.variant = (*variant).clamp(0, 1) as u8 + } + (Species::Fox, 19, Value::Byte(flags)) => m.extra.ints[0] = i32::from(*flags as u8), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. (Species::Sheep, 18, Value::Byte(wool)) => { m.extra.color = (*wool & 15) as u8; @@ -100,6 +117,98 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => { m.extra.size = (*size).clamp(1, 127); } + // Warden.CLIENT_ANGER_LEVEL: the heartbeat's pace. + (Species::Warden, 16, Value::Int(anger)) => { + if let Some(st) = m.extra.warden.as_mut() { + st.client_anger = *anger; + } + } + // Sniffer.DATA_STATE (after AgeableMob's two): the animation + // follows it in `sync::client_tick`. + (Species::Sniffer, 18, Value::Id(state)) => { + sniffer::set_state(m, (*state).clamp(0, 6) as u8); + } + // Armadillo.ARMADILLO_STATE (after AgeableMob's two): the shell and + // its animations follow it in `sync::client_tick`. + (Species::Armadillo, 18, Value::Id(state)) => { + armadillo::set_state(m, (*state).clamp(0, 3) as u8); + } + // Goat.DATA_HAS_LEFT_HORN and DATA_HAS_RIGHT_HORN: the model hides + // a horn the goat lost. + (Species::Goat, 19, Value::Bool(has)) => m.extra.lost_horns[0] = !*has, + (Species::Goat, 20, Value::Bool(has)) => m.extra.lost_horns[1] = !*has, + // Shulker.DATA_ATTACH_FACE_ID, DATA_PEEK_ID and DATA_COLOR_ID. + (Species::Shulker, 16, Value::Id(face)) => m.extra.variant3 = (*face).clamp(0, 5) as u8, + (Species::Shulker, 17, Value::Byte(peek)) => m.extra.counter = i32::from(*peek), + (Species::Shulker, 18, Value::Byte(color)) => m.extra.color = *color as u8, + // Camel.DASH and LAST_POSE_CHANGE_TICK (after AbstractHorse's + // flags). + (Species::Camel | Species::CamelHusk, 19, Value::Bool(dashing)) => { + camel::set_dashing(m, *dashing); + } + (Species::Camel | Species::CamelHusk, 20, Value::Long(tick)) => { + camel::set_synced_pose_tick(m, *tick); + } + // Vex.DATA_FLAGS_ID: charging in bit 0. + (Species::Vex, 16, Value::Byte(flags)) => m.extra.flag = flags & 1 != 0, + // Creaking.CAN_MOVE, IS_ACTIVE and IS_TEARING_DOWN. + (Species::Creaking, 16, Value::Bool(can_move)) => m.extra.flag2 = !*can_move, + (Species::Creaking, 17, Value::Bool(active)) => m.extra.flag = *active, + (Species::Creaking, 18, Value::Bool(true)) => creaking::set_tearing_down(m), + // Allay.DATA_DANCING and DATA_CAN_DUPLICATE (a cooldown running + // is any non-zero `egg_time`). + (Species::Allay, 16, Value::Bool(dancing)) => m.extra.flag = *dancing, + (Species::Allay, 17, Value::Bool(can)) => m.extra.egg_time = i32::from(!*can), + // Axolotl.DATA_PLAYING_DEAD (after DATA_VARIANT): the factors + // ease in `sync::client_tick`. + (Species::Axolotl, 19, Value::Bool(dead)) => m.extra.axolotl.playing_dead = *dead, + // CopperGolem.COPPER_GOLEM_STATE (after DATA_WEATHER_STATE). + (Species::CopperGolem, 17, Value::Id(state)) => { + m.extra.variant3 = (*state).clamp(0, 4) as u8; + } + // AbstractHorse's flags take 18. Horse.DATA_ID_TYPE_VARIANT: the + // colour in the low byte, the markings in the next. + (Species::Horse, 19, Value::Int(v)) => { + m.extra.variant = (v & 0xFF).clamp(0, 6) as u8; + m.extra.variant2 = ((v >> 8) & 0xFF).clamp(0, 4) as u8; + } + // AbstractChestedHorse.DATA_ID_CHEST, then Llama.DATA_STRENGTH_ID + // and DATA_VARIANT_ID. + ( + Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama, + 19, + Value::Bool(chested), + ) => m.extra.chested = *chested, + (Species::Llama | Species::TraderLlama, 20, Value::Int(strength)) => { + m.extra.variant2 = (*strength).clamp(1, 5) as u8; + } + (Species::Llama | Species::TraderLlama, 21, Value::Int(variant)) => { + m.extra.variant = (*variant).clamp(0, 3) as u8; + } + // Axolotl.DATA_VARIANT (lucy 0 to blue 4) and Parrot.DATA_VARIANT_ID + // (after TamableAnimal's flags and owner). + (Species::Axolotl, 18, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 4) as u8, + (Species::Parrot, 20, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 4) as u8, + // Rabbit.DATA_TYPE_ID: the killer bunny's 99 has no model here. + (Species::Rabbit, 18, Value::Int(t)) if (0..=5).contains(t) => { + m.extra.variant = *t as u8; + } + // Bee.DATA_FLAGS_ID and DATA_ANGER_END_TIME (after Animal's). + (Species::Bee, 18, Value::Byte(flags)) => bee::set_synced(m, Some(*flags as u8), None), + (Species::Bee, 19, Value::Long(end)) => bee::set_synced(m, None, Some(*end)), + // AbstractFish.FROM_BUCKET takes 16: Salmon.DATA_TYPE (small 0 + // to large 2), Pufferfish.PUFF_STATE and + // TropicalFish.DATA_ID_TYPE_VARIANT. + (Species::Salmon, 17, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 2) as u8, + (Species::Pufferfish, 17, Value::Int(state)) => m.extra.size = (*state).clamp(0, 2), + (Species::TropicalFish, 17, Value::Int(v)) => tropical_fish(m, *v), + // Ghast.DATA_IS_CHARGING and WitherBoss.DATA_ID_INV. + (Species::Ghast, 16, Value::Bool(charging)) => m.extra.flag = *charging, + (Species::Wither, 19, Value::Int(ticks)) => m.extra.counter = (*ticks).max(0), + // CopperGolem.DATA_WEATHER_STATE: the oxidation the texture shows. + (Species::CopperGolem, 16, Value::Id(state)) => { + m.extra.variant = (*state).clamp(0, 3) as u8; + } // Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's // IS_CELEBRATING takes 16). (Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging, @@ -121,6 +230,56 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti } } +/// A tropical fish's packed variant: the pattern's id (the size, then the +/// index << 8), the base colour << 16 and the pattern colour << 24. Here the +/// pattern is 0 to 5 for the small ones and 6 to 11 for the large ones. +fn tropical_fish(m: &mut Mob, packed: i32) { + let (size, index) = (packed & 0xFF, (packed >> 8) & 0xFF); + // TropicalFish.Pattern.byId: an unknown id is a kob. + m.extra.variant = if size <= 1 && index < 6 { + (size * 6 + index) as u8 + } else { + 0 + }; + m.extra.variant2 = ((packed >> 16) & 0xFF) as u8 & 15; + m.extra.variant3 = ((packed >> 24) & 0xFF) as u8 & 15; +} + +/// The values of one SetEntityData packet that name an entry of a +/// synchronized registry (the variants of the cat, wolf, frog, pig, cow, +/// chicken and zombie nautilus) or count game time (a wolf's anger). +/// `game_time` is the client level's. +fn apply_registry_data( + m: &mut Mob, + values: &[(u8, i32, Value)], + registries: &Dynamic, + game_time: i64, +) { + let species = m.species(); + for (index, _, value) in values { + let registry = match (species, *index, value) { + (Species::Cat, 20, Value::Id(_)) => "minecraft:cat_variant", + (Species::Wolf, 23, Value::Id(_)) => "minecraft:wolf_variant", + (Species::Frog, 18, Value::Id(_)) => "minecraft:frog_variant", + (Species::Pig, 19, Value::Id(_)) => "minecraft:pig_variant", + (Species::Cow, 18, Value::Id(_)) => "minecraft:cow_variant", + (Species::Chicken, 18, Value::Id(_)) => "minecraft:chicken_variant", + (Species::ZombieNautilus, 21, Value::Id(_)) => "minecraft:zombie_nautilus_variant", + // Wolf.DATA_ANGER_END_TIME: the angry texture while it lies ahead. + (Species::Wolf, 22, Value::Long(end)) => { + m.extra.anger = (end - game_time).clamp(0, i64::from(i32::MAX)) as i32; + continue; + } + _ => continue, + }; + if let Value::Id(id) = value + && let Some(name) = registries.name(registry, *id) + { + m.extra.variant = finalize::variant_index(species, name); + } + } +} + /// The options of a synched particle list: an entity effect carries its ARGB /// colour, the omens none. fn swirls(list: &[Particle], builtin: &Builtin) -> Vec { @@ -175,6 +334,7 @@ impl Game<'_> { }; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { apply(m, values, &r.builtin, r.entity_id); + apply_registry_data(m, values, &r.registries, self.world.game_time); } } } diff --git a/crates/horizon-client/src/game/remote_mob_use.rs b/crates/horizon-client/src/game/remote_mob_use.rs index 9575cf925..bd38c7301 100644 --- a/crates/horizon-client/src/game/remote_mob_use.rs +++ b/crates/horizon-client/src/game/remote_mob_use.rs @@ -66,8 +66,11 @@ impl Game<'_> { | Species::Salmon | Species::TropicalFish | Species::Pufferfish - | Species::Axolotl - | Species::Tadpole => item == "minecraft:water_bucket", + | Species::Axolotl => item == "minecraft:water_bucket", + // Tadpole.mobInteract: frog food, else the bucket. + Species::Tadpole => { + item == "minecraft:water_bucket" || m.kind.food.iter().any(|f| f.as_str() == item) + } Species::Armadillo => item == "minecraft:brush", // ZombieVillager.mobInteract: CONSUME for a golden apple. Species::ZombieVillager => item == "minecraft:golden_apple", diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs index 05b1a2b9e..d70ab795d 100644 --- a/crates/horizon-client/src/game/remote_objects.rs +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -1,9 +1,10 @@ -//! Boats, minecarts, armor stands, item frames and paintings on a server's +//! Boats, minecarts, armor stands, item frames, paintings and fence knots on a server's //! client (`ClientPacketListener.handleAddEntity`, `handleSetEntityData`, //! `handleSetEquipment`): the server simulates them, the client places them //! where it says and interpolates their moves like a mob's. use super::Game; use horizon_client::entities::{ArmorStand, Cushion, ItemFrame, Painting}; +use horizon_client::mobs::leash::Holder; use horizon_core::geometry::Vec3; use horizon_protocol::entity_data::Value; use std::sync::Arc; @@ -24,7 +25,17 @@ impl Game<'_> { let at = Vec3::new(position[0], position[1], position[2]); let block = position.map(|v| v.floor() as i32); self.remove_remote_object(id); - if kind == "minecraft:text_display" { + if kind == "minecraft:leash_knot" { + // A lead that came before its knot waits as a mob holder with the + // knot's id (handleEntityLinkPacket's delayed holder); now it can + // be tied to the fence. + self.remote_knots.insert(id, block); + for m in &mut self.mobs { + if m.extra.leash == Some(Holder::Mob(id)) { + m.extra.leash = Some(Holder::Knot(block)); + } + } + } else if kind == "minecraft:text_display" { self.text_displays.insert( id as i32, super::text_displays::RemoteTextDisplay::new(position, yaw), @@ -153,6 +164,10 @@ impl Game<'_> { } (3, Value::Bool(visible)) => a.name_visible = *visible, (9, Value::Float(health)) => a.health = *health, + // ArmorStand.DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE. + (16..=21, Value::Floats(r)) if r.len() == 3 => { + a.pose[usize::from(index - 16)] = [r[0], r[1], r[2]]; + } // ArmorStand.DATA_CLIENT_FLAGS. (15, Value::Byte(flags)) => { a.small = flags & 1 != 0; @@ -304,6 +319,7 @@ impl Game<'_> { /// Every object a server sent (a new connection, level or dimension). pub(super) fn clear_remote_objects(&mut self) { self.text_displays.clear(); + self.remote_knots.clear(); self.carts.clear(); self.boats.clear(); self.armor_stands.clear(); @@ -314,6 +330,7 @@ impl Game<'_> { pub(super) fn remove_remote_object(&mut self, id: u32) { self.text_displays.remove(&(id as i32)); + self.remote_knots.remove(&id); self.carts.retain(|c| c.id != id); self.boats.retain(|b| b.id != id); self.armor_stands.retain(|a| a.id != id); diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 474c85d70..00d4abaed 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -3,8 +3,11 @@ //! and `handleSetEntityData`): the server simulates them, the client draws //! them where it says and interpolates their moves. use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector}; -use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_client::projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}; +use horizon_client::{ + collisions::SceneCollisions, + particles::{ParticleOptions, ParticleType}, +}; use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; use horizon_protocol::entity_data::Value; use horizon_world::registry::BlockStateId; @@ -23,6 +26,59 @@ fn default_cloud_particle() -> ParticleOptions { ParticleOptions::colored(ParticleType::EntityEffect, [1.0; 4]) } +/// `AreaEffectCloud.clientTick`: while waiting, now and then two particles +/// near the middle; then about one per square block of the disc, drifting +/// (an entity effect stays still). +pub(super) fn cloud_client_tick( + particles: &mut horizon_client::particles::ParticleEngine, + at: [f64; 3], + radius: f32, + waiting: bool, + particle: &ParticleOptions, +) { + if waiting && particles.random().next_boolean() { + return; + } + let (count, spread) = if waiting { + (2, 0.2) + } else { + ( + (std::f32::consts::PI * radius * radius).ceil() as i32, + radius, + ) + }; + for _ in 0..count { + let r = particles.random(); + let angle = r.next_float() * std::f32::consts::TAU; + let distance = r.next_float().sqrt() * spread; + let at = [ + at[0] + f64::from(angle.cos() * distance), + at[1], + at[2] + f64::from(angle.sin() * distance), + ]; + let (options, velocity) = if particle.ty == ParticleType::EntityEffect { + let default = waiting && r.next_boolean(); + let options = if default { + default_cloud_particle() + } else { + particle.clone() + }; + (options, [0.0; 3]) + } else if waiting { + (particle.clone(), [0.0; 3]) + } else { + let v = [ + (0.5 - r.next_double()) * 0.15, + f64::from(0.01f32), + (0.5 - r.next_double()) * 0.15, + ]; + (particle.clone(), v) + }; + // `addAlwaysVisibleParticle`. + particles.add_with(&options, at, velocity, false, true); + } +} + /// The projectile a type id names, as Horizon models it. fn projectile_kind(kind: &str) -> Option { Some(match kind { @@ -392,31 +448,58 @@ impl Game<'_> { let id = t.id; t.remote_step(|at| step(id, at)); } - // FireworkRocketEntity.tick: a rocket attached to the gliding local - // player boosts it client-side too (attachedToEntity.isFallFlying). + // FireworkRocketEntity.tick: a rocket attached to an entity follows it + // and boosts it client-side too (attachedToEntity.isFallFlying), and + // every rocket leaves its spark trail on a client. let me = self .remote .as_ref() .and_then(|r| u32::try_from(r.entity_id).ok()); - for r in &mut self.rockets { - let id = r.id; - r.remote_step(|at| step(id, at)); - if me.is_some() - && r.attached_to == me - && let Some(p) = self.player.as_mut() - && p.fall_flying - { - let look = view_vector(self.yaw, self.pitch); - let m = p.velocity; - p.velocity = Vec3::new( - m.x + look[0] * 0.1 + (look[0] * 1.5 - m.x) * 0.5, - m.y + look[1] * 0.1 + (look[1] * 1.5 - m.y) * 0.5, - m.z + look[2] * 0.1 + (look[2] * 1.5 - m.z) * 0.5, - ); - r.position = p.position; - r.velocity = p.velocity; + let mut rockets = std::mem::take(&mut self.rockets); + for r in &mut rockets { + r.remote_step(&mut SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }); + if let Some(target) = r.attached_to { + if me == Some(target) { + if let Some(p) = self.player.as_mut() { + if p.fall_flying { + let look = view_vector(self.yaw, self.pitch); + let m = p.velocity; + p.velocity = Vec3::new( + m.x + look[0] * 0.1 + (look[0] * 1.5 - m.x) * 0.5, + m.y + look[1] * 0.1 + (look[1] * 1.5 - m.y) * 0.5, + m.z + look[2] * 0.1 + (look[2] * 1.5 - m.z) * 0.5, + ); + } + r.position = p.position; + r.velocity = p.velocity; + } + } else if let Some(m) = self.mobs.iter().find(|m| m.id == target) { + // Another player's motion is not known here: its step. + r.velocity = Vec3::new( + m.position.x - r.previous.x, + m.position.y - r.previous.y, + m.position.z - r.previous.z, + ); + r.position = m.position; + } } + let g = |g: &mut horizon_core::random::LegacyRandom| g.next_gaussian() * 0.05; + let v = [ + g(&mut self.world.random), + -r.velocity.y * 0.5, + g(&mut self.world.random), + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::Firework), + [r.position.x, r.position.y, r.position.z], + v, + ); } + self.rockets = rockets; for c in &mut self.crystals { c.time += 1; c.position = step(c.id, c.position); @@ -446,52 +529,10 @@ impl Game<'_> { } } - /// `AreaEffectCloud.clientTick`: while waiting, now and then two - /// particles near the middle; then about one per square block of the - /// disc, drifting (an entity effect stays still). + /// `AreaEffectCloud.clientTick` for each cloud a server tracks. fn tick_remote_clouds(&mut self) { for c in &self.potions.clouds { - let r = self.particles.random(); - if c.waiting && r.next_boolean() { - continue; - } - let (count, spread) = if c.waiting { - (2, 0.2) - } else { - ( - (std::f32::consts::PI * c.radius * c.radius).ceil() as i32, - c.radius, - ) - }; - for _ in 0..count { - let r = self.particles.random(); - let angle = r.next_float() * std::f32::consts::TAU; - let distance = r.next_float().sqrt() * spread; - let at = [ - c.at[0] + f64::from(angle.cos() * distance), - c.at[1], - c.at[2] + f64::from(angle.sin() * distance), - ]; - let (options, velocity) = if c.particle.ty == ParticleType::EntityEffect { - let default = c.waiting && r.next_boolean(); - let options = if default { - default_cloud_particle() - } else { - c.particle.clone() - }; - (options, [0.0; 3]) - } else if c.waiting { - (c.particle.clone(), [0.0; 3]) - } else { - let v = [ - (0.5 - r.next_double()) * 0.15, - f64::from(0.01f32), - (0.5 - r.next_double()) * 0.15, - ]; - (c.particle.clone(), v) - }; - self.particles.add(&options, at, velocity); - } + cloud_client_tick(&mut self.particles, c.at, c.radius, c.waiting, &c.particle); } } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index c6c632f02..27081b43b 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -92,9 +92,8 @@ impl Game<'_> { distant_terrain: self.lod.is_some(), cloud_range_chunks: self.settings.cloud_range, camera_y: camera.y, - // level.getMinY(): the Nether and the End start at y 0. - min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 }, - flat: false, + min_y: self.level_min_y(), + flat: self.level_flat(), forward: forward.map(|c| c as f32), rain, thunder, @@ -108,9 +107,30 @@ impl Game<'_> { }, ) } - /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. + /// `ClientLevelData.isFlat`: on the server thread, the world-wide flag. + fn level_flat(&self) -> bool { + match self.remote.as_ref() { + Some(r) => r.flat, + None => self.world_flat, + } + } + /// `Level.getMinY`: the current dimension type's minimum y. + fn level_min_y(&self) -> i32 { + match self.remote.as_ref() { + Some(r) => r.dimension.min_y, + None => self.dim.min_y(), + } + } + /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon and not under + /// water. `ClientLevelData.getHorizonHeight`: the bottom of a flat world, + /// otherwise y 63. pub(super) fn dark_disc(&self, camera: glam::DVec3) -> bool { - camera.y < 63.0 + let horizon = if self.level_flat() { + f64::from(self.level_min_y()) + } else { + 63.0 + }; + camera.y < horizon && fog_type( &self.world, self.res.facts(), @@ -245,6 +265,7 @@ impl Game<'_> { 1.0, ); } + self.particles.particle_level = self.settings.particles; if let Some(e) = eye { self.particles.camera = e; } @@ -272,6 +293,16 @@ impl Game<'_> { && motion_blocking(world, facts, p[0], p[2], p[1] + 64) <= p[1] && rains_at(world, biomes, p[0], p[1], p[2]) }; + let tables = &self.pack.context.tables; + let model_offset = |state, x, z| tables.offset(state, x, z); + let gateway_particles = |state, p| { + self.res + .block_entity_render() + .gateway_faces(world, state, p) + .len() + }; + // Level.isThundering: a thunder level above 0.9 where the sky is open. + let thundering = self.dim == Dim::Overworld && world.weather.levels(1.0).1 > 0.9; let ctx = AnimateContext { world, facts, @@ -280,6 +311,10 @@ impl Game<'_> { registry: self.pack.assets.registry, raining_at: &raining_at, marker: marker.map(|name| (name, &marker_options as &dyn Fn(_) -> _)), + model_offset: &model_offset, + gateway_particles: &gateway_particles, + thundering, + ultrawarm: self.dim == Dim::Nether, }; if let Some(e) = eye { let block = [ @@ -288,13 +323,16 @@ impl Game<'_> { e[2].floor() as i32, ]; animate_tick(self.res.animate(), &mut self.particles, &ctx, block); - // The Horizon Weather option off means no rain visuals at all. + // The Horizon Weather option off means no rain visuals or sounds at all. if rain > 0.0 && self.settings.horizon.weather { - // ClientLevel.tickWeatherEffects: rain splashes within the weather radius. + // ClientLevel.tickWeatherEffects: rain splashes within the weather + // radius, and the rain sound. let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231)); let radius = self.settings.weather_radius; let diameter = 2 * radius + 1; - let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32; + let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32 + / if self.settings.particles == 1 { 2 } else { 1 }; + let mut rain_position = None; for _ in 0..count { let x = block[0] + random.next_int_bound(diameter).unwrap_or(0) - radius; let z = block[2] + random.next_int_bound(diameter).unwrap_or(0) - radius; @@ -307,6 +345,12 @@ impl Game<'_> { continue; } let below = top - 1; + rain_position = Some([x, below, z]); + // The Minimal option stops at the first spot that rains (the + // rain sound still plays there). + if self.settings.particles >= 2 { + break; + } let (bx, bz) = (random.next_double(), random.next_double()); let state = world.block(x, below, z); let f = facts.get(state); @@ -338,6 +382,26 @@ impl Game<'_> { self.particles .add(&ParticleOptions::simple(ty), p, [0.0; 3]); } + // The last rain column of the tick makes the sound, more often the + // longer it has been quiet; indoors it is the quieter one. + if let Some(at) = rain_position { + let waited = self.rain_sound_time; + self.rain_sound_time += 1; + if random.next_int_bound(3).unwrap_or(0) < waited { + self.rain_sound_time = 0; + let roof = + motion_blocking(world, facts, block[0], block[2], MIN_Y + HEIGHT); + let (name, volume, pitch) = if at[1] > block[1] + 1 && roof > block[1] { + ("minecraft:weather.rain.above", 0.1, 0.5) + } else { + ("minecraft:weather.rain", 0.2, 1.0) + }; + let p = at.map(|c| f64::from(c) + 0.5); + // playLocalSound: guests make their own rain, so a host + // must not capture it for them. + self.audio.play_unshared(name, Some(p), volume, pitch); + } + } } } if let Some(r) = &self.renderer { diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 53323fdbb..443cb2c03 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -683,7 +683,7 @@ impl Game<'_> { let objective = board.display_objective(sb::SLOT_LIST); let shown = tab_list::visible( key, - self.remote.is_none(), + self.has_singleplayer_server(), players.len(), objective.is_some(), ); diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 750895adb..4b5c4c333 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -322,6 +322,58 @@ impl Game<'_> { ); } } + /// LocalPlayer.respawn: the player comes back (the death screen's + /// button, or at once with `immediate_respawn`). + pub(super) fn respawn_player(&mut self) -> Result<()> { + if self.remote.is_none() { + // PlayerList.respawn removes the dead player, and Player.remove's + // inventoryMenu.removed drops what the cursor held, whatever + // keep_inventory says (the 20-tick branch handles a later respawn). + if let Some(stack) = self.carried.take() + && let Some(eye) = self.eye_position() + { + self.throw_from_eyes(stack, eye, false); + } + let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); + self.experience.respawn(keep); + // The guests are sent the respawned host as a new entity, not the dead body. + if let Some(host) = self.lan.as_mut() { + let id = host.host_entity; + host.hub.respawned(id); + } + // Autosaves keep a login position; death must resolve the respawn point instead. + self.level.position = None; + } + if self.remote.is_some() { + self.ui.death_text = None; + self.toggles.respawn(); + self.remote_respawn(); + } else if self.respawn_config.is_some() { + // LocalPlayer.respawn: KeyMapping.resetToggleKeys. + self.toggles.respawn(); + // PlayerList.respawn at the respawn anchor, once it is loaded. + self.begin_anchor_respawn()?; + self.screen = Screen::Playing; + self.ui.death_text = None; + self.spawn_player()?; + self.capture(true); + } else { + // LocalPlayer.respawn: KeyMapping.resetToggleKeys. + self.toggles.respawn(); + self.respawn_out_of_end()?; + self.player = None; + self.screen = Screen::Playing; + self.ui.death_text = None; + self.spawn_player()?; + self.capture(true); + } + // ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's + // respawned player only watches. + if self.remote.is_none() && self.level.hardcore { + self.set_mode(GameMode::Spectator); + } + Ok(()) + } pub(super) fn death_click(&mut self) -> Result<()> { if self .ui @@ -339,51 +391,11 @@ impl Game<'_> { .into_iter() .find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)) .map(|d| d.3); - if hit == Some(0) && self.remote.is_none() { - let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); - self.experience.respawn(keep); - // The guests are sent the respawned host as a new entity, not the dead body. - if let Some(host) = self.lan.as_mut() { - let id = host.host_entity; - host.hub.respawned(id); - } - // Autosaves keep a login position; death must resolve the respawn point instead. - self.level.position = None; - } match hit { - Some(0) if self.remote.is_some() => { - self.ui.death_text = None; - self.toggles.respawn(); - self.remote_respawn(); - } - Some(0) if self.respawn_config.is_some() => { - // LocalPlayer.respawn: KeyMapping.resetToggleKeys. - self.toggles.respawn(); - // PlayerList.respawn at the respawn anchor, once it is loaded. - self.begin_anchor_respawn()?; - self.screen = Screen::Playing; - self.ui.death_text = None; - self.spawn_player()?; - self.capture(true); - } - Some(0) => { - // LocalPlayer.respawn: KeyMapping.resetToggleKeys. - self.toggles.respawn(); - self.respawn_out_of_end()?; - self.player = None; - self.screen = Screen::Playing; - self.ui.death_text = None; - self.spawn_player()?; - self.capture(true); - } + Some(0) => self.respawn_player()?, Some(1) => self.close_world()?, _ => {} } - // ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's - // respawned player only watches. - if hit == Some(0) && self.remote.is_none() && self.level.hardcore { - self.set_mode(GameMode::Spectator); - } if hit.is_some() { self.audio.play_button_click(); } diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 473509f0a..65dfede1a 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1515,6 +1515,16 @@ impl Game<'_> { fn tick_entity_events(&mut self) { self.tick_player_sculk_events(); self.tick_mob_sculk_events(); + // Dropped items are entities too: Entity.applyEffectsFromBlocks. + let items: Vec<[f64; 3]> = self + .dropped + .iter() + .filter(|i| i.on_ground) + .map(|i| [i.position.x, i.position.y, i.position.z]) + .collect(); + for at in items { + self.step_on_redstone_ore(at, false); + } } /// Entity.move emits on the authoritative server too, for each ServerPlayer. @@ -1530,6 +1540,9 @@ impl Game<'_> { }); if let Some((at, on_ground, health, flying)) = player { let crouch = self.keys.contains(&KeyCode::ShiftLeft); + if on_ground && !self.spectator() { + self.step_on_redstone_ore(at, crouch); + } let in_water = self.in_water_at(at); self.entity_motion_events( Who::Player, @@ -1548,6 +1561,26 @@ impl Game<'_> { } } + /// `RedStoneOreBlock.stepOn`: standing on the ore lights it, unless the + /// entity is stepping carefully (`attack_block` only lights an unlit ore). + fn step_on_redstone_ore(&mut self, at: [f64; 3], carefully: bool) { + if carefully { + return; + } + // getOnPosLegacy: 0.2 below the feet. + let pos = [ + at[0].floor() as i32, + (at[1] - 0.2).floor() as i32, + at[2].floor() as i32, + ]; + if matches!( + &*self.block_name(pos), + "minecraft:redstone_ore" | "minecraft:deepslate_redstone_ore" + ) { + let _ = self.attack_block(pos); + } + } + fn tick_mob_sculk_events(&mut self) { let snapshot: Vec<(u32, [f64; 3], bool, bool, Species, Option)> = self .mobs @@ -1565,6 +1598,9 @@ impl Game<'_> { }) .collect(); for (id, at, on_ground, in_water, species, damaged) in snapshot { + if on_ground { + self.step_on_redstone_ore(at, false); + } let emits = !matches!(species, Species::Shulker); if emits { self.entity_motion_events(Who::Mob(id), at, on_ground, in_water, false, false); diff --git a/crates/horizon-client/src/game/server_packs.rs b/crates/horizon-client/src/game/server_packs.rs index 58d25de0e..a616be199 100644 --- a/crates/horizon-client/src/game/server_packs.rs +++ b/crates/horizon-client/src/game/server_packs.rs @@ -3,7 +3,7 @@ //! and `DownloadedPackSource` as `Minecraft` drives it): the prompt, the //! server list's setting, downloads into `downloads/`, and a resource reload //! with the server's packs on top of the player's own. -use super::Game; +use super::{Game, Progress}; use horizon_client::{ Result, confirm_screen::Confirm, @@ -67,6 +67,13 @@ impl PackPrompt { } } +impl ServerPackState { + /// The `ToastManager` slots the download toasts hold. + pub(super) fn toast_slots(&self) -> impl Iterator + '_ { + self.notifiers.iter().filter_map(|n| n.toast.as_ref()?.slot) + } +} + /// The game's `DownloadedPackSource`. #[derive(Default)] pub(super) struct ServerPackState { @@ -82,6 +89,9 @@ pub(super) struct ServerPackState { pub(super) active: Vec, /// The download batches' notifiers, oldest first. notifiers: Vec, + /// A `tick`-asked reload staged on a worker (`LoadingOverlay`): the + /// frame draws its progress until `tick_server_packs` applies it. + pub(super) reload: Option, } /// `DownloadedPackSource.createDownloadNotifier`: one batch's progress in its /// own `SystemToast`. @@ -191,6 +201,21 @@ fn saves() -> PathBuf { std::env::current_dir().unwrap_or_default().join("saves") } +/// `LoadingOverlay`'s stage lines for a pack reload, indexed by `progress`. +const RELOAD_LINES: [&str; 4] = [ + "Preparing resources", + "Loading assets", + "Loading pack tables", + "Applying resources", +]; +/// A pack reload `ServerPacks::tick` asked for: the CPU half runs on a +/// worker while `progress` feeds the loading screen, then the apply lands +/// on the render thread. +pub(super) struct PackReload { + pub(super) progress: Progress, + handle: std::thread::JoinHandle>, +} + impl Game<'_> { /// `ConnectScreen`: the server's setting decides what its packs do /// (`configureForServerControl`); single player's own server takes them @@ -314,6 +339,7 @@ impl Game<'_> { if self.rest_loader.is_some() || self.world_loader.is_some() { return; } + self.drive_pack_reload(); let finished = self .server_packs .queue @@ -328,13 +354,8 @@ impl Game<'_> { if !tick.download.is_empty() { self.start_pack_downloads(tick.download); } - if let Some(mut load) = tick.reload { - while let Some(recovery) = { - let ok = self.reload_server_packs(&load); - self.server_packs.packs.reloaded(ok) - } { - load = recovery; - } + if let Some(load) = tick.reload { + self.start_pack_reload(&load); } } for (id, status) in self.server_packs.packs.take_replies() { @@ -379,24 +400,90 @@ impl Game<'_> { } } /// `DownloadedPackSource.startReload`: the packs on top of the player's - /// own, then `Minecraft.reloadResourcePacks`. False when a pack has no - /// readable `pack.mcmeta` or the reload failed. - fn reload_server_packs(&mut self, load: &[(u128, PathBuf)]) -> bool { - let packs: Option> = load + /// own, staged on a worker (`Minecraft.reloadResourcePacks` under a + /// `LoadingOverlay`); `drive_pack_reload` applies it. A pack with no + /// readable `pack.mcmeta` fails the reload at once, as `onFailure`. + fn start_pack_reload(&mut self, load: &[(u128, PathBuf)]) { + let server: Option> = load .iter() .map(|(id, path)| packs::server_pack(*id, path)) .collect(); - let Some(packs) = packs else { + let Some(server) = server else { log::warn!("Horizon: invalid pack metadata in a server pack, ignoring all"); - return false; + self.finish_pack_reload(false); + return; }; - self.server_packs.active = packs; - match self.reload_selected_packs() { + self.server_packs.active = server.clone(); + // The overlay swallows input until the apply (`LoadingOverlay`): + // release what is held so nothing keeps acting while it covers the + // frame (`KeyMapping.releaseAll` when a screen opens). + self.keys.clear(); + self.physical_keys.clear(); + self.left = false; + self.right = false; + let vanilla = self.vanilla_root(); + if self.ui.vanilla_root.as_os_str().is_empty() { + self.ui.vanilla_root = vanilla.clone(); + } + let (selected, mods, dev_mods) = ( + self.settings.resource_packs.clone(), + self.settings.mods.enabled.clone(), + self.options.dev_mods.clone(), + ); + let (assets, res, context) = ( + self.pack.assets.clone(), + self.res.clone(), + self.pack.context.clone(), + ); + let (unicode, japanese) = (self.settings.force_unicode, self.settings.japanese_glyphs); + let progress = Progress::with(&RELOAD_LINES); + let worker = progress.clone(); + let handle = std::thread::Builder::new() + .name("server-pack-reload".into()) + .spawn(move || { + super::packs::stage_pack( + &vanilla, &selected, &server, &mods, &dev_mods, &assets, &res, &context, + unicode, japanese, &worker, + ) + .map_err(|e| e.to_string()) + }); + match handle { + Ok(handle) => self.server_packs.reload = Some(PackReload { progress, handle }), + Err(e) => { + log::error!("Horizon: could not start the pack reload worker: {e}"); + self.finish_pack_reload(false); + } + } + } + /// `PackReloadConfig.Callbacks`: applies the staged reload once its + /// worker is done; on failure the packs active before reload again. + fn drive_pack_reload(&mut self) { + let Some(reload) = &self.server_packs.reload else { + return; + }; + if !reload.handle.is_finished() { + return; + } + let reload = self.server_packs.reload.take().unwrap(); + let staged = reload + .handle + .join() + .unwrap_or_else(|_| Err("the pack reload worker panicked".into())); + let ok = match staged + .and_then(|staged| self.apply_staged_pack(staged).map_err(|e| e.to_string())) + { Ok(()) => true, Err(e) => { log::warn!("Horizon: server resource pack reload failed: {e}"); false } + }; + self.finish_pack_reload(ok); + } + /// `ServerPacks::reloaded` and the recovery reload it can ask for. + fn finish_pack_reload(&mut self, ok: bool) { + if let Some(recovery) = self.server_packs.packs.reloaded(ok) { + self.start_pack_reload(&recovery); } } @@ -423,15 +510,22 @@ impl Game<'_> { .layout(atlas, (w, h)) .draw(batch, atlas, self.cursor, [&yes, &no]); } - /// The download notifiers' toasts, each in the next 32-pixel slot - /// below an advancement or recipe toast (`ToastManager`). - pub(super) fn draw_pack_toasts(&mut self, batch: &mut HudBatch) { + /// The download notifiers' toasts, each in a free 32-pixel slot of the + /// `ToastManager` (`hidden`, F1, keeps them timing out undrawn). + pub(super) fn draw_pack_toasts(&mut self, batch: &mut HudBatch, hidden: bool) { let multiplier = f64::from(self.settings.notification_display_time); - let mut slot = usize::from(!self.adv.toasts.is_empty()); + let mut used = self.toast_slots_used(); for notifier in &mut self.server_packs.notifiers { let Some(toast) = &mut notifier.toast else { continue; }; + if toast.slot.is_none() { + let Some(slot) = (0..Self::TOAST_SLOTS).find(|s| used & (1 << s) == 0) else { + continue; + }; + used |= 1 << slot; + toast.slot = Some(slot); + } let (sound, finished) = toast.update(multiplier); if let Some(show) = sound { let event = if show { "ui.toast.in" } else { "ui.toast.out" }; @@ -442,8 +536,9 @@ impl Game<'_> { notifier.toast = None; continue; } - toast.draw(&self.gui.atlas, batch, 32.0 * slot as f32); - slot += 1; + if let (false, Some(slot)) = (hidden, toast.slot) { + toast.draw(&self.gui.atlas, batch, 32.0 * slot as f32); + } } } /// A left click on the prompt: its answer when it hit a button. diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index c4f7f98d1..228b7c206 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -176,18 +176,30 @@ impl Game<'_> { if projectile { return; } - let Some(id) = attacker else { return }; + let Some(id) = attacker else { + // Another player's melee hit has no mob behind it. + if let Some((from, disable)) = self.combat.player_attacker { + let fully = outcome.blocked >= damage; + self.blocked_by_attacker(&component, [from[0], from[2]], fully, disable, at); + } + return; + }; let fully = outcome.blocked >= damage; let Some(m) = self.mobs.iter().find(|m| m.id == id) else { return; }; let (mx, mz) = (m.position.x, m.position.z); - let disable = m - .extra - .main_hand - .as_deref() - .and_then(|item| self.res.items().get(item)) - .map_or(0.0, |i| i.disable_blocking_seconds); + // LivingEntity.getSecondsToDisableBlocking: the held weapon's value; + // Warden overrides it with a flat 5 seconds. + let disable = if m.species() == horizon_client::mobs::Species::Warden { + 5.0 + } else { + m.extra + .main_hand + .as_deref() + .and_then(|item| self.res.items().get(item)) + .map_or(0.0, |i| i.disable_blocking_seconds) + }; // Ravager.blockedByItem: stunned half the time (the defender pushed // apart), else the defender flung away; no roar in progress. if m.species() == horizon_client::mobs::Species::Ravager { @@ -214,6 +226,21 @@ impl Game<'_> { let _ = self.handle_mob_events(events); return; } + self.blocked_by_attacker(&component, [mx, mz], fully, disable, at); + } + + /// What a blocked melee hit does to the defender once the shield took + /// it: `LivingEntity.blockedByItem` knocks them back unless fully + /// blocked, then `Player.blockUsingItem` disables the shield. + fn blocked_by_attacker( + &mut self, + component: &horizon_client::items::BlocksAttacks, + attacker: [f64; 2], + fully: bool, + disable: f32, + at: Option<[f64; 3]>, + ) { + let [mx, mz] = attacker; // LivingEntity.blockedByItem: defender.knockback(0.5, defender - attacker), // which moves the defender along -(xd, zd). if !fully && let Some(p) = self.player.as_mut() { diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index 2d010f1f5..c26314513 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -5,7 +5,8 @@ use super::{Game, lan::LanHost}; use horizon_client::{ containers::BlockEntity, hud::{HudBatch, rgba}, - signs::wood_type, + items::ItemStack, + signs::{DYE_TEXT, wood_type}, ui::EditBox, }; use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; @@ -20,6 +21,9 @@ pub(super) struct SignEditor { pub line: usize, /// The line being edited (`AbstractSignEditScreen`'s text field). edit: EditBox, + /// `AbstractSignEditScreen.messages`: the side's lines as edited, sent + /// when the editor closes, even if the sign is gone by then. + lines: [String; 4], } fn sign_box() -> EditBox { @@ -31,13 +35,172 @@ fn sign_box() -> EditBox { } impl Game<'_> { + /// `SignBlockEntity.getSlotPlayerIsFacing`: whether the player stands in + /// front of the sign's text (within 90 degrees of its facing). + fn facing_sign_front(&self, pos: (i32, i32, i32)) -> bool { + let Some(player) = self.player.as_ref() else { + return true; + }; + let state = self.world.block(pos.0, pos.1, pos.2); + let Some(state) = self.pack.assets.registry.state(state) else { + return true; + }; + let prop = |key: &str| state.properties.get(key).map(String::as_str); + // getYRotationDegrees: a wall sign's `Direction.toYRot`, a standing or + // ceiling sign's rotation segment. + let y_rot = if state.name.contains("_wall_") { + match prop("facing") { + Some("west") => 90.0, + Some("north") => 180.0, + Some("east") => 270.0, + _ => 0.0, + } + } else { + prop("rotation") + .and_then(|r| r.parse::().ok()) + .unwrap_or(0.0) + * 22.5 + }; + // getSignHitboxCenterPosition: only a wall sign's board is off-centre, + // against the wall it hangs on. + let centre = if state.name.ends_with("_wall_sign") { + match y_rot as i32 { + 90 => (0.9375, 0.5), + 180 => (0.5, 0.9375), + 270 => (0.0625, 0.5), + _ => (0.5, 0.0625), + } + } else { + (0.5, 0.5) + }; + let xd = player.position.x - (f64::from(pos.0) + centre.0); + let zd = player.position.z - (f64::from(pos.2) + centre.1); + let player_y_rot = (zd.atan2(xd).to_degrees() - 90.0) as f32; + // Mth.degreesDifferenceAbs. + let diff = (player_y_rot - y_rot).rem_euclid(360.0); + let diff = if diff >= 180.0 { 360.0 - diff } else { diff }; + diff <= 90.0 + } + /// `SignBlock.useWithoutItem` (the block's `OpenMenu` effect): a waxed + /// sign plays the failed-interaction sound; otherwise a player who may + /// build edits the side they face. + pub(super) fn use_sign_empty_hand(&mut self, pos: [i32; 3]) { + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&key) else { + return; + }; + if sign.waxed { + // `getSignInteractionFailedSoundEvent`: a hanging sign has its own. + let sound = if sign.hanging { + "minecraft:block.hanging_sign.waxed_interact_fail" + } else { + "minecraft:block.sign.waxed_interact_fail" + }; + self.audio + .play(sound, Some(pos.map(|v| f64::from(v) + 0.5)), 1.0, 1.0); + } else if self.may_build() { + let front = self.facing_sign_front(key); + self.open_sign_editor(key, front); + } + } + /// `SignBlock.useItemOn` with a `SignApplicator` in hand (dyes, ink sacs, + /// honeycomb): the item changes the side the player faces and is used up. + /// Whether it did; a sign it does not apply to goes on to the empty hand. + pub(super) fn use_sign_applicator(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { + let Some(stack) = held else { + return false; + }; + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&key) else { + return false; + }; + if sign.waxed || !self.may_build() { + return false; + } + let item = &*stack.item; + let dye = if item.ends_with("_dye") { + self.res + .items() + .get(&stack.item) + .and_then(|i| i.dye.clone()) + } else { + None + }; + let colour = dye.and_then(|d| DYE_TEXT.iter().position(|(n, _)| *n == d)); + if !matches!( + item, + "minecraft:honeycomb" | "minecraft:glow_ink_sac" | "minecraft:ink_sac" + ) && colour.is_none() + { + return false; + } + let front = self.facing_sign_front(key); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) else { + return false; + }; + let centre = pos.map(|v| f64::from(v) + 0.5); + let sound = if item == "minecraft:honeycomb" { + // HoneycombItem.tryApplyToSign: waxes any sign, empty or not. + sign.waxed = true; + "minecraft:item.honeycomb.wax_on" + } else { + let side = if front { + &mut sign.front + } else { + &mut sign.back + }; + // SignApplicator.canApplyToSign: the side must have text. + if side.is_empty() { + return false; + } + match colour { + Some(c) if side.color != c as u8 => { + side.color = c as u8; + "minecraft:item.dye.use" + } + None if item == "minecraft:glow_ink_sac" && !side.glowing => { + side.glowing = true; + "minecraft:item.glow_ink_sac.use" + } + None if item == "minecraft:ink_sac" && side.glowing => { + side.glowing = false; + "minecraft:item.ink_sac.use" + } + _ => return false, + } + }; + if item == "minecraft:honeycomb" { + self.level_event_at(3003, pos, 0); + } + self.audio.play(sound, Some(centre), 1.0, 1.0); + self.mark_block_entity_updated(key); + let state = self.world.block(pos[0], pos[1], pos[2]); + self.post_block_game_event( + "minecraft:block_change", + pos, + self.sculk_actor(), + Some(state), + ); + self.stats.add("used", &stack.item, 1); + self.consume_held(); + self.trigger_block("minecraft:item_used_on_block", pos, stack); + true + } /// `SignBlock.openTextEdit` for the front side after placement. pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) { + // Minecraft.setScreen: the editor already open is removed first. + self.close_sign_editor(); + let lines = match self.world.block_entities.get(&pos) { + Some(BlockEntity::Sign(sign)) if front => sign.front.lines.clone(), + Some(BlockEntity::Sign(sign)) => sign.back.lines.clone(), + _ => Default::default(), + }; self.sign_edit = Some(SignEditor { pos, front, line: 0, edit: sign_box(), + lines, }); self.sign_load(); self.keys.clear(); @@ -50,14 +213,11 @@ impl Game<'_> { pub(super) fn close_sign_editor(&mut self) { if let Some(edit) = self.sign_edit.take() { if self.remote.is_some() { - if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) { - let side = if edit.front { &sign.front } else { &sign.back }; - self.send(S::SignUpdate(play::SignUpdate { - pos: [edit.pos.0, edit.pos.1, edit.pos.2], - lines: side.lines.clone(), - front: edit.front, - })); - } + self.send(S::SignUpdate(play::SignUpdate { + pos: [edit.pos.0, edit.pos.1, edit.pos.2], + lines: edit.lines, + front: edit.front, + })); } else { self.mark_block_entity_updated(edit.pos); } @@ -206,7 +366,8 @@ impl Game<'_> { edit.edit.set_value(&text); } } - /// The box's text onto the sign, when it still fits the line. + /// The box's text onto the editor's lines and the sign + /// (`AbstractSignEditScreen.setMessage`), when it still fits the line. fn sign_write(&mut self) { let Some(edit) = self.sign_edit.as_ref() else { return; @@ -215,6 +376,9 @@ impl Game<'_> { if !self.sign_fits(&value) { return; } + if let Some(edit) = self.sign_edit.as_mut() { + edit.lines[line].clone_from(&value); + } let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&pos) else { return; }; diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index 538cb39e7..a3761cf7a 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -253,12 +253,21 @@ impl Game<'_> { self.world.modified.insert((key.0 >> 4, key.2 >> 4)); } /// `LivingEntity.makePoofParticles` (entity event 20) for a mob. - fn mob_poof(&mut self, id: u32) { + pub(super) fn mob_poof(&mut self, id: u32) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + let at = m.position; + self.lan_entity_event(id as i32, 20, [at.x, at.y, at.z]); + self.poof_particles(id); + } + /// `Mob.handleEntityEvent` 20 (`spawnAnim` on a client): the poof about + /// mob `id`. + pub(super) fn poof_particles(&mut self, id: u32) { let Some(m) = self.mobs.iter().find(|m| m.id == id) else { return; }; let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height())); - self.lan_entity_event(id as i32, 20, [at.x, at.y, at.z]); let options = ParticleOptions::simple(ParticleType::Poof); for _ in 0..20 { let r = self.particles.level_random(); diff --git a/crates/horizon-client/src/game/spill.rs b/crates/horizon-client/src/game/spill.rs index b1953596b..d8f15daa1 100644 --- a/crates/horizon-client/src/game/spill.rs +++ b/crates/horizon-client/src/game/spill.rs @@ -5,9 +5,11 @@ //! world as soon as the behaviour returns, within the same tick. use super::{Game, GameLevel, Screen, dispenser::new_item_motion, storage::is_shulker_box}; use horizon_client::{ + block_entity_item, block_entity_nbt, containers::{Banner, BlockEntity}, item_data, items::ItemStack, + save, }; use horizon_core::position::BlockPos; use horizon_core::random::RandomSource; @@ -16,7 +18,7 @@ use horizon_world::{ LevelEvent, removal::{self, PreRemove}, }, - nbt::{JavaString, Tag}, + nbt::{Compound, JavaString, Tag}, registry::BlockStateId, }; use std::collections::HashMap; @@ -32,6 +34,9 @@ pub(super) struct Pending { pub(super) names: HashMap<[i32; 3], (String, String)>, /// A decorated pot's sherds (back, left, right, front). pub(super) pot: HashMap<[i32; 3], [Option; 4]>, + /// A head's profile, note block sound and name, or a hive's bees: the + /// dropped item and the component patch it takes. + pub(super) copied: HashMap<[i32; 3], (String, Compound)>, } impl Pending { /// Remember what the block entity at `pos` copies into the drops of `block`. @@ -49,6 +54,31 @@ impl Pending { if let Some(name) = name { self.names.insert(pos, (block.to_owned(), name)); } + // `copy_components` from the block entity: the head tables copy the + // profile (player heads), note block sound and name, the hive tables + // the bees. + let include: &[&str] = match entity { + BlockEntity::Skull(_) if block.starts_with("minecraft:player_") => &[ + "minecraft:profile", + "minecraft:note_block_sound", + "minecraft:custom_name", + ], + BlockEntity::Skull(_) => &["minecraft:custom_name"], + BlockEntity::Beehive(_) => &["minecraft:bees"], + _ => &[], + }; + if !include.is_empty() { + let saved = save::encode_block_entity((pos[0], pos[1], pos[2]), entity, block); + let mut patch = block_entity_nbt::canonical(&saved) + .map(|saved| block_entity_item::pick(&saved)) + .unwrap_or_default(); + patch.retain(|k, _| include.contains(&k.to_string_lossy().as_str())); + if !patch.is_empty() { + // `Blocks.wallVariant`: a wall head drops the standing item. + let item = block.replacen("_wall_", "_", 1); + self.copied.insert(pos, (item, patch)); + } + } if is_shulker_box(block) && let BlockEntity::Chest(items) = entity { @@ -76,6 +106,19 @@ impl Pending { { stack.data_mut().custom_name = Some(name); } + if self + .copied + .get(&pos) + .is_some_and(|(item, _)| **item == *stack.item) + && let Some((_, copied)) = self.copied.remove(&pos) + { + let mut patch = match item_data::encode_components(stack) { + Some(Tag::Compound(c)) => c, + _ => Default::default(), + }; + patch.extend(copied); + (stack.damage, stack.extra) = item_data::decode_components(Some(&Tag::Compound(patch))); + } if &*stack.item == "minecraft:decorated_pot" { // The pot's block entity always copies its decorations, empty or not. let sides = self.pot.remove(&pos).unwrap_or_default(); @@ -155,6 +198,7 @@ impl Pending { self.shulker.remove(&pos); self.banner.remove(&pos); self.names.remove(&pos); + self.copied.remove(&pos); } } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 361879d2e..1734cb3ee 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -779,6 +779,7 @@ impl Game<'_> { return; }; let pos = s.pos; + let enchanted_item = enchanted.clone(); // Player.onEnchantmentPerformed self.give_levels(-(lapis_needed as i32)); self.level.xp_seed = self.world.random.next_int(); @@ -795,6 +796,7 @@ impl Game<'_> { } let pitch = self.world.random.next_float() * 0.1 + 0.9; self.stats.custom("enchant_item", 1); + self.trigger_enchanted_item(&enchanted_item, lapis_needed as i32); self.play_at("minecraft:block.enchantment_table.use", pos, 1.0, pitch); self.station_changed(); } @@ -1768,6 +1770,11 @@ impl Game<'_> { }; let gray = rgba(170, 170, 170, 255); let item_info = self.res.items().get(&stack.item); + // SmithingTemplateItem.appendHoverText: `Item.appendHoverText` comes + // before the components. + for (text, c) in horizon_client::item_tooltip::smithing_template_lines(stack, &translate) { + push(&mut lines, text, c); + } // InstrumentComponent.addToTooltip. if let Some(text) = horizon_client::item_tooltip::instrument_line(stack, &display, &translate) @@ -2023,15 +2030,19 @@ impl Game<'_> { && stack.damage > 0 && advanced { - push( - &mut lines, - format!( - "Durability: {} / {}", - info.max_damage - stack.damage, - info.max_damage + // `item.durability`, in the selected language. + lines.push(( + horizon_client::text::Text::translate( + "item.durability", + &[ + horizon_client::text::Text::literal( + (info.max_damage - stack.damage).to_string(), + ), + horizon_client::text::Text::literal(info.max_damage.to_string()), + ], ), u32::MAX, - ); + )); } // ItemStack.addDetailsToTooltipTail: with advanced tooltips the item id // and how many components the stack has. diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index 7f64c6bb2..94814320c 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -256,9 +256,8 @@ impl Game<'_> { .fluid == horizon_client::blocks::Fluid::Water; let on_ground = p.ground.on_ground; - let (sprinting, flying, gliding, swimming) = ( + let (sprinting, gliding, swimming) = ( p.sprinting, - p.flying, p.fall_flying, p.pose == horizon_client::pose::Pose::Swimming, ); @@ -272,15 +271,27 @@ impl Game<'_> { }); let s = &mut self.stats; match riding { - Some(Ok(horizon_client::mobs::Species::Pig)) => s.custom("pig_one_cm", total), - Some(Ok(horizon_client::mobs::Species::Strider)) => s.custom("strider_one_cm", total), - Some(Ok(sp)) if horizon_client::mobs::equine::is_equine(sp) => { - s.custom("horse_one_cm", horizontal) + Some(Ok(sp)) => { + use horizon_client::mobs::Species; + // `checkRidingStatistics`: only these mounts count, the horse + // family by the full 3D distance; any other mount nothing. + match sp { + Species::Pig => s.custom("pig_one_cm", total), + Species::Strider => s.custom("strider_one_cm", total), + Species::HappyGhast => s.custom("happy_ghast_one_cm", total), + Species::Nautilus | Species::ZombieNautilus => { + s.custom("nautilus_one_cm", total) + } + sp if horizon_client::mobs::equine::is_equine(sp) => { + s.custom("horse_one_cm", total) + } + _ => {} + } } - Some(_) => { + Some(Err(())) => { if self.boats.iter().any(|b| Some(b.id) == self.riding) { s.custom("boat_one_cm", total) - } else { + } else if self.carts.iter().any(|c| Some(c.id) == self.riding) { s.custom("minecart_one_cm", total) } } @@ -300,8 +311,9 @@ impl Game<'_> { } } None if gliding => s.custom("aviate_one_cm", total), - None if flying => s.custom("fly_one_cm", horizontal), - None if d.y < 0.0 => s.custom("fall_one_cm", (-d.y * 100.0).round() as i32), + // Airborne and not gliding: more than 25 cm sideways per move + // (creative flight, or a long jump), not only flying. + None if horizontal > 25 => s.custom("fly_one_cm", horizontal), None => {} } } @@ -366,9 +378,10 @@ impl Game<'_> { if pos[1] < 63 || !self.can_see_sky(pos) { return; } - // DifficultyInstance.isHarderThan(random * 3) at normal difficulty. + // `getCurrentDifficultyAt(playerPos).isHarderThan(random * 3)`. + let difficulty = self.local_difficulty([position.x, position.y, position.z]); let r = &mut self.world.random; - if r.next_float() * 3.0 >= 2.0 { + if difficulty.effective <= r.next_float() * 3.0 { return; } if r.next_int_bound(since_rest.max(1)).unwrap_or(0) < 72000 { diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index e5cb0ab26..81895dba3 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -3,6 +3,7 @@ //! player's `PlayerEnderChestContainer`, saved as `EnderItems`). use super::Game; use horizon_client::{containers::BlockEntity, items::ItemStack, text::Text}; +use horizon_core::random::RandomSource; pub(super) fn is_shulker_box(name: &str) -> bool { name.ends_with("shulker_box") @@ -156,6 +157,79 @@ impl Game<'_> { ); paired.then_some((other, kind == "right")) } + /// The open or close sound of a container block (`ChestBlockEntity.playSound`, + /// `BarrelBlockEntity.playSound`, `ShulkerBoxBlockEntity.startOpen`): volume + /// 0.5 and pitch 0.9 to 1.0. A double chest sounds once from the middle of + /// both halves, a barrel from the face it opens on. + pub(super) fn container_sound(&mut self, sound: &str, key: (i32, i32, i32), name: &str) { + let mut at = [ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]; + if let Some((other, _)) = self.chest_partner(key) { + at[0] = f64::from(key.0 + other.0) / 2.0 + 0.5; + at[2] = f64::from(key.2 + other.2) / 2.0 + 0.5; + } else if name == "minecraft:barrel" + && let Some(state) = self + .pack + .assets + .registry + .state(self.world.block(key.0, key.1, key.2)) + && let Some(facing) = state.properties.get("facing") + { + let (dx, dy, dz) = match facing.as_str() { + "up" => (0.0, 0.5, 0.0), + "down" => (0.0, -0.5, 0.0), + f => { + let (x, z) = facing_step(f); + (f64::from(x) / 2.0, 0.0, f64::from(z) / 2.0) + } + }; + at = [at[0] + dx, at[1] + dy, at[2] + dz]; + } + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play(sound, Some(at), 0.5, pitch); + } + /// The open or close sound of the container block at `key`, if it has one. + /// Callers play it only when the opener count crosses zero + /// (`ContainerOpenersCounter.onOpen` / `onClose`). + pub(super) fn container_edge_sound(&mut self, key: (i32, i32, i32), open: bool) { + let name = self + .res + .facts() + .get(self.world.block(key.0, key.1, key.2)) + .name + .clone(); + let sound = if is_shulker_box(&name) { + if open { + "minecraft:block.shulker_box.open" + } else { + "minecraft:block.shulker_box.close" + } + } else if &*name == "minecraft:ender_chest" { + if open { + "minecraft:block.ender_chest.open" + } else { + "minecraft:block.ender_chest.close" + } + } else if name.contains("chest") { + if open { + "minecraft:block.chest.open" + } else { + "minecraft:block.chest.close" + } + } else if &*name == "minecraft:barrel" { + if open { + "minecraft:block.barrel.open" + } else { + "minecraft:block.barrel.close" + } + } else { + return; + }; + self.container_sound(sound, key, &name); + } /// The other half of a double chest at `key`, for neighbour updates. pub(super) fn chest_other_half(&self, key: (i32, i32, i32)) -> Option<(i32, i32, i32)> { self.chest_partner(key).map(|p| p.0) diff --git a/crates/horizon-client/src/game/text_displays.rs b/crates/horizon-client/src/game/text_displays.rs index 587db3382..6812be7bf 100644 --- a/crates/horizon-client/src/game/text_displays.rs +++ b/crates/horizon-client/src/game/text_displays.rs @@ -269,6 +269,8 @@ impl Game<'_> { light, layer: if through { 2 } else { 0 }, normal: [0; 4], + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index 9bb000314..217702e51 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -12,12 +12,14 @@ use horizon_client::{ impl Game<'_> { /// `Hud.extractOverlayMessage` and `extractTitle`. - pub(super) fn draw_titles(&self, batch: &mut HudBatch) { + pub(super) fn draw_titles(&self, batch: &mut HudBatch, bar_height: i32) { let (w, h) = (batch.width as i32, batch.height as i32); let partial = self.clock.fraction() as f32; let background = self.settings.text_background(0.0); let font = &self.gui.atlas.font; - let mut draws = self.titles.overlay_message(w, h, partial, font, background); + let mut draws = self + .titles + .overlay_message(w, h, bar_height, partial, font, background); draws.extend(self.titles.title(w, h, partial, font, background)); hud_layout::paint(batch, &self.gui.atlas, &draws); } @@ -60,6 +62,7 @@ impl Game<'_> { /// The title, action bar and selected-item parts of `Hud.tick`. pub(super) fn tick_hud(&mut self) { self.titles.tick(); + self.tick_in_bed_chat(); // `MinecraftServer.isCurrentlySaving` of single player's server. let saving = self .integrated @@ -71,10 +74,11 @@ impl Game<'_> { .tick(held, f64::from(self.settings.notification_display_time)); } /// `Hud.extractSelectedItemName`. - pub(super) fn draw_selected_name(&self, batch: &mut HudBatch, can_hurt: bool) { + pub(super) fn draw_selected_name(&self, batch: &mut HudBatch, bar_height: i32, can_hurt: bool) { let draws = self.tool_highlight.draw( batch.width as i32, batch.height as i32, + bar_height, can_hurt, &self.gui.atlas.font, self.settings.text_background(0.0), diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 177e3bf80..beaac42cc 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -178,7 +178,9 @@ impl Game<'_> { ]; self.tnts.remove(i); count -= 1; - self.server_explode(center, 4.0, BlockInteraction::Destroy, false)?; + self.with_hive_emptying_blast(|g| { + g.server_explode(center, 4.0, BlockInteraction::Destroy, false) + })?; } else { i += 1; } @@ -332,6 +334,8 @@ impl Game<'_> { layer: if lit { 5 } else { 0 }, color, light: packed, + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 6986d8baa..0f8723737 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -245,7 +245,7 @@ impl Game<'_> { self.handle_mob_events(events)?; return Ok(true); } - self.stats.custom("talk_to_villager", 1); + self.stats.custom("talked_to_villager", 1); self.ensure_offers(index); let m = &self.mobs[index]; let trade = m.extra.trade.as_deref().cloned().unwrap_or_default(); @@ -398,18 +398,21 @@ impl Game<'_> { .as_ref() .and_then(|s| s.merchant.as_ref()) .and_then(|m| m.mob); - let session = self.merchant_apply(session, mob); + let (session, traded) = self.merchant_apply(session, mob); + self.merchant_traded(mob, &traded); if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) { m.session = session; } } - /// What a menu click's session did, applied to the world and its mob. + /// What a menu click's session did, applied to the world and its mob; + /// with the result of each trade made, for `merchant_traded`. pub(super) fn merchant_apply( &mut self, session: Box, mob: Option, - ) -> Box { + ) -> (Box, Vec) { let mut session = session; + let mut traded = Vec::new(); let events = std::mem::take(&mut session.events); let (villager, origin) = (session.villager, session.origin); if let Some(m) = mob.and_then(|id| self.mobs.iter_mut().find(|m| m.id == id)) { @@ -438,11 +441,26 @@ impl Game<'_> { }; self.audio.play(sound, Some(origin), 1.0, pitch); } - merchant::Event::Traded(_) => self.stats.custom("traded_with_villager", 1), + merchant::Event::Traded(index) => { + traded.extend(session.offers.get(index).map(|o| o.result.clone())); + } merchant::Event::TradeSound => {} } } - session + (session, traded) + } + /// `MerchantResultSlot.checkTakeAchievements` and `AbstractVillager.notifyTrade` + /// for each trade made: the statistic and the `villager_trade` trigger. + pub(super) fn merchant_traded(&mut self, mob: Option, results: &[ItemStack]) { + for result in results { + self.stats.custom("traded_with_villager", 1); + let villager = mob + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|m| self.mob_entity(m)); + if let Some(villager) = villager { + self.trigger_trade(&villager, result); + } + } } /// `Villager.customServerAiStep`: the TRADE reputation event of the last /// trade, a tick later; the prices follow the new reputation. diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 0ab873f40..dcddb9f15 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -6,6 +6,7 @@ use super::{Game, view_vector}; use horizon_client::{ collisions::SceneCollisions, + enchant::EffectContext, items::ItemStack, mesher::Vertex, mobs::{Damage, DamageKind, Who, anim::Poses}, @@ -32,6 +33,8 @@ pub(super) struct ThrownTrident { pub(super) no_physics: bool, returning: u32, creative_only: bool, + /// The guest that threw it (`Projectile.getOwner`); `None` for the host. + guest: Option, } impl ThrownTrident { /// A trident a server sent (`handleAddEntity`): placed and moved by it. @@ -51,6 +54,7 @@ impl ThrownTrident { no_physics: false, returning: 0, creative_only: false, + guest: None, } } /// One tick of a server's client: the previous position, then `step`. @@ -258,8 +262,24 @@ impl Game<'_> { // Player.startAutoSpinAttack(20, 8, stack). p.auto_spin_attack_ticks = 20; p.auto_spin_attack_dmg = 8.0; - if p.ground.on_ground { - p.position.y += 1.2; + } + // `player.move(SELF, (0, 1.1999999, 0))` when on the ground: the lift + // stops at a ceiling. + let lift = self + .player + .as_ref() + .filter(|p| p.ground.on_ground) + .map(|p| p.bounds()); + if let Some(bounds) = lift { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + let up = Vec3::new(0.0, f64::from(1.1999999f32), 0.0); + let moved = scene.resolve(bounds, up, 0.0, true).unwrap_or(Vec3::ZERO); + if let Some(p) = self.player.as_mut() { + p.position.y += moved.y; } } if !server_client { @@ -313,11 +333,33 @@ impl Game<'_> { no_physics: false, returning: 0, creative_only: self.creative, + guest: self.lan_acting, }); self.player_projectile_shot(); self.audio .play("minecraft:item.trident.throw", at, 1.0, 1.0); } + /// The thrower's `PLAYER_HURT_ENTITY` for a trident hit: run as the + /// guest that threw it, and not at all once they have left. + fn thrower_hit( + &mut self, + guest: Option, + victim: &horizon_client::advancements::EntityView, + direct: horizon_client::advancements::EntityView, + damage: f32, + ) { + let Some(conn) = guest.filter(|c| self.lan_acting != Some(*c)) else { + self.player_hit(victim, "minecraft:trident", Some(direct), damage); + return; + }; + let Some(mut host) = self.lan.take() else { + return; + }; + self.as_guest(&mut host, conn, |g| { + g.player_hit(victim, "minecraft:trident", Some(direct), damage) + }); + self.lan = Some(host); + } pub(super) fn tick_tridents(&mut self) { let Some(eye) = self.eye_position() else { return; @@ -378,11 +420,29 @@ impl Game<'_> { } } if let Some((id, _)) = hit_mob { - let impaling = t.stack.enchantment_level("minecraft:impaling") as f32; - let aquatic = self.mobs.iter().find(|m| m.id == id).is_some_and(|m| { - m.kind.flags.aquatic_swimmer || m.kind.flags.breathes_water - }); - let damage = 8.0 + if aquatic { 2.5 * impaling } else { 0.0 }; + // ThrownTrident.getDamage: `EnchantmentHelper.modifyDamage` on 8 + // (impaling hits `#sensitive_to_impaling`, the aquatic tag). + let victim = self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| m.kind.id.clone()); + let ctx = EffectContext { + this: victim.as_deref(), + attacker: Some("minecraft:player"), + direct_attacker: Some("minecraft:trident"), + is_direct: true, + damage_type: Some("minecraft:trident"), + items: Some(self.res.items()), + ..Default::default() + }; + let damage = self.res.stations().enchantments.modify_value( + Some(&t.stack), + "minecraft:damage", + &ctx, + &mut self.world.random, + 8.0, + ); t.dealt_damage = true; let mut hurt_at = None; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { @@ -405,6 +465,18 @@ impl Game<'_> { { self.channel_lightning(at); } + if hurt_at.is_some() + && let Some(m) = self.mobs.iter().find(|m| m.id == id) + { + // LivingEntity.hurtServer: PLAYER_HURT_ENTITY. + let victim = self.mob_entity(m); + let direct = horizon_client::advancements::EntityView { + kind: "minecraft:trident".into(), + position: [t.position.x, t.position.y, t.position.z], + ..Default::default() + }; + self.thrower_hit(t.guest, &victim, direct, damage); + } self.audio.play( "minecraft:item.trident.hit", Some([t.position.x, t.position.y, t.position.z]), diff --git a/crates/horizon-client/src/game/vault.rs b/crates/horizon-client/src/game/vault.rs index f3edfddb3..18430daf6 100644 --- a/crates/horizon-client/src/game/vault.rs +++ b/crates/horizon-client/src/game/vault.rs @@ -169,6 +169,8 @@ impl Game<'_> { self.consume_held(); } } + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, &stack); Ok(true) } fn vault_events(&mut self, key: Pos, events: Vec) -> Result<()> { diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index c04b18604..36c79f893 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -148,7 +148,7 @@ impl Game<'_> { // VillagerMakeLove: entity event 13 for the partner, then the parent. for i in [ib, ia] { let id = self.mobs[i].id; - self.villager_particles(id, "angry_villager"); + self.mob_event_particles(id, 13); } return; }; @@ -173,12 +173,31 @@ impl Game<'_> { child.extra.bed = Some(bed); } // VillagerMakeLove.giveBirth: entity event 12 for the child. - self.villager_particles(id, "heart"); + self.mob_event_particles(id, 12); } - /// `Villager.handleEntityEvent` 12, 13, 14 and 42: - /// `AbstractVillager.addParticlesAroundSelf`. - pub(super) fn villager_particles(&mut self, id: u32, kind: &'static str) { - self.particles_around_mob(id, kind, horizon_client::particles::Burst::VILLAGER); + /// `Level.broadcastEntityEvent` of an event whose `handleEntityEvent` + /// draws particles about the mob (villager 12, 13 and 14, taming 6 and 7, + /// love 18): the guests get the byte, and this game draws it as its own + /// client would. + pub(super) fn mob_event_particles(&mut self, id: u32, event: i8) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + let at = [m.position.x, m.position.y, m.position.z]; + self.lan_entity_event(id as i32, event, at); + self.entity_event_particles(id, event); + } + /// `handleEntityEvent(event)`'s particles about mob `id` + /// (`Villager`, `TamableAnimal`, `AbstractHorse`, `Animal`, `Allay`). + pub(super) fn entity_event_particles(&mut self, id: u32, event: i8) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + if let Some((kind, burst)) = + horizon_client::particles::entity_event_burst(&m.kind.id, event as u8) + { + self.particles_around_mob(id, kind, burst); + } } /// `particles::around_self` about mob `id`. pub(super) fn particles_around_mob( @@ -315,7 +334,7 @@ impl Game<'_> { } // Villager.setLastHurtByMob: entity event 13. for id in angry { - self.villager_particles(id, "angry_villager"); + self.mob_event_particles(id, 13); } } /// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a @@ -370,7 +389,7 @@ impl Game<'_> { gossip::REPUTATION_CHANGE_PER_TRADE, ); // Villager.customServerAiStep after a trade: entity event 14. - self.villager_particles(id, "happy_villager"); + self.mob_event_particles(id, 14); } /// `Villager.getPlayerReputation` of the local player. pub(super) fn villager_reputation(&self, id: u32) -> i32 { diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 63ac2641d..b00cea116 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -470,6 +470,7 @@ impl Game<'_> { } /// The bursts guests' turns put off. pub(super) fn flush_wind_bursts(&mut self) -> Result<()> { + self.flush_smash_pushes(); for b in std::mem::take(&mut self.creatures.wind_bursts) { self.wind_burst(b.center, b.radius, b.multiplier, b.breeze, b.wind_charge)?; } diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index 8084425ca..5f01633b0 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -2,11 +2,53 @@ //! its boss bar, and its skulls hitting and exploding. use super::Game; use horizon_client::{ + items::ItemStack, mobs::{Damage, DamageKind, Species, Who}, projectiles::{Projectile, ProjectileKind}, }; +use horizon_core::position::BlockPos; impl Game<'_> { + /// `LivingEntity.createWitherRose`: a mob a wither killed leaves a wither + /// rose where it stood (with mobGriefing, on air that can hold it), else + /// drops one. + pub(super) fn create_wither_rose(&mut self, m: &horizon_client::mobs::Mob) { + // getKillCredit: the player who last hurt it, else the last mob (kept + // for 100 ticks). + let by_wither = m.ai.last_hurt_by_player <= 0 + && m.age as i32 - m.ai.last_hurt_by_time <= 100 + && matches!(m.ai.last_hurt_by, Some(Who::Mob(id)) + if self.mobs.iter().any(|o| o.id == id && o.alive() && o.species() == Species::Wither)); + if !by_wither { + return; + } + let pos = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + let registry = self.pack.assets.registry; + let rose = registry.default_state("minecraft:wither_rose"); + if self.ui.rules.bool("mob_griefing") + && let Some(rose) = rose + && self + .res + .facts() + .is_air(self.world.block(pos[0], pos[1], pos[2])) + && self.with_level(|b, level, ticks| { + b.can_survive(level, ticks, BlockPos::new(pos[0], pos[1], pos[2]), rose) + }) + { + let _ = self.level_set(pos, rose); + return; + } + self.spawn_item( + ItemStack::new("minecraft:wither_rose", 1), + [m.position.x, m.position.y, m.position.z], + super::dispenser::new_item_motion(), + 0, + ); + } fn is_wither_skull(&self, p: [i32; 3]) -> bool { let name = &*self .res @@ -130,7 +172,10 @@ impl Game<'_> { if let Some(id) = owner { self.note_attacker("minecraft:explosion", id); } - self.explode(at, 1.0) + self.combat.explosion_owner = owner; + let result = self.with_hive_emptying_blast(|g| g.explode(at, 1.0)); + self.combat.explosion_owner = None; + result } } /// Wither skulls drawn as the skull model, blue when dangerous. diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index 454f9f2eb..d7c4f2b03 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -93,7 +93,12 @@ impl WorldRequest { level.hardcore = o.hardcore; level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into(); level.allow_commands = Some(o.commands(creative)); - horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; + horizon_client::save::write_world_gen_settings_with( + &save_root, + level.seed, + o.world_gen(), + o.flat_settings(), + )?; // WorldCreationUiState.getGameRules, written with the level. level.game_rules = o.rules.by_name(); } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index a98637b5a..801dedde9 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -35,10 +35,11 @@ fn entity_shader() -> String { #[cfg(test)] mod crumbling_tests; mod entity_batch; +mod entity_outline; mod weather; use entity_batch::EntityBatch; pub use entity_batch::{ - SHADOW_OVERLAY, TRANSLUCENT_GLINT_ITEM_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, + ENERGY_SWIRL_OVERLAY, SHADOW_OVERLAY, TRANSLUCENT_GLINT_ITEM_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY, }; @@ -175,12 +176,13 @@ struct Globals { inverse_view: [[f32; 4]; 4], sunrise: [f32; 4], sun: [f32; 4], - /// x: sky fog end, y: cloud fog end, z: dark disc (camera below the horizon), w: unused. + /// x: sky fog end, y: cloud fog end, z: dark disc (camera below the horizon), + /// w: the glint strength (`GlintAlpha`). fog_ends: [f32; 4], /// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: [[f32; 4]; 2], /// x: vanilla's `GameTime` uniform; y: nether cardinal lighting; z: how many - /// `dynamic_lights` are set; w unused. + /// `dynamic_lights` are set; w: the glint scroll clock (`Glint::scroll_ticks`). time: [f32; 4], /// Atlas rect of a destroy stage (entity.wgsl takes only its size: every stage's is the same, /// and each crack carries its own stage's origin). @@ -261,10 +263,19 @@ pub struct Frame<'a> { /// drawn after the hand at its projection, without the bob or fog. pub debug_crosshair: &'a [[f32; 8]], pub hud: &'a HudBatch, + /// `GlintAlpha` (accessibility Glint Strength); the entity shader uses it + /// for held/world items, independent of what the HUD batch last drew. + pub glint_alpha: f32, + /// The glint scroll clock (`Glint::scroll_ticks`): entity.wgsl's + /// `ARMOR_ENTITY_GLINT_TEXTURING` phase. + pub glint_ticks: f32, /// CardinalLighting.Type.NETHER, otherwise DEFAULT. pub nether_lighting: bool, /// Camera-relative entity geometry textured from the shared atlas. pub entities: &'a [Vertex], + /// The glowing entities' silhouettes in their team colours (`OutlineBufferSource`), + /// outlined through walls after the hand. + pub glowing: &'a [Vertex], /// Runs of `entities` by entity, while a shader pack draws them (`pack_draw::EntitySpan`). pub entity_spans: &'a [pack_draw::EntitySpan], pub weather: &'a [crate::weather::Vertex], @@ -407,6 +418,8 @@ pub struct Renderer { cloud_uniform: wgpu::Buffer, cloud_group: wgpu::BindGroup, additive_pipeline: wgpu::RenderPipeline, + /// `RenderPipelines.ENERGY_SWIRL`: additive, unlit, the sprite repeated within itself. + energy_swirl_pipeline: wgpu::RenderPipeline, lightning_pipeline: wgpu::RenderPipeline, lightning: lightning::Renderer, see_through_pipeline: wgpu::RenderPipeline, @@ -414,6 +427,8 @@ pub struct Renderer { celestial_buffer: wgpu::Buffer, end_sky: end_sky::EndSky, stars: stars::Stars, + /// The glowing entities' outline (`LevelRenderer.entityOutlineTarget`). + entity_outline: entity_outline::EntityOutline, panorama: panorama::Panorama, /// `RenderPipelines.WORLD_BORDER` and its buffers. border_pipeline: wgpu::RenderPipeline, @@ -1026,6 +1041,8 @@ impl Renderer { sprite_mips: &[crate::mipmap::Settings], animations: &[SpriteAnimation], hud_atlas: (&[u8], u32, u32), + glint: (&[u8], u32, u32), + glint_armor: (&[u8], u32, u32), forcefield: (&[u8], u32), panorama_faces: &panorama::Faces, prepared: Option, @@ -1585,7 +1602,68 @@ impl Renderer { atlas_pixels, ); let atlas_view = atlas.create_view(&Default::default()); - let mut hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?; + // vanilla's `GlintSampler`: enchanted_glint_item as its own texture, + // repeated per pixel (`clamp: false`), linear without mipmaps + // (`blur: true`). + let (glint_pixels, glint_width, glint_height) = glint; + let glint_texture = device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: Some("Enchanted glint"), + size: wgpu::Extent3d { + width: glint_width, + height: glint_height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + glint_pixels, + ); + let glint_view = glint_texture.create_view(&Default::default()); + let glint_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Glint"), + address_mode_u: wgpu::AddressMode::Repeat, + address_mode_v: wgpu::AddressMode::Repeat, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + // ARMOR_ENTITY_GLINT_TEXTURING's sampler is vanilla's GlintSampler: the + // same repeat and linear filtering as the item glint. + let (glint_armor_pixels, glint_armor_width, glint_armor_height) = glint_armor; + let glint_armor_texture = device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: Some("Enchanted armor glint"), + size: wgpu::Extent3d { + width: glint_armor_width, + height: glint_armor_height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + glint_armor_pixels, + ); + let glint_armor_view = glint_armor_texture.create_view(&Default::default()); + let mut hud = HudRenderer::new( + &device, + config.format.remove_srgb_suffix(), + &atlas_view, + &glint_view, + &glint_sampler, + )?; hud.atlas_texture = Some(atlas.clone()); let entity_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Horizon entities"), @@ -1631,6 +1709,29 @@ impl Renderer { vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), ), + entry( + 5, + vf, + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + ), + entry( + 6, + vf, + wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + ), + entry( + 7, + vf, + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + ), ], }); let weather = weather::Weather::new( @@ -1667,6 +1768,18 @@ impl Renderer { binding: 4, resource: wgpu::BindingResource::Sampler(&lightmap_sampler), }, + wgpu::BindGroupEntry { + binding: 5, + resource: wgpu::BindingResource::TextureView(&glint_view), + }, + wgpu::BindGroupEntry { + binding: 6, + resource: wgpu::BindingResource::Sampler(&glint_sampler), + }, + wgpu::BindGroupEntry { + binding: 7, + resource: wgpu::BindingResource::TextureView(&glint_armor_view), + }, ], }); let hand_group = device.create_bind_group(&wgpu::BindGroupDescriptor { @@ -1693,6 +1806,18 @@ impl Renderer { binding: 4, resource: wgpu::BindingResource::Sampler(&lightmap_sampler), }, + wgpu::BindGroupEntry { + binding: 5, + resource: wgpu::BindingResource::TextureView(&glint_view), + }, + wgpu::BindGroupEntry { + binding: 6, + resource: wgpu::BindingResource::Sampler(&glint_sampler), + }, + wgpu::BindGroupEntry { + binding: 7, + resource: wgpu::BindingResource::TextureView(&glint_armor_view), + }, ], }); let entity_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -1737,7 +1862,7 @@ impl Renderer { usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - let entity_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4]; + let entity_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4,6=>Float32x2]; let entity_vertex = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, @@ -1893,7 +2018,29 @@ impl Renderer { alpha_blend, false, ); - let lightning_attributes = wgpu::vertex_attr_array![6=>Float32x3]; + // RenderPipelines.ENERGY_SWIRL: BlendFunction.ADDITIVE (one, one), no culling; no depth + // writes either: vanilla sorts the quads far to near, so every face passes the test. + let one_one = wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }; + let energy_swirl_pipeline = entity_pipeline_with( + "Energy swirls", + None, + false, + wgpu::CompareFunction::GreaterEqual, + Default::default(), + wgpu::BlendState { + color: one_one, + alpha: one_one, + }, + false, + "fs_energy_swirl", + wgpu::ColorWrites::ALL, + ); + // Attribute 7: 6 is the entity vertex buffer's glint UV. + let lightning_attributes = wgpu::vertex_attr_array![7=>Float32x3]; let lightning_vertex = [ entity_vertex[0].clone(), Some(wgpu::VertexBufferLayout { @@ -2345,6 +2492,11 @@ impl Renderer { let uploads = upload::Uploads::new(&device); let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK); let stars = stars::Stars::new(&device, config.format.remove_srgb_suffix()); + let entity_outline = entity_outline::EntityOutline::new( + &device, + (&entity_shader, &entity_layout, &entity_vertex), + config.format.remove_srgb_suffix(), + ); let panorama = panorama::Panorama::new( &device, &queue, @@ -2410,6 +2562,7 @@ impl Renderer { cloud_uniform, cloud_group, additive_pipeline, + energy_swirl_pipeline, lightning_pipeline, lightning: lightning::Renderer::new(), see_through_pipeline, @@ -2417,6 +2570,7 @@ impl Renderer { celestial_buffer, end_sky: end_sky::EndSky::default(), stars, + entity_outline, panorama, border_pipeline, border_group, @@ -3518,7 +3672,7 @@ impl Renderer { frame.fog.map_or(frame.distance.min(512.0), |f| f.sky_end), frame.fog.map_or(2048.0, |f| f.cloud_end), if frame.dark_disc { 1.0 } else { 0.0 }, - 0.0, + frame.glint_alpha, ], end_portal_sprites: frame.end_portal_sprites, crumbling_sprite: frame.crumbling_sprite, @@ -3526,7 +3680,7 @@ impl Renderer { frame.shader_game_time, f32::from(frame.nether_lighting), frame.dynamic_lights.len().min(crate::dynamic_light::MAX) as f32, - 0.0, + frame.glint_ticks, ], outline_params: outline_params(self.config.width, self.config.height), dynamic_lights: { @@ -4041,6 +4195,7 @@ impl Renderer { crumbling_quads, translucent_crumbling_quads, water_mask_quads, + swirl_quads, shadow_quads, translucent_particle_quads, translucent_item_quads, @@ -4052,6 +4207,7 @@ impl Renderer { + crumbling_quads + translucent_crumbling_quads + water_mask_quads + + swirl_quads + shadow_quads + translucent_particle_quads + translucent_item_quads; @@ -4115,6 +4271,13 @@ impl Renderer { bytemuck::cast_slice(all_entities), ); } + self.entity_outline.prepare( + &self.device, + &mut self.uploads, + &mut encoder, + frame.glowing, + [self.config.width, self.config.height], + ); if let Some((rotation, brightness)) = frame.stars { self.stars.prepare( &mut self.uploads, @@ -4142,7 +4305,8 @@ impl Renderer { } else { lightning::QUADS }) - .max(weather_quads); + .max(weather_quads) + .max(frame.glowing.len() as u32 / 4); if max_quads > self.index_quads { self.index_quads = max_quads.next_power_of_two(); self.indices = Self::quad_indices(&self.device, self.index_quads); @@ -4633,6 +4797,21 @@ impl Renderer { self.lightning.draw(&mut pass, &frame.lightning); pass.set_bind_group(0, &self.group, &[]); } + if swirl_quads > 0 { + pass.set_pipeline(&self.energy_swirl_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed( + 0..swirl_quads * 6, + ((entity_quads + + crumbling_quads + + translucent_crumbling_quads + + water_mask_quads) + * 4) as i32, + 0..1, + ); + pass.set_bind_group(0, &self.group, &[]); + } if additive_quads > 0 { pass.set_pipeline(&self.additive_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); @@ -4884,6 +5063,13 @@ impl Renderer { 0..1, ); } + // GameRenderer.render: LevelRenderer.blitEntityOutline after the level and the hand. + self.entity_outline.draw( + &mut encoder, + &view_target, + &self.entity_group, + &self.indices, + ); if !frame.screen.is_empty() { let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, @@ -5298,6 +5484,7 @@ mod tests { color: 0xffff_ffff, light: id, normal: [0; 4], + glint_uv: [0.0, 0.0], }; 4] }; let entities: Vec<_> = [ @@ -5316,7 +5503,7 @@ mod tests { let mut batch = super::EntityBatch::default(); let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8)); let vertices = &batch.combined; - assert_eq!(counts, [4, 1, 1, 0, 1, 1, 0]); + assert_eq!(counts, [4, 1, 1, 0, 0, 1, 1, 0]); assert_eq!( vertices .as_chunks::<4>() diff --git a/crates/horizon-client/src/gfx/end_sky.rs b/crates/horizon-client/src/gfx/end_sky.rs index 15e9001fc..d74e053df 100644 --- a/crates/horizon-client/src/gfx/end_sky.rs +++ b/crates/horizon-client/src/gfx/end_sky.rs @@ -72,6 +72,8 @@ fn vertices(uv: [f32; 4]) -> Vec { layer: 2, color: 0xFF28_2828, light: 0, + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/gfx/end_sky/tests.rs b/crates/horizon-client/src/gfx/end_sky/tests.rs index 61266003d..5cd2bcf7f 100644 --- a/crates/horizon-client/src/gfx/end_sky/tests.rs +++ b/crates/horizon-client/src/gfx/end_sky/tests.rs @@ -12,15 +12,15 @@ fn geometry_matches_pre_residency_vertex_snapshots() { for (uv, expected) in [ ( [0.0, 0.0, 1.0, 1.0], - "f7ee23457fc557b33ecf09c9afaf858f3d8907e108abf06055f627523f733536", + "82a9be3f3ed1f733017df2c81dc6dff163f67bf739c768e3fd0f90f00c7802f6", ), ( [0.125, 0.25, 0.375, 0.5], - "f74c4b8d23ec2b7c11b5752821d0733851bf11358f1b26f9448226ff62a6a318", + "05a058bd8e70cff900c8e1c81061892ed27866d86498ebe1e8ae5af4c3b770ef", ), ( [0.13, 0.27, 0.41, 0.59], - "f0aaa39c5b22168bdc7c6c329acb4d3598a2feb61ff7b6f2850b644682749b39", + "93064b9fd2e745da46b927b2625edc8a381bb8c6e20b0f0880e816c4c1745ec1", ), ] { let mut mesh = vertices(uv); @@ -31,10 +31,8 @@ fn geometry_matches_pre_residency_vertex_snapshots() { if n == 0.0 { 0.0 } else { n } }); } - assert_eq!( - format!("{:x}", Sha256::digest(bytemuck::cast_slice(&mesh))), - expected - ); + let hash = format!("{:x}", Sha256::digest(bytemuck::cast_slice(&mesh))); + assert_eq!(hash, expected); } } @@ -95,7 +93,7 @@ fn separate_draws_match_combined_celestial_pixels() { label: Some("End sky differential shader"), source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()), }); - let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4]; + let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4,6=>Float32x2]; let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("End sky differential pipeline"), layout: None, @@ -305,6 +303,8 @@ fn separate_draws_match_combined_celestial_pixels() { color: level * 0x01010101, light: 0, normal: [0; 4], + + glint_uv: [0.0, 0.0], }) .to_vec() }; diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index 08d749b54..f71545f2c 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -3,13 +3,18 @@ use super::Vertex; /// Entity materials by a quad's overlay (`Vertex::layer`), in draw order: /// ordinary entities, breaking cracks (11), translucent breaking cracks (12), -/// the boat water mask (13, `RenderPipelines.WATER_MASK`), entity shadows -/// (14, `RenderPipelines.ENTITY_SHADOW`) and translucent-layer particles (15, -/// drawn after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`) +/// the boat water mask (13, `RenderPipelines.WATER_MASK`), energy swirls +/// (34, `RenderPipelines.ENERGY_SWIRL`), entity shadows (14, +/// `RenderPipelines.ENTITY_SHADOW`), translucent-layer particles (15, drawn +/// after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`) /// and translucent item quads (32, drawn without depth writes). -const MATERIALS: usize = 7; +const MATERIALS: usize = 8; /// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`). pub const WATER_MASK_OVERLAY: u32 = 13; +/// The overlay of energy swirl quads (`RenderTypes.energySwirl`: the charged creeper's and the +/// powered wither's armour). The light bytes carry the sprite's origin and the colour bytes its +/// size (`breaking::stage_light`), the UV the scrolled position in the sprite. +pub const ENERGY_SWIRL_OVERLAY: u32 = 34; /// The overlay of entity shadow quads (`RenderTypes.entityShadow`). pub const SHADOW_OVERLAY: u32 = 14; /// The overlay of translucent-layer particles (`SingleQuadParticle.Layer.translucent`). @@ -49,9 +54,10 @@ impl EntityBatch { 11 => 1, 12 => 2, WATER_MASK_OVERLAY => 3, - SHADOW_OVERLAY => 4, - TRANSLUCENT_PARTICLE_OVERLAY => 5, - TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 6, + ENERGY_SWIRL_OVERLAY => 4, + SHADOW_OVERLAY => 5, + TRANSLUCENT_PARTICLE_OVERLAY => 6, + TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 7, _ => 0, }; self.buckets[material][counts[material]] = index; @@ -103,12 +109,13 @@ mod tests { ) -> (Vec, [u32; MATERIALS]) { let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len()); let mut counts = [0; MATERIALS]; - for (i, layer) in [0, 11, 12, 13, 14, 15].into_iter().enumerate() { + for (i, layer) in [0, 11, 12, 13, 34, 14, 15].into_iter().enumerate() { for quad in entities.as_chunks::<4>().0 { let material = match quad[0].layer { 11 => 11, 12 => 12, 13 => 13, + 34 => 34, 14 => 14, 15 => 15, _ => 0, @@ -137,6 +144,8 @@ mod tests { color: index as u32, light: (index * 3) as u32, normal: [1, 2, 3, 4], + + glint_uv: [0.0, 0.0], }) .collect() } diff --git a/crates/horizon-client/src/gfx/entity_outline.rs b/crates/horizon-client/src/gfx/entity_outline.rs new file mode 100644 index 000000000..748622019 --- /dev/null +++ b/crates/horizon-client/src/gfx/entity_outline.rs @@ -0,0 +1,311 @@ +//! The entity outline (`LevelRenderer.entityOutlineTarget`): the glowing entities' +//! silhouettes in their team colours, drawn without depth so walls do not hide them +//! (`RenderTypes.outline`), the `entity_outline` post chain over them (`entity_sobel`, then +//! `entity_outline_box_blur` across and up), and `LevelRenderer.blitEntityOutline` onto +//! the frame after the hand. +use super::Vertex; + +/// `entityOutlineTarget`'s `GpuFormat.RGBA8_UNORM`. +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; + +struct Targets { + size: [u32; 2], + /// `entityOutlineTarget`. + outline: wgpu::TextureView, + /// The chain's `swap` target. + swap: wgpu::TextureView, + /// What each pass reads: the outline (nearest), swap (bilinear), the outline + /// (bilinear), swap (nearest). + groups: [wgpu::BindGroup; 4], +} + +pub(super) struct EntityOutline { + silhouette: wgpu::RenderPipeline, + /// Sobel, blur across, blur up (into `FORMAT`) and the blended blit (onto the frame). + passes: [wgpu::RenderPipeline; 4], + layout: wgpu::BindGroupLayout, + nearest: wgpu::Sampler, + bilinear: wgpu::Sampler, + vertices: wgpu::Buffer, + capacity: u64, + quads: u32, + targets: Option, +} + +impl EntityOutline { + /// `entity` draws the silhouettes with the entity shader's vertex stage and + /// `fs_outline`; `format` is the frame's. + pub(super) fn new( + device: &wgpu::Device, + entity: ( + &wgpu::ShaderModule, + &wgpu::PipelineLayout, + &[Option], + ), + format: wgpu::TextureFormat, + ) -> Self { + let (entity_shader, entity_layout, entity_vertex) = entity; + // RenderPipelines.OUTLINE_NO_CULL: no depth test, the colour replaced. + let silhouette = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Entity outline silhouettes"), + layout: Some(entity_layout), + vertex: wgpu::VertexState { + module: entity_shader, + entry_point: Some("vs_entity"), + compilation_options: Default::default(), + buffers: entity_vertex, + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: entity_shader, + entry_point: Some("fs_outline"), + compilation_options: Default::default(), + targets: &[Some(FORMAT.into())], + }), + multiview_mask: None, + cache: None, + }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Entity outline"), + source: wgpu::ShaderSource::Wgsl(include_str!("entity_outline.wgsl").into()), + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Entity outline bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Entity outline"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pass = |entry: &str, target: wgpu::ColorTargetState| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_quad"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(entry), + compilation_options: Default::default(), + targets: &[Some(target)], + }), + multiview_mask: None, + cache: None, + }) + }; + // BlendFunction.ENTITY_OUTLINE_BLIT over the colour only (write mask 7). + let blit = wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }), + write_mask: wgpu::ColorWrites::COLOR, + }; + let sampler = |label, filter| { + device.create_sampler(&wgpu::SamplerDescriptor { + label: Some(label), + mag_filter: filter, + min_filter: filter, + ..Default::default() + }) + }; + Self { + silhouette, + passes: [ + pass("fs_sobel", FORMAT.into()), + pass("fs_blur_x", FORMAT.into()), + pass("fs_blur_y", FORMAT.into()), + pass("fs_blit", blit), + ], + layout, + nearest: sampler("Entity outline nearest", wgpu::FilterMode::Nearest), + bilinear: sampler("Entity outline bilinear", wgpu::FilterMode::Linear), + vertices: Self::vertex_buffer(device, 256), + capacity: 256, + quads: 0, + targets: None, + } + } + + fn vertex_buffer(device: &wgpu::Device, capacity: u64) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Entity outline vertices"), + size: capacity * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) + } + + /// Uploads this frame's silhouettes (`LevelRenderer.currentFrameRendersEntityOutline` + /// when there are any) and sizes the targets like the window. + pub(super) fn prepare( + &mut self, + device: &wgpu::Device, + uploads: &mut super::upload::Uploads, + encoder: &mut wgpu::CommandEncoder, + silhouettes: &[Vertex], + size: [u32; 2], + ) { + self.quads = (silhouettes.len() / 4) as u32; + if self.quads == 0 { + return; + } + let vertices = silhouettes.len() as u64; + if vertices > self.capacity { + self.capacity = vertices.next_power_of_two(); + self.vertices = Self::vertex_buffer(device, self.capacity); + } + uploads.buffer( + encoder, + &self.vertices, + 0, + bytemuck::cast_slice(silhouettes), + ); + if self.targets.as_ref().is_some_and(|t| t.size == size) { + return; + } + let texture = |label| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + let outline = texture("Entity outline"); + let swap = texture("Entity outline swap"); + let group = |view: &wgpu::TextureView, sampler: &wgpu::Sampler| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Entity outline pass"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(sampler), + }, + ], + }) + }; + let groups = [ + group(&outline, &self.nearest), + group(&swap, &self.bilinear), + group(&outline, &self.bilinear), + group(&swap, &self.nearest), + ]; + self.targets = Some(Targets { + size, + outline, + swap, + groups, + }); + } + + /// `LevelRenderer.executeOutline`, the post chain and `blitEntityOutline` onto `frame`. + pub(super) fn draw( + &self, + encoder: &mut wgpu::CommandEncoder, + frame: &wgpu::TextureView, + entity_group: &wgpu::BindGroup, + indices: &wgpu::Buffer, + ) { + let Some(t) = self.targets.as_ref().filter(|_| self.quads > 0) else { + return; + }; + let clear = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT); + { + let mut pass = begin(encoder, "Entity outline", &t.outline, clear); + pass.set_pipeline(&self.silhouette); + pass.set_bind_group(0, entity_group, &[]); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(0, self.vertices.slice(..)); + pass.draw_indexed(0..self.quads * 6, 0, 0..1); + } + // post_effect/entity_outline.json; its last pass only copies swap back to the + // outline target, so the blit reads swap. + let steps = [ + ("Entity outline sobel", &t.swap, clear), + ("Entity outline blur across", &t.outline, clear), + ("Entity outline blur up", &t.swap, clear), + ("Entity outline blit", frame, wgpu::LoadOp::Load), + ]; + for (i, (label, view, load)) in steps.into_iter().enumerate() { + let mut pass = begin(encoder, label, view, load); + pass.set_pipeline(&self.passes[i]); + pass.set_bind_group(0, &t.groups[i], &[]); + pass.draw(0..3, 0..1); + } + } +} + +fn begin<'e>( + encoder: &'e mut wgpu::CommandEncoder, + label: &str, + view: &wgpu::TextureView, + load: wgpu::LoadOp, +) -> wgpu::RenderPass<'e> { + let attachments = [Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load, + store: wgpu::StoreOp::Store, + }, + })]; + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(label), + color_attachments: &attachments, + ..Default::default() + }) +} diff --git a/crates/horizon-client/src/gfx/entity_outline.wgsl b/crates/horizon-client/src/gfx/entity_outline.wgsl new file mode 100644 index 000000000..bd723f11e --- /dev/null +++ b/crates/horizon-client/src/gfx/entity_outline.wgsl @@ -0,0 +1,60 @@ +// The entity_outline post chain (post_effect/entity_outline.json) over the silhouettes of +// the glowing entities, then RenderTarget.blitAndBlendToTexture onto the frame. +@group(0) @binding(0) var source: texture_2d; +@group(0) @binding(1) var source_sampler: sampler; + +struct PostOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; + +// screenquad.vsh, with v running down the rows as wgpu's textures do. +@vertex fn vs_quad(@builtin(vertex_index) i: u32) -> PostOut { + let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + var out: PostOut; + out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0); + out.uv = vec2(p.x, 1.0 - p.y); + return out; +} + +fn tap(uv: vec2) -> vec4 { + return textureSampleLevel(source, source_sampler, uv, 0.0); +} + +// entity_sobel.fsh: alpha marks where coverage changes, the colour is the mean of the +// covered texels around. +@fragment fn fs_sobel(in: PostOut) -> @location(0) vec4 { + let texel = 1.0 / vec2(textureDimensions(source)); + let center = tap(in.uv); + let left = tap(in.uv - vec2(texel.x, 0.0)); + let right = tap(in.uv + vec2(texel.x, 0.0)); + let up = tap(in.uv - vec2(0.0, texel.y)); + let down = tap(in.uv + vec2(0.0, texel.y)); + let total = clamp(abs(center.a - left.a) + abs(center.a - right.a) + + abs(center.a - up.a) + abs(center.a - down.a), 0.0, 1.0); + let color = center.rgb * center.a + left.rgb * left.a + right.rgb * right.a + + up.rgb * up.a + down.rgb * down.a; + return vec4(color * 0.2, total); +} + +// entity_outline_box_blur.fsh at Radius 2: bilinear taps at -1.5 and 0.5 texels and half +// a tap at 2; the colour averaged, the alpha summed. +fn blur(uv: vec2, step: vec2) -> vec4 { + let blurred = tap(uv + step * -1.5) + tap(uv + step * 0.5) + tap(uv + step * 2.0) / 2.0; + return vec4(blurred.rgb / 2.5, blurred.a); +} + +// BlurDir (1, 0). +@fragment fn fs_blur_x(in: PostOut) -> @location(0) vec4 { + return blur(in.uv, vec2(1.0 / f32(textureDimensions(source).x), 0.0)); +} + +// BlurDir (0, 1): up the screen in GL's bottom-up textures, towards row 0 here. +@fragment fn fs_blur_y(in: PostOut) -> @location(0) vec4 { + return blur(in.uv, vec2(0.0, -1.0 / f32(textureDimensions(source).y))); +} + +// blit_screen.fsh, blended by RenderPipelines.ENTITY_OUTLINE_BLIT. +@fragment fn fs_blit(in: PostOut) -> @location(0) vec4 { + return tap(in.uv); +} diff --git a/crates/horizon-client/src/gfx/lightning.rs b/crates/horizon-client/src/gfx/lightning.rs index 251dbf00e..d979bb368 100644 --- a/crates/horizon-client/src/gfx/lightning.rs +++ b/crates/horizon-client/src/gfx/lightning.rs @@ -77,6 +77,8 @@ fn geometry(seed: i64, uv: [f32; 2]) -> Vec { layer: 2, color, light: 240 | 240 << 8, + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/gfx/lightning/tests/mod.rs b/crates/horizon-client/src/gfx/lightning/tests/mod.rs index f89f402de..66959ce54 100644 --- a/crates/horizon-client/src/gfx/lightning/tests/mod.rs +++ b/crates/horizon-client/src/gfx/lightning/tests/mod.rs @@ -60,6 +60,8 @@ fn reference(seed: i64, at: [f64; 3], camera: DVec3, uv: [f32; 2]) -> VecFloat32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4]; - let offsets = wgpu::vertex_attr_array![6=>Float32x3]; + let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4,6=>Float32x2]; + // Attribute 7: 6 is the entity vertex buffer's glint UV. + let offsets = wgpu::vertex_attr_array![7=>Float32x3]; let vertices = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, diff --git a/crates/horizon-client/src/gfx/pack_entities.rs b/crates/horizon-client/src/gfx/pack_entities.rs index ab3c66c69..c6bcd8beb 100644 --- a/crates/horizon-client/src/gfx/pack_entities.rs +++ b/crates/horizon-client/src/gfx/pack_entities.rs @@ -405,12 +405,12 @@ pub(super) fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer { } /// Whether a run holds only geometry a gbuffers program can draw from the shared atlas: no -/// celestial body, cloud, beam, End portal or crack (overlay codes Horizon's entity shader -/// draws in its own way; entity.wgsl). +/// celestial body, cloud, beam, End portal, crack or energy swirl (overlay codes Horizon's entity +/// shader draws in its own way; entity.wgsl). fn plain(run: &[Vertex]) -> bool { run.iter() .step_by(4) - .all(|v| !matches!(v.layer, 2 | 4 | 6 | 9 | 10 | 11 | 12)) + .all(|v| !matches!(v.layer, 2 | 4 | 6 | 9 | 10 | 11 | 12 | 34)) } /// The programs of entity runs, in the order they draw. diff --git a/crates/horizon-client/src/gfx/pack_weather.rs b/crates/horizon-client/src/gfx/pack_weather.rs index 3479450af..f6bef0219 100644 --- a/crates/horizon-client/src/gfx/pack_weather.rs +++ b/crates/horizon-client/src/gfx/pack_weather.rs @@ -135,6 +135,8 @@ impl PackWeather { color: v.color, light: v.light, normal: [0; 4], + + glint_uv: [0.0, 0.0], } })); if self.scratch.len() > self.capacity { diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index d55e44d99..cb097c114 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -5,8 +5,7 @@ use crate::{ graphics::{FarDetail, GraphicsApi, Overlay, Pacing, PresentMode, Preset}, graphics_style::{Cost, STYLE}, hud::{HudAtlas, HudBatch}, - options_ui::Opt, - settings::Settings, + settings::{Opt, Settings}, text::Text, ui, }; diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 4514c2bcf..28391c496 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -25,19 +25,7 @@ use std::{fs, io, path::Path}; pub(crate) type Attributes = LiveAttributes i32>>; pub(crate) type State = HurtState; -#[derive(Clone, Copy, Debug)] -pub struct HealthRules { - pub difficulty: Difficulty, - pub natural_regeneration: bool, -} -impl Default for HealthRules { - fn default() -> Self { - Self { - difficulty: Difficulty::Normal, - natural_regeneration: true, - } - } -} +pub use crate::world::HealthRules; pub struct HealthResources { pub damage: Catalog, pub ids: PlayerFloatIds, @@ -170,6 +158,12 @@ pub struct PlayerHealth { pub hurt: State, /// Client hurt animation; fully blocked hits only refresh the server's hurt state. pub hurt_animation_time: i32, + /// `Player.hurtDir` on a client: the yaw `ClientboundHurtAnimationPacket` + /// gave, which `GameRenderer.bobHurt` tilts the camera around. + pub hurt_dir: f32, + /// `ServerPlayer.hurtDir` of a hit the player's client hasn't been told + /// of yet (`indicateDamage`). + pub indicated_dir: Option, pub dead: bool, pub sync_velocity: bool, pub game_time: i64, @@ -220,6 +214,8 @@ impl PlayerHealth { last_stamp: 0, }, hurt_animation_time: 0, + hurt_dir: 0.0, + indicated_dir: None, dead: false, sync_velocity: false, game_time: 0, @@ -267,6 +263,18 @@ impl PlayerHealth { self.hurt.hurt_time = 10; self.hurt_animation_time = 10; } + /// `LivingEntity.animateHurt(yaw)` on a player: the tilt restarts around + /// `yaw` (`Player.animateHurt` keeps it as `hurtDir`). + pub fn animate_hurt_dir(&mut self, yaw: f32) { + self.animate_hurt(); + self.hurt_dir = yaw; + } + /// `ServerPlayer.indicateDamage`: the hit's direction relative to where + /// the player looks, kept for the packet to its client. + pub fn indicate_damage(&mut self, xd: f64, zd: f64, yaw: f32) { + use horizon_core::geometry::trig::{RAD_TO_DEG, atan2}; + self.indicated_dir = Some((atan2(zd, xd) * f64::from(RAD_TO_DEG) - f64::from(yaw)) as f32); + } /// `LocalPlayer.hurtTo` with `flashOnSetHealth`: a drop below the current /// health starts the hurt animation; `damageCooldownTime` (20 on a drop, /// 10 on a gain) is what lets `Hud.extractPlayerHealth` blink the hearts. @@ -370,6 +378,13 @@ impl PlayerMotion { if outcome.hurt { h.hurt_animation_time = h.hurt.hurt_time; } + // `dealDefaultKnockback` ends in `indicateDamage` unless blocked: a + // hit with no direction of its own (`xd` and `zd` zero) is sent as + // the opposite of the player's yaw. A hit that has a direction + // replaces this (`mob_hits_player`). + if outcome.knockback && outcome.blocked <= 0.0 { + h.indicate_damage(0.0, 0.0, self.yaw); + } let after = h.health() + h.absorption(); if self.hurt_log.len() >= HURT_LOG { self.hurt_log.remove(0); @@ -633,8 +648,13 @@ impl ImmunityWorld for Environment<'_> { fn enchantment_immunity(&mut self) -> io::Result { Ok(false) } - fn damage_rule(&mut self, _: DamageRule) -> io::Result { - Ok(true) + fn damage_rule(&mut self, rule: DamageRule) -> io::Result { + Ok(match rule { + DamageRule::Drowning => self.rules.drowning_damage, + DamageRule::Fall => self.rules.fall_damage, + DamageRule::Fire => self.rules.fire_damage, + DamageRule::Freeze => self.rules.freeze_damage, + }) } fn changing_dimension(&mut self) -> io::Result { Ok(false) diff --git a/crates/horizon-client/src/hotbar.rs b/crates/horizon-client/src/hotbar.rs index a60f28287..dccae7560 100644 --- a/crates/horizon-client/src/hotbar.rs +++ b/crates/horizon-client/src/hotbar.rs @@ -119,3 +119,23 @@ pub fn load(path: &Path, known: &dyn Fn(&str) -> bool) -> Vec { _ => (0..GROUPS).map(|_| empty()).collect(), } } + +/// `HotbarManager.save`: the nine rows with the current data version, each +/// stack as `ItemStack.OPTIONAL_CODEC` writes it (an empty one is `{}`). +pub fn save(path: &Path, rows: &[Hotbar]) -> crate::Result<()> { + let mut entries = vec![( + JavaString::from("DataVersion"), + Tag::Int(horizon_world::DATA_VERSION), + )]; + for (i, row) in rows.iter().enumerate() { + let stacks = row.iter().map(|s| match s { + Some(s) => save::item_to_nbt(s), + None => Tag::compound(Vec::<(&str, Tag)>::new()), + }); + entries.push(( + JavaString::from(i.to_string().as_str()), + Tag::List(stacks.collect()), + )); + } + save::write_dat(path, Tag::compound(entries)) +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 850093780..2b9bae9b5 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -67,6 +67,11 @@ pub struct HudAtlas { pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>, /// The default font (bitmap sheets in this atlas, unifont rasterized on demand). pub font: crate::font::Font, + /// `misc/enchanted_glint_item` as its own image: vanilla's `GlintSampler` + /// repeats it per pixel, which one sprite inside this atlas cannot. + pub glint: (Vec, u32, u32), + /// `misc/enchanted_glint_armor`, the armour layers' `GlintSampler`. + pub glint_armor: (Vec, u32, u32), white: Rect, } /// Atlas rows reserved for glyphs rasterized at run time. @@ -526,6 +531,8 @@ impl HudAtlas { } } let white = sprites["horizon/white"]; + let glint = Self::glint_texture(root, defaults, "enchanted_glint_item"); + let glint_armor = Self::glint_texture(root, defaults, "enchanted_glint_armor"); let font = crate::font::Font::load( root, &sprites, @@ -542,10 +549,22 @@ impl HudAtlas { translucent, flags, fire_animations, + glint, + glint_armor, font, white, }) } + /// `misc/.png` on its own, or a transparent texel if the resource + /// pack lacks it. + fn glint_texture(root: &Path, defaults: &Path, name: &str) -> (Vec, u32, u32) { + let relative = format!("assets/minecraft/textures/misc/{name}.png"); + let mut path = root.join(&relative); + if !path.exists() && defaults != root { + path = defaults.join(&relative); + } + decode(&path).map_or((vec![0; 4], 1, 1), |(w, h, pixels)| (pixels, w, h)) + } } #[repr(C)] #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] @@ -554,6 +573,9 @@ pub struct HudVertex { pub uv: [f32; 2], pub color: u32, pub depth: f32, + /// The `GLINT_TEXTURING` UV into the repeating glint texture, unused + /// unless `uv.x >= 2`. + pub glint_uv: [f32; 2], } /// The GUI Scale option (0 = auto). pub static GUI_SCALE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -569,6 +591,8 @@ pub struct HudBatch { pub blends: Vec<(std::ops::Range, Blend)>, /// The textures and time of the `Blend::EndPortal` runs. pub end_portal: EndPortalFill, + /// `options.glintStrength` for the glint pass (`GlintAlpha`). + pub glint_alpha: f32, /// Screen's first vertex: the preceding HUD is part of its blurred background. pub blur_at: u32, } @@ -620,6 +644,7 @@ impl HudBatch { patches: Vec::new(), blends: Vec::new(), end_portal: EndPortalFill::default(), + glint_alpha: 0.75, blur_at: 0, } } @@ -695,6 +720,26 @@ impl HudBatch { uv: uv[i], color, depth: 0.0, + glint_uv: [0.0, 0.0], + }); + } + } + /// A quad whose texture is the `GLINT_TEXTURING` sample at `glint_uv`; + /// `uv` is the item's atlas UV, which the shader masks by. + pub fn quad_glint( + &mut self, + p: [[f32; 2]; 4], + uv: [[f32; 2]; 4], + glint_uv: [[f32; 2]; 4], + color: u32, + ) { + for i in [0, 1, 2, 0, 2, 3] { + self.vertices.push(HudVertex { + pos: p[i], + uv: uv[i], + color, + depth: 0.0, + glint_uv: glint_uv[i], }); } } @@ -705,6 +750,7 @@ impl HudBatch { uv: uv[i], color, depth: p[i][2], + glint_uv: [0.0, 0.0], }); } } @@ -875,6 +921,7 @@ impl HudBatch { uv, color: c[i], depth: 0.0, + glint_uv: [0.0, 0.0], }); } } @@ -1055,6 +1102,8 @@ impl HudRenderer { device: &wgpu::Device, format: wgpu::TextureFormat, view: &wgpu::TextureView, + glint_view: &wgpu::TextureView, + glint_sampler: &wgpu::Sampler, ) -> Result { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Horizon HUD"), @@ -1099,6 +1148,22 @@ impl HudRenderer { ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None, }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, ], }); let group = device.create_bind_group(&wgpu::BindGroupDescriptor { @@ -1117,6 +1182,14 @@ impl HudRenderer { binding: 2, resource: wgpu::BindingResource::Sampler(&sampler), }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(glint_view), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(glint_sampler), + }, ], }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -1124,7 +1197,8 @@ impl HudRenderer { bind_group_layouts: &[Some(&layout)], ..Default::default() }); - let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4,3=>Float32]; + let attributes = + wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4,3=>Float32,4=>Float32x2]; let create = |label, blend, fragment_entry, depth: bool| { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some(label), @@ -1339,7 +1413,12 @@ impl HudRenderer { &self.uniform, 0, bytemuck::bytes_of(&HudUniform::new( - [size[0] as f32, size[1] as f32, batch.scale, 0.0], + [ + size[0] as f32, + size[1] as f32, + batch.scale, + batch.glint_alpha, + ], batch.end_portal, )), ); @@ -1789,6 +1868,7 @@ mod tests { patches: Vec::new(), blends: Vec::new(), end_portal: EndPortalFill::default(), + glint_alpha: 0.75, blur_at: 0, }; for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] { diff --git a/crates/horizon-client/src/hud.wgsl b/crates/horizon-client/src/hud.wgsl index ebb6dc2cb..435f7f062 100644 --- a/crates/horizon-client/src/hud.wgsl +++ b/crates/horizon-client/src/hud.wgsl @@ -7,28 +7,35 @@ struct Hud { @group(0) @binding(0) var hud: Hud; @group(0) @binding(1) var atlas: texture_2d; @group(0) @binding(2) var atlas_sampler: sampler; +// enchanted_glint_item on its own repeating texture (vanilla's GlintSampler). +@group(0) @binding(3) var glint_tex: texture_2d; +@group(0) @binding(4) var glint_sampler: sampler; struct Out { @builtin(position) clip: vec4, @location(0) uv: vec2, @location(1) color: vec4, // projection_from_position(gl_Position): the End portal's texProj0. @location(2) proj: vec4, + @location(3) glint_uv: vec2, } -@vertex fn vs_main(@location(0) pos: vec2, @location(1) uv: vec2, @location(2) color: vec4, @location(3) depth: f32) -> Out { +@vertex fn vs_main(@location(0) pos: vec2, @location(1) uv: vec2, @location(2) color: vec4, @location(3) depth: f32, @location(4) glint_uv: vec2) -> Out { let pixels = pos * hud.size.z; var out: Out; out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, depth, 1.0); out.uv = uv; out.color = color; out.proj = vec4(out.clip.xy * 0.5 + 0.5, out.clip.zw); + out.glint_uv = glint_uv; return out; } @fragment fn fs_main(in: Out) -> @location(0) vec4 { - // u >= 2: flat vertex colour masked by the texture's alpha (enchantment glint). + // u >= 2: the GLINT_TEXTURING sample over the item, masked by the item's + // texture alpha (item.fsh's ALPHA_CUTOUT and GLINT path). if in.uv.x >= 2.0 { - let m = textureSample(atlas, atlas_sampler, in.uv - vec2(2.0, 0.0)).a * in.color.a; - if m < 0.004 { discard; } - return vec4(in.color.rgb, m); + let mask = textureSample(atlas, atlas_sampler, in.uv - vec2(2.0, 0.0)).a; + if mask < 0.1 { discard; } + let glint = hud.size.w * textureSample(glint_tex, glint_sampler, in.glint_uv); + return vec4(glint.rgb * glint.rgb, mask); } let c = textureSample(atlas, atlas_sampler, in.uv) * in.color; if c.a < 0.004 { discard; } diff --git a/crates/horizon-client/src/hud_layout.rs b/crates/horizon-client/src/hud_layout.rs index 4b0f2fa82..42347d877 100644 --- a/crates/horizon-client/src/hud_layout.rs +++ b/crates/horizon-client/src/hud_layout.rs @@ -485,6 +485,11 @@ pub struct HealthHud { /// `Util.getMillis()` of the last health change. pub last_health_time: i64, pub health_blink_time: i64, + /// `Hud.leftHeight` and `rightHeight` once the health, armor, food, mount + /// and air layers have run; the selected item name and the action bar sit + /// above them. + pub left_height: i32, + pub right_height: i32, } pub struct HealthInputs { @@ -645,6 +650,9 @@ impl HealthHud { let rows = ceil((max_health + absorption as f32) / 2.0 / 10.0); let row_height = (10 - (rows - 2)).max(3); let mut y_air = y_base - 10; + self.left_height = 39 + (rows - 1) * row_height + 10 + if i.armor > 0 { 10 } else { 0 }; + // The mount's heart rows (`extractVehicleHealth`); food adds its row below. + self.right_height = 39 + 10 * ((i.vehicle_hearts + 9) / 10); let offset_index = if i.regeneration { i.tick % ceil(max_health + 5.0) } else { @@ -739,11 +747,13 @@ impl HealthHud { } } y_air -= 10; + self.right_height += 10; } // Hud.extractAirBubbles. let max_air = i.max_air.max(1); let air = i.air.clamp(0, max_air); if i.under_water || air < max_air { + self.right_height += 10; let rows = (f64::from(i.vehicle_hearts) / 10.0).ceil() as i32; let y = y_air - (rows - 1) * 10; let bubble = |offset: i32| ceil(((air + offset) * 10) as f32 / max_air as f32); diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index c6b098f75..a5373cbf4 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -107,10 +107,11 @@ pub struct EffectIcon { impl From<&crate::effects::EffectInstance> for EffectIcon { fn from(effect: &crate::effects::EffectInstance) -> Self { - let def = crate::brewing::effect(effect.id); + let def = horizon_client_core::potions::effect(effect.id); Self { id: effect.id.to_owned(), - beneficial: def.is_some_and(|d| d.category == crate::brewing::Category::Beneficial), + beneficial: def + .is_some_and(|d| d.category == horizon_client_core::potions::Category::Beneficial), color: def.map_or(0, |d| d.color as i32), ambient: effect.ambient, duration: effect.duration, @@ -322,11 +323,13 @@ impl Titles { } } } - /// `Hud.extractOverlayMessage`. + /// `Hud.extractOverlayMessage`; `bar_height` is + /// `max(leftHeight, rightHeight)`. pub fn overlay_message( &self, w: i32, h: i32, + bar_height: i32, partial: f32, font: &Font, background: u32, @@ -342,9 +345,12 @@ impl Titles { let alpha = ((t * 255.0 / 20.0) as i32).min(255); if alpha > 0 { let message = message.resolve_legacy(); + // The bars' height plus the gap between the item name (59) and the + // overlay (68), at least the default level. + let y_shift = bar_height + (68 - 59); out.push(GuiDraw::Push(vec![PoseOp::Translate( (w / 2) as f32, - (h - 68) as f32, + (h - y_shift.max(68)) as f32, )])); let color = if self.overlay_animated { hsv_to_argb(t / 50.0, 0.7, 0.6, alpha as u32) @@ -462,11 +468,13 @@ impl ToolHighlight { self.last = selected; } /// `Hud.extractSelectedItemName`; `can_hurt` is - /// `gameMode.canHurtPlayer()` (survival and adventure). + /// `gameMode.canHurtPlayer()` (survival and adventure) and `bar_height` + /// is `max(leftHeight, rightHeight)`. pub fn draw( &self, w: i32, h: i32, + bar_height: i32, can_hurt: bool, font: &Font, background: u32, @@ -487,7 +495,7 @@ impl ToolHighlight { } let str_width = width(font, &name); let x = (w - str_width) / 2; - let mut y = h - 59; + let mut y = h - bar_height.max(59); if !can_hurt { y += 14; } diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 9873752ca..ccdccfb8e 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -106,6 +106,16 @@ impl StackData { pub fn other(&self, id: &str) -> Option<&Tag> { self.other.iter().find(|(k, _)| k == id).map(|(_, v)| v) } + /// `SetNameFunction.run`: a loot text component stored as `custom_name` + /// (plain text, as modelled) or as the unmodelled `item_name`. + pub fn set_loot_name(&mut self, id: &str, text: &serde_json::Value) { + let tag = crate::scoreboard::json_to_tag(text); + if id == "minecraft:custom_name" { + self.custom_name = read_text(&tag); + } else { + self.set_other(id, Some(tag)); + } + } /// Set (or with None remove) an unmodelled component. pub fn set_other(&mut self, id: &str, value: Option) { self.other.retain(|(k, _)| k != id); @@ -143,6 +153,9 @@ pub struct WrittenBook { pub author: String, pub generation: u8, pub pages: Vec, + /// Each page's component when it is not a plain string, so that its + /// click events survive; empty or one per page. + pub page_tags: Vec, } impl StackData { pub fn is_empty(&self) -> bool { @@ -214,6 +227,19 @@ impl ItemStack { pub fn has_any_enchantments(&self) -> bool { !self.enchantments().is_empty() || !self.stored_enchantments().is_empty() } + /// `ItemStack.hasFoil`: an explicit `minecraft:enchantment_glint_override` + /// component wins, then the item's default override (`item_glint`), then a + /// non-empty `minecraft:enchantments` component (`Item.isFoil` is + /// `ItemStack.isEnchanted`; stored book enchantments do not count). + pub fn has_foil(&self, item_glint: bool) -> bool { + if let Some(Tag::Byte(flag)) = self + .data() + .and_then(|d| d.other("minecraft:enchantment_glint_override")) + { + return *flag != 0; + } + item_glint || !self.enchantments().is_empty() + } pub fn repair_cost(&self) -> u32 { self.data().map_or(0, |d| d.repair_cost) } @@ -309,6 +335,21 @@ fn read_levels(t: Option<&Tag>) -> Levels { } /// A text component as stored by vanilla: a plain string or `{"text": ...}`. /// A `Filterable`: the value itself or `{raw: value}`. +/// `ComponentSerialization.CODEC`'s short form: a plain text component with +/// no style and no siblings is written as its string. +fn plain_component(t: &Tag) -> Tag { + if let Tag::Compound(c) = t + && let Some(text @ Tag::String(_)) = c.get(&"text".into()) + && c.iter().all(|(k, v)| { + k.to_string_lossy() == "text" + || (k.to_string_lossy() == "type" + && matches!(v, Tag::String(s) if s.to_string_lossy() == "text")) + }) + { + return text.clone(); + } + t.clone() +} fn filterable_text(t: &Tag) -> Option { match t.get("raw") { Some(raw) => read_text(raw), @@ -540,11 +581,14 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { )); } if let Some(w) = &d.written { - let pages = w - .pages - .iter() - .map(|p| raw(Tag::String(p.as_str().into()))) - .collect(); + let pages = if w.page_tags.len() == w.pages.len() { + w.page_tags.iter().cloned().map(raw).collect() + } else { + w.pages + .iter() + .map(|p| raw(Tag::String(p.as_str().into()))) + .collect() + }; entries.push(( "minecraft:written_book_content", Tag::compound({ @@ -725,6 +769,13 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option pages.iter().filter_map(filterable_text).collect(), _ => Vec::new(), }, + page_tags: match b.get("pages") { + Some(Tag::List(pages)) => pages + .iter() + .map(|p| plain_component(p.get("raw").unwrap_or(p))) + .collect(), + _ => Vec::new(), + }, }), fireworks: c .get("minecraft:fireworks") diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index 323b1dd70..107da9208 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -41,6 +41,9 @@ use std::{ pub struct ItemQuad { pub pos: [Vec3; 4], pub uv: [[f32; 2]; 4], + /// The model UVs `GLINT_TEXTURING` scrolls for the glint (vanilla's UV0, + /// or UV3 for a special model). + pub foil_uv: [[f32; 2]; 4], pub normal: Vec3, pub color: u32, pub foil: Foil, @@ -50,6 +53,47 @@ pub struct ItemQuad { /// is a translucent sheet): drawn with the translucent entities. pub translucent: bool, } +/// `TextureTransform.setupGlintTexturing`'s inputs. +#[derive(Clone, Copy, Debug)] +pub struct Glint { + /// `options.glintSpeed` (vanilla default 0.5). + pub speed: f32, + /// `options.glintStrength` / shader `GlintAlpha` (vanilla default 0.75). + pub alpha: f32, + /// `Util.getMillis()`. + pub millis: f32, + /// The transform's scale: `GLINT_TEXTURING`'s 8.0 for GUI items, + /// `ENTITY_GLINT_TEXTURING`'s 0.5 for items in the world and + /// `ARMOR_ENTITY_GLINT_TEXTURING`'s 0.16 for armour (entity.wgsl). + pub scale: f32, +} +impl Glint { + /// `Util.getMillis() * glintSpeed * 8.0` as vanilla's long. + fn ticks(millis: f32, speed: f32) -> i64 { + (f64::from(millis) * f64::from(speed) * 8.0) as i64 + } + /// The scroll clock modulo the common period of both offsets (110000 and + /// 30000 divide 330000), for `globals.time.w`: the entity shader derives + /// `ARMOR_ENTITY_GLINT_TEXTURING` from it. + pub fn scroll_ticks(millis: f32, speed: f32) -> f32 { + (Self::ticks(millis, speed) % 330_000) as f32 + } + /// `TextureTransform.setupGlintTexturing(scale)` applied to the model UV: + /// translation(-o0, o1) * rotateZ(PI/18) * scale. The result repeats: + /// the shader samples the dedicated glint texture with vanilla's + /// repeating `GlintSampler`, so the UVs stay unwrapped. + pub fn uv(&self, model: [f32; 2]) -> [f32; 2] { + let ticks = Self::ticks(self.millis, self.speed); + let offset0 = (ticks % 110_000) as f32 / 110_000.0; + let offset1 = (ticks % 30_000) as f32 / 30_000.0; + let angle = std::f32::consts::PI / 18.0; + let (sin, cos) = angle.sin_cos(); + [ + model[0] * self.scale * cos - model[1] * self.scale * sin - offset0, + model[0] * self.scale * sin + model[1] * self.scale * cos + offset1, + ] + } +} /// Which glint render type a quad uses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Foil { @@ -258,6 +302,7 @@ fn submit_quads( sink.quad(ItemQuad { pos, uv, + foil_uv: q.uv, normal: transform_normal(m, direction_vector(q.facing)), color: argb(color), foil, @@ -712,6 +757,8 @@ pub struct WorldSink<'a> { pub light: u32, /// The level's diffuse lights; `None` leaves the colour unshaded. pub lights: Option<(Vec3, Vec3)>, + /// The `GLINT_TEXTURING` sample for foil quads (`None` leaves them unglinted). + pub glint: Option, } impl ItemSink for WorldSink<'_> { fn quad(&mut self, q: ItemQuad) { @@ -726,13 +773,19 @@ impl ItemSink for WorldSink<'_> { } else { self.light }; - let overlay = match (q.foil, q.translucent) { - (Foil::None, true) => crate::gfx::TRANSLUCENT_ITEM_OVERLAY, - (Foil::None, false) => 0, - (_, true) => crate::gfx::TRANSLUCENT_GLINT_ITEM_OVERLAY, - (_, false) => 7, + let glint = if q.foil == Foil::None { + None + } else { + self.glint }; - for (p, uv) in q.pos.iter().zip(q.uv) { + let overlay = match (glint.is_some(), q.translucent) { + (false, true) => crate::gfx::TRANSLUCENT_ITEM_OVERLAY, + (false, false) => 0, + (true, true) => crate::gfx::TRANSLUCENT_GLINT_ITEM_OVERLAY, + (true, false) => 7, + }; + for (i, (p, uv)) in q.pos.iter().zip(q.uv).enumerate() { + let glint_uv = glint.map_or([0.0, 0.0], |glint| glint.uv(q.foil_uv[i])); self.out.push(Vertex { normal: [0; 4], pos: p.to_array(), @@ -740,6 +793,7 @@ impl ItemSink for WorldSink<'_> { layer: overlay, color, light, + glint_uv, }); } } @@ -796,6 +850,33 @@ pub fn cluster_poses(state: &ItemRenderState, pose: Mat4, amount: u32, seed: i64 mod tests { use super::*; + /// A bad item model surfaces only once items.json has loaded, so a broken + /// items.json still reports itself first. + #[test] + fn item_model_errors_wait_for_the_item_definitions() -> crate::Result<()> { + let root = + std::env::temp_dir().join(format!("horizon-item-model-errors-{}", std::process::id())); + let model = root.join("assets/horizon/models/INVALID.json"); + fs::create_dir_all(model.parent().unwrap())?; + fs::write(model, "{}")?; + let library = crate::model_library::ParsedModels::load(&root).into_item_library(); + assert!(library.is_err()); + fs::write(root.join("items.json"), "{")?; + let load = || { + ItemRenderer::load_with_library(&root, library.clone()) + .err() + .unwrap() + .to_string() + }; + let broken_items = load(); + fs::write(root.join("items.json"), "{}")?; + let bad_model = load(); + let _ = fs::remove_dir_all(&root); + assert!(!broken_items.starts_with("item models:")); + assert!(bad_model.starts_with("item models:")); + Ok(()) + } + #[test] fn rendered_amounts_follow_the_count_bands() { let bands: Vec = [0, 1, 2, 16, 17, 32, 33, 48, 49, 64] diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index e0c901c0e..a99969679 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -5,7 +5,7 @@ //! drawn far to near, and clipped to the item's 16x16 slot unless the model //! is oversized in the GUI (`GuiItemAtlas` draws each item into a scissored //! 16x16 slot; oversized items get a picture-in-picture of their bounds). -use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost}; +use super::{Foil, Glint, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost}; use crate::hud::{HudBatch, Rect}; use glam::{EulerRot, Mat4, Vec2, Vec3}; use std::{collections::HashMap, f32::consts::PI, sync::Arc}; @@ -43,6 +43,7 @@ pub fn items_3d_lights() -> (Vec3, Vec3) { struct Point { p: Vec2, uv: [f32; 2], + glint_uv: [f32; 2], } fn lerp(a: Point, b: Point, t: f32) -> Point { Point { @@ -51,6 +52,10 @@ fn lerp(a: Point, b: Point, t: f32) -> Point { a.uv[0] + (b.uv[0] - a.uv[0]) * t, a.uv[1] + (b.uv[1] - a.uv[1]) * t, ], + glint_uv: [ + a.glint_uv[0] + (b.glint_uv[0] - a.glint_uv[0]) * t, + a.glint_uv[1] + (b.glint_uv[1] - a.glint_uv[1]) * t, + ], } } /// Sutherland-Hodgman against one half plane `dot(p, n) <= limit`. @@ -97,37 +102,25 @@ pub fn lit_color(q: &ItemQuad, lights: (Vec3, Vec3)) -> u32 { let c = |v: u8| (f32::from(v) * light) as u8; crate::hud::rgba(c(r), c(g), c(b), a) } -/// The glint's moving sheen at a GUI position (a stand-in for the -/// `GLINT_TEXTURING`-scrolled `enchanted_glint_item` texture added on top). -fn glint_color(p: Vec2, time: f32) -> u32 { - let d = ((p.x + p.y) / 32.0 - time * 0.35).rem_euclid(1.0); - let band = (1.0 - (d - 0.5).abs() * 6.0).max(0.0); - crate::hud::rgba( - (170.0 + 70.0 * band) as u8, - (90.0 + 110.0 * band) as u8, - 255, - (45.0 + 110.0 * band) as u8, - ) -} - -fn emit(batch: &mut HudBatch, fan: &[Point], color: impl Fn(Vec2) -> u32, glint: bool) { - let shift = if glint { 2.0 } else { 0.0 }; +fn emit(batch: &mut HudBatch, fan: &[Point], color: impl Fn(Vec2) -> u32, glint: Option<&Glint>) { for i in 1..fan.len().saturating_sub(1) { let (a, b, c) = (fan[0], fan[i], fan[i + 1]); let corners = [a, b, c, c]; - // `HudBatch.quad` draws (0, 1, 2) and (0, 2, 3): the second is empty. - batch.quad( - corners.map(|v| v.p.to_array()), - corners.map(|v| [v.uv[0] + shift, v.uv[1]]), - color(a.p), - ); - if glint { - // Per-vertex colours are flat per quad in the HUD batch: use the - // fan centre for the sheen. - let n = batch.vertices.len(); - for v in &mut batch.vertices[n - 6..] { - v.color = color(Vec2::from(v.pos)); - } + if let Some(glint) = glint { + let start = batch.vertices.len(); + batch.quad_glint( + corners.map(|v| v.p.to_array()), + corners.map(|v| [v.uv[0] + 2.0, v.uv[1]]), + corners.map(|v| glint.uv(v.glint_uv)), + u32::MAX, + ); + batch.blend_since(start, crate::hud::Blend::Additive); + } else { + batch.quad( + corners.map(|v| v.p.to_array()), + corners.map(|v| v.uv), + color(a.p), + ); } } } @@ -144,6 +137,8 @@ pub fn draw( x: f32, y: f32, time: f32, + glint_speed: f32, + glint_alpha: f32, ) { if state.is_empty() { return; @@ -162,7 +157,18 @@ pub fn draw( return; } let start = batch.vertices.len(); - draw_now(state, renderer, sprites, host, batch, x, y, time); + draw_now( + state, + renderer, + sprites, + host, + batch, + x, + y, + time, + glint_speed, + glint_alpha, + ); if let Some(key) = key && let Ok(mut drawn) = renderer.gui_drawn.lock() { @@ -236,6 +242,8 @@ fn draw_now( x: f32, y: f32, time: f32, + glint_speed: f32, + glint_alpha: f32, ) { let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0)) * Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0)); @@ -256,7 +264,16 @@ fn draw_now( } else { [x, y, x + 16.0, y + 16.0] }; - draw_quads(&quads, lights, batch, rect, time); + let glint = sprites + .contains_key("misc/enchanted_glint_item") + .then_some(Glint { + speed: glint_speed, + alpha: glint_alpha, + millis: time * 1000.0, + scale: 8.0, + }); + batch.glint_alpha = glint_alpha; + draw_quads(&quads, lights, batch, rect, glint.as_ref()); } /// Lights, culls, sorts far to near and clips `quads` (GUI positions) to @@ -266,7 +283,7 @@ fn draw_quads( lights: (Vec3, Vec3), batch: &mut HudBatch, rect: [f32; 4], - time: f32, + glint: Option<&Glint>, ) { for face in depth::sort(quads) { let q = &quads[face.quad]; @@ -276,6 +293,7 @@ fn draw_quads( .map(|v| Point { p: v.pos.truncate(), uv: v.uv, + glint_uv: v.glint_uv, }) .collect(); let color = lit_color(q, lights); @@ -285,9 +303,9 @@ fn draw_quads( if fan.len() < 3 { continue; } - emit(batch, &fan, |_| color, false); + emit(batch, &fan, |_| color, None); if q.foil != Foil::None { - emit(batch, &fan, |p| glint_color(p, time), true); + emit(batch, &fan, |_| color, glint); } } } @@ -342,7 +360,7 @@ pub fn draw_banner_result( items_flat_lights(), batch, [x0, y0, x0 + 20.0, y0 + 40.0], - 0.0, + None, ); } @@ -354,6 +372,7 @@ mod tests { ItemQuad { pos: [(0.0, y0), (0.0, y1), (8.0, y1), (8.0, y0)].map(|(x, y)| Vec3::new(x, y, z(y))), uv: [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], + foil_uv: [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], normal: Vec3::Z, color, foil: Foil::None, @@ -395,7 +414,7 @@ mod tests { (Vec3::Z, Vec3::Z), &mut batch, [0.0, 0.0, 16.0, 16.0], - 0.0, + None, ); assert_eq!(color_at(&batch, Vec2::new(4.0, 0.5)), Some(u32::MAX)); } @@ -411,7 +430,7 @@ mod tests { (Vec3::Z, Vec3::Z), &mut batch, [0.0, 0.0, 16.0, 16.0], - 0.0, + None, ); assert_eq!( color_at(&batch, Vec2::new(4.0, 2.0)), @@ -443,7 +462,7 @@ mod tests { (Vec3::Z, Vec3::Z), &mut batch, [0.0, 0.0, 16.0, 16.0], - 0.0, + None, ); for y in [0.5, 6.0] { assert_eq!( @@ -469,6 +488,7 @@ mod tests { let p = |x: f32, y: f32| Point { p: Vec2::new(x, y), uv: [x, y], + glint_uv: [0.0, 0.0], }; let fan = clip_triangle( [p(-4.0, 0.0), p(8.0, 0.0), p(8.0, 8.0)], diff --git a/crates/horizon-client/src/item_render/gui/depth.rs b/crates/horizon-client/src/item_render/gui/depth.rs index 9fecfdee7..aaaa0c55d 100644 --- a/crates/horizon-client/src/item_render/gui/depth.rs +++ b/crates/horizon-client/src/item_render/gui/depth.rs @@ -10,6 +10,7 @@ use glam::{Vec3, Vec4}; pub(super) struct Corner { pub pos: Vec3, pub uv: [f32; 2], + pub glint_uv: [f32; 2], } pub(super) struct Face { @@ -38,6 +39,9 @@ fn split(face: Face, distances: &[f32]) -> (Face, Face) { let corner = Corner { pos: a.pos.lerp(b.pos, t), uv: std::array::from_fn(|k| a.uv[k] + (b.uv[k] - a.uv[k]) * t), + glint_uv: std::array::from_fn(|k| { + a.glint_uv[k] + (b.glint_uv[k] - a.glint_uv[k]) * t + }), }; back.push(corner); front.push(corner); @@ -73,6 +77,7 @@ pub(super) fn sort(quads: &[ItemQuad]) -> Vec { corners: std::array::from_fn::<_, 4, _>(|k| Corner { pos: q.pos[k], uv: q.uv[k], + glint_uv: q.foil_uv[k], }) .to_vec(), }) diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index dc023f756..6a1d049af 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -115,6 +115,7 @@ fn draw( sprite.v0 + (sprite.v1 - sprite.v0) * v[4], ] }), + foil_uv: poly.map(|v| [v[3], v[4]]), normal, color, foil, @@ -499,7 +500,7 @@ pub(super) fn submit( let skin = (!argument.is_null()) .then(|| host.player_skin(argument)) .flatten() - .unwrap_or_else(|| "entity/player/wide/steve".to_owned()); + .unwrap_or_else(|| "entity/player/slim/steve".to_owned()); part("player", &none, &skin, white, Foil::None); } SpecialKind::Trident => { diff --git a/crates/horizon-client/src/item_sync.rs b/crates/horizon-client/src/item_sync.rs index fc35e15e7..bc2b54e26 100644 --- a/crates/horizon-client/src/item_sync.rs +++ b/crates/horizon-client/src/item_sync.rs @@ -95,6 +95,22 @@ fn components_tag(s: &Stack, builtin: &Builtin, synced: &Dynamic) -> Option ), ]), Component::FireworkExplosion(e) => fireworks_tag(e), + Component::LodestoneTracker { target, tracked } => { + let mut entries = Vec::new(); + if let Some((dimension, pos)) = target { + entries.push(( + "target", + Tag::compound([ + ("dimension", Tag::String(dimension.as_str().into())), + ("pos", Tag::IntArray(pos.to_vec())), + ]), + )); + } + if !tracked { + entries.push(("tracked", Tag::Byte(0))); + } + Tag::compound(entries) + } Component::Enchantments(list) => { // Enchantments are a synced (data-driven) registry: the // ids index the server's RegistryData, not the builtin @@ -229,6 +245,17 @@ fn profile_tag(p: &Profile) -> Tag { if let Some(name) = &p.name { entries.push(("name", Tag::String(name.as_str().into()))); } + if let Some(id) = p.id { + entries.push(( + "id", + Tag::IntArray(vec![ + (id >> 96) as i32, + (id >> 64) as i32, + (id >> 32) as i32, + id as i32, + ]), + )); + } entries.push(("properties", Tag::List(properties))); Tag::compound(entries) } diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index 63a19b114..ce4fc352d 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -484,6 +484,37 @@ pub fn component_count(stack: &ItemStack, info: Option<&ItemInfo>) -> usize { keys.len() } +/// `SmithingTemplateItem.appendHoverText`: the template's kind, what it applies to +/// and its ingredients (gray titles over blue descriptions); none for other items. +pub fn smithing_template_lines( + stack: &ItemStack, + translate: &dyn Fn(&str) -> Option, +) -> Vec<(String, u32)> { + let path = stack.item.trim_start_matches("minecraft:"); + if !path.ends_with("_smithing_template") { + return Vec::new(); + } + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + let kind = if path == "netherite_upgrade_smithing_template" { + "netherite_upgrade" + } else { + "armor_trim" + }; + let (title, description) = (rgba(170, 170, 170, 255), rgba(85, 85, 255, 255)); + let described = |what: &str| { + let key = format!("item.minecraft.smithing_template.{kind}.{what}"); + (format!(" {}", text(&key)), description) + }; + vec![ + (text("item.minecraft.smithing_template"), title), + (String::new(), u32::MAX), + (text("item.minecraft.smithing_template.applies_to"), title), + described("applies_to"), + (text("item.minecraft.smithing_template.ingredients"), title), + described("ingredients"), + ] +} + /// The lines of `stack` below its name that its components give, in /// `ItemStack.addDetailsToTooltip` order. pub fn detail_lines( @@ -494,30 +525,11 @@ pub fn detail_lines( let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); let path = stack.item.trim_start_matches("minecraft:"); let mut lines = Vec::new(); - // SmithingTemplateItem.appendHoverText. - if path.ends_with("_smithing_template") { - let kind = if path == "netherite_upgrade_smithing_template" { - "netherite_upgrade" - } else { - "armor_trim" - }; - lines.push(text("item.minecraft.smithing_template")); - lines.push(String::new()); - lines.push(text("item.minecraft.smithing_template.applies_to")); - lines.push(format!( - " {}", - text(&format!( - "item.minecraft.smithing_template.{kind}.applies_to" - )) - )); - lines.push(text("item.minecraft.smithing_template.ingredients")); - lines.push(format!( - " {}", - text(&format!( - "item.minecraft.smithing_template.{kind}.ingredients" - )) - )); - } + lines.extend( + smithing_template_lines(stack, translate) + .into_iter() + .map(|l| l.0), + ); let display = TooltipDisplay::for_stack(stack); lines.extend(bees_line(stack, &display, translate)); lines.extend(honey_line(stack, &display, translate)); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 10f1c72ad..bd818bd76 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -1154,6 +1154,8 @@ impl Items { ctx.evaluate(table, random) } } +/// `DataComponents.BLOCK_STATE`. +const BLOCK_STATE: &str = "minecraft:block_state"; impl LootContext<'_> { fn evaluate(&self, table: &Value, random: &mut R) -> Vec { let ctx = self; @@ -1561,6 +1563,30 @@ impl LootContext<'_> { } } } + // CopyBlockState: the listed properties of the broken block + // become the item's `block_state` component. + "minecraft:copy_state" => { + use horizon_world::nbt::Tag; + let mut copied = match stack.data().and_then(|d| d.other(BLOCK_STATE)) { + Some(Tag::Compound(c)) => c.clone(), + _ => Default::default(), + }; + for name in f["properties"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if let Some(value) = self.properties.get(name) { + copied.insert(name.into(), Tag::String(value.as_str().into())); + } + } + if !copied.is_empty() { + stack + .data_mut() + .set_other(BLOCK_STATE, Some(Tag::Compound(copied))); + } + } // ApplyExplosionDecay: each item survives with 1 / radius. "minecraft:explosion_decay" => { if let Some(radius) = self.explosion_radius { diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 920052b5a..19eda20a9 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -742,6 +742,24 @@ impl Entities { chunk, }); } + // TrackedEntity.getEffectiveRange: a vehicle is tracked as far as its + // widest indirect passenger, so a rider never leaves before its mount. + for (&vehicle, passengers) in &riding.passengers { + let Some(own) = self.states.get(&vehicle).filter(|s| s.seen == now) else { + continue; + }; + let (index, mut range) = (own.index, own.range); + let mut pending = passengers.clone(); + while let Some(id) = pending.pop() { + if let Some(s) = self.states.get(&id).filter(|s| s.seen == now) { + range = range.max(s.range); + } + pending.extend_from_slice(riding.passengers(id)); + } + self.probes[index].range = self + .range_percent + .map_or(range * 16, |p| p * (range * 16) / 100); + } self.flags.resize_with(viewers.len(), Vec::new); self.pairs.clear(); self.pairs.resize(entities.len(), false); diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 2deb5905e..083a99dec 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -614,6 +614,21 @@ fn network_stack( )); } stack.added.extend(firework_components(d)); + // The compass's lodestone target. + if let Some(t) = d.other("minecraft:lodestone_tracker") { + let target = t.get("target").and_then(|g| { + let Some(horizon_world::nbt::Tag::IntArray(pos)) = g.get("pos") else { + return None; + }; + let dimension = crate::save::text(g.get("dimension"))?; + Some((dimension, [*pos.first()?, *pos.get(1)?, *pos.get(2)?])) + }); + let tracked = crate::save::number(t.get("tracked")).is_none_or(|v| v != 0); + stack.added.push(( + horizon_protocol::item::component::LODESTONE_TRACKER, + horizon_protocol::item::Component::LodestoneTracker { target, tracked }, + )); + } // PotionContents: the potion by its `minecraft:potion` id. if let Some(id) = (d.potion.as_deref()).and_then(|potion| { synced_id( @@ -669,11 +684,14 @@ fn network_stack( title: w.title.clone(), author: w.author.clone(), generation: i32::from(w.generation), - pages: w - .pages - .iter() - .map(|p| horizon_protocol::text::literal(p)) - .collect(), + pages: if w.page_tags.len() == w.pages.len() { + w.page_tags.clone() + } else { + w.pages + .iter() + .map(|p| horizon_protocol::text::literal(p)) + .collect() + }, resolved: true, }, ), diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 7395cc0a4..70b9babe0 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -43,6 +43,7 @@ pub mod game_event { pub const RAIN_LEVEL: u8 = 7; pub const THUNDER_LEVEL: u8 = 8; pub const GUARDIAN_ELDER_EFFECT: u8 = 10; + pub const IMMEDIATE_RESPAWN: u8 = 11; pub const LEVEL_CHUNKS_LOAD_START: u8 = 13; } @@ -172,9 +173,14 @@ pub struct Hub { /// The `player_movement_check` and `elytra_movement_check` game rules, /// set by the game before each tick. pub movement_checks: (bool, bool), + /// The `immediate_respawn` game rule, as the players were last told. + immediate_respawn: bool, /// An integrated server's owner (`MinecraftServer.isSingleplayerOwner`), /// whose moves are never checked. pub singleplayer_owner: Option, + /// The world is superflat (`ServerLevel.isFlat`, a world-wide flag, sent as + /// `CommonPlayerSpawnInfo.isFlat` in every dimension). + pub flat_world: bool, /// Who rides what, set by the game before each tick. pub riding: super::entity::Riding, /// The scoreboard's teams, set by the game each tick, for players' @@ -352,8 +358,10 @@ impl Hub { guests: Vec::new(), sync, ticks: 0, + immediate_respawn: false, movement_checks: (true, true), singleplayer_owner: None, + flat_world: false, riding: Default::default(), last_clock: i64::MIN, last_rate: 0.0, @@ -429,6 +437,17 @@ impl Hub { g.sender.send(body.clone()); } } + /// MinecraftServer.onGameRuleChanged: every player is told when + /// `immediate_respawn` changes; a joining player's Login carries it. + pub fn set_immediate_respawn(&mut self, on: bool) { + if self.immediate_respawn != on { + self.immediate_respawn = on; + self.broadcast(&C::GameEvent(play::GameEvent { + event: game_event::IMMEDIATE_RESPAWN, + param: if on { 1.0 } else { 0.0 }, + })); + } + } /// PlayerList.setViewDistance: every player is told the new radius, /// and each one's chunks follow it, up to what they asked for /// (ChunkMap.getPlayerViewDistance). @@ -595,7 +614,7 @@ impl Hub { game_type: game_mode, previous_game_type: None, debug: false, - flat: false, + flat: self.flat_world, last_death: None, portal_cooldown: 0, sea_level: 63, @@ -663,7 +682,7 @@ impl Hub { chunk_radius: self.config.view_distance, simulation_distance: self.config.simulation_distance, reduced_debug_info: false, - show_death_screen: true, + show_death_screen: !self.immediate_respawn, limited_crafting: false, spawn: self.spawn_info(mode), // MinecraftServer.usesAuthentication, enforceSecureProfile. diff --git a/crates/horizon-client/src/main.rs b/crates/horizon-client/src/main.rs index 7144a1670..8d03455af 100644 --- a/crates/horizon-client/src/main.rs +++ b/crates/horizon-client/src/main.rs @@ -23,6 +23,8 @@ fn main() { }; if !help { logging::init(&home, thread); + // The log's first line names the build, so a bug report that carries the log says which one it was. + log::info!("Horizon {}", crash::version()); crash::install(home.clone(), side); } if let Err(error) = game::run() { diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index da24eb176..1aeeec1e1 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -288,6 +288,9 @@ pub struct Menu { pub player_sounds: Vec<&'static str>, /// Recipes whose result was taken (`awardUsedRecipes`), for the caller. pub crafted: Vec, + /// Potions taken from a brewing stand's bottle slots + /// (`PotionSlot.onTake`), for the caller. + pub brewed: Vec, /// `LivingEntity.onEquipItem` calls that change the item: the /// `EquipmentSlot` name and the new stack, in order, for the caller. pub equipped: Vec<(&'static str, Option)>, @@ -683,6 +686,7 @@ impl Menu { sounds: Vec::new(), player_sounds: Vec::new(), crafted: Vec::new(), + brewed: Vec::new(), equipped: Vec::new(), merchant: None, stone: Stonecutter::default(), @@ -1504,7 +1508,17 @@ impl Menu { } /// `ResultSlot.onTake` and the other `Slot.onTake` overrides. - fn on_take(&mut self, env: &Env, s: usize) { + fn on_take(&mut self, env: &Env, s: usize, taken: &ItemStack) { + if self.slots[s].role == Role::Potion { + // BrewingStandMenu.PotionSlot.onTake: a stack with potion contents. + if matches!( + &*taken.item, + "minecraft:potion" | "minecraft:splash_potion" | "minecraft:lingering_potion" + ) { + self.brewed.push(taken.clone()); + } + return; + } if self.slots[s].role == Role::MerchantResult { self.merchant_take(env); return; @@ -1671,7 +1685,7 @@ impl Menu { max_amount: u32, ) -> Option { let mut result = self.try_remove(env, s, amount, max_amount)?; - self.on_take(env, s); + self.on_take(env, s, &result); if self.slots[s].role == Role::CartoResult { Self::map_crafted(env, &mut result); } @@ -2346,7 +2360,7 @@ impl Menu { return None; } if after_take || matches!(self.kind, Kind::Inventory | Kind::Crafting) { - self.on_take(env, index); + self.on_take(env, index, &clicked); } // What the result slot's move left over is dropped. if (index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting)) @@ -2594,7 +2608,7 @@ impl Menu { }; if let Some(mut taken) = self.try_remove(env, s, amount, u32::MAX) { self.carried = Some(taken.clone()); - self.on_take(env, s); + self.on_take(env, s, &taken); if self.slots[s].role == Role::CartoResult { // onTake's onCraftedBy edits the carried stack. Self::map_crafted(env, &mut taken); @@ -2628,7 +2642,7 @@ impl Menu { if let Some(c) = self.carried.as_mut() { c.count += taken.count; } - self.on_take(env, s); + self.on_take(env, s, &taken); if self.slots[s].role == Role::CartoResult { // onCraftedBy edits the taken stack, not the carried one. Self::map_crafted(env, &mut taken); @@ -2656,7 +2670,7 @@ impl Menu { if self.may_pickup(env, target) { self.containers[PLAYER][inv_slot] = Some(taken.clone()); self.set_by_player(env, target, None); - self.on_take(env, target); + self.on_take(env, target, &taken); if self.slots[target].role == Role::CartoResult && let Some(stack) = self.containers[PLAYER][inv_slot].as_mut() { @@ -2684,14 +2698,14 @@ impl Menu { let part = split(&mut source, max); self.containers[PLAYER][inv_slot] = Some(source); self.set_by_player(env, target, Some(part)); - self.on_take(env, target); + self.on_take(env, target, &taken); if !self.inventory_add(env, &mut taken) { self.drop_stack(&taken); } } else { - self.containers[PLAYER][inv_slot] = Some(taken); + self.containers[PLAYER][inv_slot] = Some(taken.clone()); self.set_by_player(env, target, Some(source)); - self.on_take(env, target); + self.on_take(env, target, &taken); } } } diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 48d2f08bd..7594e7e31 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -38,6 +38,8 @@ pub struct Vertex { pub light: u32, /// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour. pub normal: [i8; 4], + /// The `GLINT_TEXTURING` atlas UV for a foil item quad; zero elsewhere. + pub glint_uv: [f32; 2], } /// A section vertex: vanilla's `DefaultVertexFormat.BLOCK` (position, colour, /// UV0, UV2) with the sprite's array layer beside the light, in 24 bytes diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 50ce01f9f..cd8962754 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -11,6 +11,7 @@ pub mod ambient; pub mod anim; pub mod animal_brain; pub mod aquatic; +pub mod armadillo; pub mod axolotl; pub mod bat; pub mod bee; @@ -25,14 +26,18 @@ pub mod creaking; pub mod creaking_heart; pub mod cube; pub mod data; +pub mod dolphin; pub mod doors; pub mod drops; pub mod enderman; pub mod equine; pub mod farm; pub mod finalize; +pub mod fox; +pub mod frog; pub mod gear; pub mod goals; +pub mod goat; pub mod golem; pub mod guardian; pub mod happy_ghast; @@ -47,6 +52,7 @@ pub mod monster_brain; pub mod nautilus; pub mod nav; pub mod nether; +pub mod panda; pub mod path; pub mod phantom; pub mod piglin; @@ -66,6 +72,7 @@ pub mod spawning; pub mod species; pub mod strider; pub mod sulfur_cube; +pub mod sync; pub mod tame; pub mod trader; pub mod transport_items; @@ -796,12 +803,16 @@ pub struct Extra { /// A goat's `IsScreamingGoat` and the horns it lost (left, right). pub screaming: bool, pub lost_horns: [bool; 2], + /// A goat's lowered head and ram behaviours. + pub goat: goat::State, /// Attribute bases and permanent modifiers set by `finalizeSpawn`. pub attributes: Option>, /// Brain memories `finalizeSpawn` sets: (memory, value, ticks to expiry). pub memories: Vec<(&'static str, i64, i64)>, /// A camel's `LAST_POSE_CHANGE_TICK`. pub pose_change_tick: i64, + /// `Entity.DATA_POSE` as a mob of a server has it (`sync::pose_id`). + pub pose: u8, /// The school leader a fish follows, and a tropical fish that swims alone. pub leader: Option, pub lone: bool, @@ -809,6 +820,12 @@ pub struct Extra { pub brain: Option>, /// A bee's nectar, anger, flower and hive state. pub bee: Option>, + /// An armadillo's state and scare brain. + pub armadillo: armadillo::State, + /// A frog's brain memories and tongue target. + pub frog: frog::State, + /// A panda's flags, counters and amounts. + pub panda: Option>, } #[derive(Clone, Debug)] pub struct Mob { @@ -845,6 +862,9 @@ pub struct Mob { pub previous_swell: i32, pub ambient_timer: i32, pub fall_distance: f64, + /// `Entity.pistonDeltas` and `pistonDeltasGameTime`: how far a moving + /// block has pushed this mob this tick (0.51 at most on any axis). + pub piston: horizon_world::piston_movement::PistonMovement, pub persistent: bool, /// `CustomName` (plain text) and `CustomNameVisible`. pub custom_name: Option, @@ -917,6 +937,12 @@ pub enum MobEvent { mob: u32, at: [f64; 3], }, + /// `Level.broadcastEntityEvent` for a mob: guests run `sync::entity_event`. + EntityEvent { + mob: u32, + event: i8, + at: [f64; 3], + }, Sound(&'static str, [f64; 3], f32, f32), /// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the /// chest's opener count goes up or down (interaction range 3). @@ -940,6 +966,10 @@ pub enum MobEvent { slot: usize, stack: Option, }, + /// `InfestedMobEffect.onMobHurt`: the mob was hurt while infested. + Infested { + mob: u32, + }, /// `OfferFlowerGoal.stop`: the item goes to the target's antenna (saddle) /// slot if it is empty, as a guaranteed drop. Gift { @@ -982,6 +1012,16 @@ pub enum MobEvent { state: horizon_world::registry::BlockStateId, }, AttackPlayer(f32, [f64; 3]), + /// A melee hit whose effect comes only if the hit lands (husk hunger, + /// cave spider poison, wither skeleton wither, bee and pufferfish + /// poison): a shield-blocked hit gives nothing. + AttackPlayerWithEffect { + amount: f32, + from: [f64; 3], + effect: &'static str, + ticks: i32, + amplifier: i32, + }, /// Damage of a given type to the player (guardian lasers, thorns). DamagePlayer { amount: f32, @@ -1023,13 +1063,22 @@ pub enum MobEvent { mob: u32, charged: bool, }, - Explode([f64; 3], f32), + /// The centre, the radius and the kind of the mob blowing up (it may be + /// gone from the list by the time the blast is handled). + Explode([f64; 3], f32, Species), /// Melee or ranged damage to another mob. AttackMob { target: u32, amount: f32, source: Damage, }, + /// `LivingEntity.knockback(power, x, z)`: pushed away from the direction. + Knockback { + target: Who, + power: f64, + x: f64, + z: f64, + }, /// Set another mob's attack target (HurtByTargetGoal alerts). SetTarget { mob: u32, @@ -1087,8 +1136,11 @@ pub enum MobEvent { at: [f64; 3], count: u32, }, - /// Client particles about a mob's box (`particles::around_self`). + /// Client particles about a mob's box (`particles::around_self`) and the + /// entity event `event` that shows them, sent for mob `mob`. AroundSelf { + mob: u32, + event: i8, kind: &'static str, feet: [f64; 3], width: f64, @@ -1107,6 +1159,12 @@ pub enum MobEvent { }, /// Regeneration support after an axolotl-assisted kill. AxolotlSupportPlayer, + /// A dolphin that was given a fish asks the game for the nearest + /// shipwreck or ocean ruin (`DolphinSwimToTreasureGoal.start`): the game + /// sets the dolphin's `extra.home` to it, or leaves it empty. + DolphinTreasure { + mob: u32, + }, /// Apply an effect to the player (witch potions, bee stings, cave spider poison). EffectPlayer { effect: &'static str, @@ -1216,6 +1274,12 @@ pub enum MobEvent { table: &'static str, at: [f64; 3], }, + /// `Armadillo.customServerAiStep`: the armadillo sheds a scute. + ShedScute { + mob: u32, + at: [f64; 3], + pitch: f32, + }, /// A lead snaps or loses its holder: the lead item drops when asked. LeashBreak { mob: u32, @@ -1264,6 +1328,10 @@ pub enum MobEvent { center: [f64; 3], spread: [f64; 3], }, + /// `Panda.afterSneeze`: the grown pandas within 10 blocks start. + PandaSneezed { + mob: u32, + }, } /// How a spawned-by-kind mob should be set up. #[derive(Clone, Debug, Default)] @@ -1301,6 +1369,8 @@ pub struct Seen { pub target: Option, pub health: f32, pub variant: u8, + /// A slime's or magma cube's size. + pub size: i32, /// Dye colour (sheep). pub color: u8, /// A villager's claimed job site and bed. @@ -1320,6 +1390,8 @@ pub struct Seen { pub active_raid: bool, /// A copper golem's `openedChestPos` (`ContainerUser.hasContainerOpen`). pub opened_chest: Option<[i32; 3]>, + /// `isPassenger`. + pub passenger: bool, /// A villager's reputation of the player (`getPlayerReputation`). pub player_rep: i32, /// `isPushable` and pushed by others (`Entity.push(Entity)` moves it). @@ -1344,6 +1416,8 @@ pub struct Seen { pub sitting: bool, /// `Entity.isVehicle` or `isPassenger`. pub ridden: bool, + /// `Attributes.KNOCKBACK_RESISTANCE`. + pub knockback_resistance: f64, /// The active effects, without namespace (`slowness`, `poison`...). pub effects: Vec<&'static str>, } @@ -1400,6 +1474,7 @@ impl Mob { target: m.ai.target, health: m.health, variant: m.extra.variant, + size: m.extra.size, color: m.extra.color, job: villager.then_some(m.extra.home).flatten(), bed: villager.then_some(m.extra.bed).flatten(), @@ -1411,6 +1486,7 @@ impl Mob { hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), active_raid: raider::has_active_raid(m), opened_chest: m.extra.opened_chest, + passenger: m.extra.mount.is_some(), player_rep: match (villager, player) { (true, Some(uuid)) => villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid)), _ => 0, @@ -1430,6 +1506,7 @@ impl Mob { ], sitting: m.extra.sitting, ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(), + knockback_resistance: m.attrs.knockback_resistance, effects: m .extra .effects @@ -1564,11 +1641,15 @@ pub struct PlayerView { pub alive: bool, pub creative: bool, pub sneaking: bool, + /// `Entity.isSwimming`. + pub swimming: bool, pub look: [f64; 3], pub main_hand: Option>, pub off_hand: Option>, pub head: Option>, pub armor_cover: f32, + /// The Invisibility effect (`isInvisible`). + pub invisible: bool, pub spectator: bool, /// `PiglinAi.isWearingSafeArmor`: some golden armour. pub gold_armor: bool, @@ -1578,6 +1659,9 @@ pub struct PlayerView { pub last_hurt: Option<(Who, i64)>, pub velocity: Vec3, pub yaw: f32, + /// `Player.isSprinting` and `isPassenger` (what scares an armadillo). + pub sprinting: bool, + pub riding: bool, /// The Hero of the Village effect. pub hero: bool, /// The active effects, without namespace (`slowness`, `poison`...). @@ -1590,8 +1674,21 @@ pub struct PlayerView { /// A LAN guest: its own client moves it, and touching mobs push it there /// (`EntitySelector.pushableBy` on the client). pub remote: bool, + /// `isPassenger`. + pub passenger: bool, } impl PlayerView { + /// `LivingEntity.getVisibilityPercent` without the worn-skull scaling. + pub fn visibility_percent(&self) -> f64 { + let mut visibility = 1.0; + if self.sneaking { + visibility *= 0.8; + } + if self.invisible { + visibility *= 0.7 * f64::from(self.armor_cover).max(0.1); + } + visibility + } /// `LivingEntity.hasEffect`, by id without namespace. pub fn has_effect(&self, effect: &str) -> bool { self.effects.contains(&effect) @@ -1602,6 +1699,8 @@ pub struct MobWorld<'a> { pub world: &'a World, pub registry: &'a horizon_world::registry::BlockRegistry, pub facts: &'a BlockFacts, + /// Fluid states and flow facts, for the currents that push mobs. + pub fluid_tables: &'a crate::motion::FluidResources, pub movement: &'a horizon_world::movement_properties::BoundMovementProperties, pub collision: &'a BlockCollisionRegistry<'a>, pub data: &'a MobData, @@ -1624,7 +1723,10 @@ pub struct MobWorld<'a> { pub biomes: &'a crate::biome::Biomes, /// The `mob_griefing` game rule. pub mob_griefing: bool, - /// `getCurrentDifficultyAt` near the player. + /// The `mob_drops` game rule (`shouldDropLoot`). + pub mob_drops: bool, + /// `getCurrentDifficultyAt` at the mob being ticked (near the player + /// outside the mob tick). pub difficulty: spawning::LocalDifficulty, /// The End (its dimension type's monster spawn light rules). pub end: bool, @@ -1637,6 +1739,8 @@ pub struct MobWorld<'a> { pub teams: std::sync::Arc>, /// Item data (max stack sizes), when the host has it. pub items: Option<&'a crate::items::Items>, + /// `ChestBlockEntity.getOpenCount`: the players with each chest open. + pub lid_openers: &'a HashMap<(i32, i32, i32), i32>, } /// `Entity.getTeam` of the player and of the mobs on a team. #[derive(Clone, Debug, Default)] @@ -1690,6 +1794,7 @@ impl Mob { // Mob.ambientSoundTime starts at 0. ambient_timer: 0, fall_distance: 0.0, + piston: Default::default(), persistent: false, random, ai: Box::default(), @@ -1802,8 +1907,14 @@ impl Mob { /// the last-hurt-by bookkeeping goals read. /// The `armor` and `armor_toughness` modifiers of worn humanoid armour. pub fn worn_armor(&self) -> (f32, f32) { + // An equine keeps its horse armor in `extra.head`: the item's `armor` + // and `armor_toughness` modifiers of the body slot. if equine::is_equine(self.species()) { - return (0.0, 0.0); + return self + .extra + .head + .as_deref() + .map_or((0.0, 0.0), spawning::horse_armor_stats); } [ &self.extra.head, @@ -1844,6 +1955,9 @@ impl Mob { return false; } let mut amount = if reflected { 1000.0 } else { amount }; + if self.species() == Species::Armadillo { + amount = armadillo::reduce_damage(self, amount); + } if source.kind == DamageKind::FallingBlock && !species::body_slot(self.species()) && self.extra.head.is_some() @@ -1860,9 +1974,15 @@ impl Mob { amount *= 5.0; } let (worn, worn_toughness) = self.worn_armor(); - if !source.bypasses_armor() && self.kind.armor + worn > 0.0 { + // Shulker.setRawPeekAmount: a closed shell adds the covered armor modifier. + let covered = if self.species() == Species::Shulker && self.extra.counter == 0 { + 20.0 + } else { + 0.0 + }; + if !source.bypasses_armor() && self.kind.armor + worn + covered > 0.0 { // CombatRules.getDamageAfterAbsorb - let armor = self.kind.armor + worn; + let armor = self.kind.armor + worn + covered; let toughness = 2.0 + (self.kind.armor_toughness + worn_toughness) / 4.0; let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0); let mut fraction = effective / 25.0; @@ -1920,7 +2040,7 @@ impl Mob { let dead = !self.alive(); let sound = ai::voice_sounds(self)[if dead { 2 } else { 1 }]; if !dead { - self.ambient_timer = -self.kind.ambient_interval; + self.ambient_timer = -self.ambient_interval(); } if !sound.is_empty() { let pitch = self.voice_pitch(); @@ -1931,6 +2051,9 @@ impl Mob { } } } + if self.has_effect("minecraft:infested") { + self.outbox.push(MobEvent::Infested { mob: self.id }); + } // 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() @@ -2001,16 +2124,21 @@ impl Mob { pub fn has_effect(&self, effect: &str) -> bool { self.extra.effects.iter().any(|e| e.0 == effect) } + /// `LivingEntity.isCurrentlyGlowing`: the Glowing effect or the `Glowing` tag (on a + /// server's client, `glowing` holds shared flag 6 instead). + pub fn is_currently_glowing(&self) -> bool { + self.glowing || self.has_effect("minecraft:glowing") + } pub fn add_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) { if let Some(e) = self.extra.effects.iter_mut().find(|e| e.0 == effect) { - // MobEffectInstance.update: a stronger effect replaces the old one - // with its own duration, an equal one keeps the longer duration, - // and a weaker one never changes the active effect. + // MobEffectInstance.update: a stronger effect replaces with its + // own duration, an equal one only extends it; a weaker one is + // ignored (vanilla keeps it hidden behind the active one). if amplifier > e.2 { e.1 = ticks; e.2 = amplifier; - } else if amplifier == e.2 { - e.1 = e.1.max(ticks); + } else if amplifier == e.2 && e.1 != -1 && (ticks == -1 || e.1 < ticks) { + e.1 = ticks; } } else { self.extra.effects.push((effect, ticks, amplifier)); @@ -2030,6 +2158,16 @@ impl Mob { let at = [self.position.x, self.eye_y(), self.position.z]; events.push(MobEvent::Sound(event, at, 1.0, 1.0)); } + /// `Mob.getAmbientSoundInterval`; `HappyGhast` waits six times as long + /// while it carries a passenger. + pub fn ambient_interval(&self) -> i32 { + let ridden = self.rider.is_some() || self.extra.rider.is_some(); + if self.species() == Species::HappyGhast && ridden { + self.kind.ambient_interval * 6 + } else { + self.kind.ambient_interval + } + } /// LivingEntity.getVoicePitch. pub fn voice_pitch(&mut self) -> f32 { // HappyGhast.getVoicePitch: always 1.0, babies and all. @@ -2154,6 +2292,7 @@ pub fn render_model( layer: overlay, color: 0xFFFF_FFFF, light, + glint_uv: [0.0, 0.0], }); } } @@ -2288,7 +2427,7 @@ mod lighting_tests { #[test] fn packed_normal_uses_native_snorm_bytes_without_changing_vertex_offsets() { assert_eq!(std::mem::offset_of!(Vertex, normal), 32); - assert_eq!(std::mem::size_of::(), 36); + assert_eq!(std::mem::size_of::(), 44); let part = plane([0.0, 1.0, 0.0]); assert_eq!( part.polygons[0].vertex_normal(ModelNormals::new(Mat4::from_scale(Vec3::ZERO))), diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 9adf93a8f..e1627e29f 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -106,6 +106,7 @@ pub enum Family { Strider, Bat, Bee, + Panda, PolarBear, } pub fn family(s: Species) -> Family { @@ -168,6 +169,7 @@ pub fn family(s: Species) -> Family { S::Strider => Family::Strider, S::Bat => Family::Bat, S::Bee => Family::Bee, + S::Panda => Family::Panda, S::PolarBear => Family::PolarBear, _ => Family::Generic, } @@ -180,20 +182,18 @@ pub fn register(m: &mut Mob) { Family::Undead => undead::register(m), Family::Hostile => hostile::register(m), Family::Aquatic => aquatic::register(m), + Family::Generic if m.species() == Species::Armadillo => super::armadillo::register(m), + Family::Generic if m.species() == Species::Frog => super::frog::register(m), + Family::Generic if m.species() == Species::Fox => super::fox::register(m), Family::Generic => { generic(m); if m.species() == Species::Rabbit { super::rabbit::register(m); } - if m.species() == Species::Turtle { - super::turtle::register(m); - } if m.species() == Species::Frog { // `Frog()`: SmoothSwimmingMoveControl(85, 10, 0.02, 0.1, true). - // The frog's movement speed is 1.0, so the controller's 0.1 - // outside-water speed is what keeps a walking frog at - // vanilla's pace; the plain ground controller walks ten - // times too fast (#2213). + // The speed attribute is 1.0, so the controller's scaling is + // what keeps a frog at a walking pace on land. m.ai.mov.kind = super::control::MoveKind::SmoothSwimming { max_turn_x: 85.0, max_turn_y: 10.0, @@ -202,6 +202,12 @@ pub fn register(m: &mut Mob) { gravity: true, }; } + if m.species() == Species::Turtle { + super::turtle::register(m); + } + if m.species() == Species::Goat { + super::goat::register(m); + } } Family::Inert => {} Family::Witch => super::witch::register(m), @@ -243,6 +249,7 @@ pub fn register(m: &mut Mob) { Family::Strider => super::strider::register(m), Family::Bat => super::bat::register(m), Family::Bee => super::bee::register(m), + Family::Panda => super::panda::register(m), Family::PolarBear => super::polar_bear::register(m), } // FloatGoal's constructor lets the navigation float, as do the @@ -321,12 +328,30 @@ fn generic(m: &mut Mob) { m.ai.targets.add(1, HurtByTarget::new()); m.ai.targets.add(2, NearestTarget::player(true)); } else { + if m.kind.species == Species::Goat { + // GoatAi's idle and core behaviours (the ram and long jump + // activities are not here): panic 2.0, AnimalMakeLove, tempting + // with goat_food and baby follow at 1.25, then stroll. + g.add(0, Float); + g.add(1, Panic::new(2.0)); + g.add(2, Breed::new(1.0)); + g.add(3, Tempt::new(1.25, m.kind.food.clone(), false)); + g.add(4, FollowParent::new(1.25)); + g.add(5, Stroll::avoiding_water(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); + return; + } g.add(0, Float); let rabbit = m.kind.species == Species::Rabbit; g.add(1, Panic::new(if rabbit { 2.2 } else { 1.25 })); g.add(5, Stroll::avoiding_water(if rabbit { 0.6 } else { 1.0 })); g.add(6, LookAtPlayer::new(6.0)); g.add(7, RandomLookAround::default()); + if m.kind.species == Species::Armadillo { + // Armadillo's constructor: pickNextScuteDropTime. + m.extra.egg_time = next_scute_time(m); + } } } /// Subclasses of `net.minecraft.world.entity.monster.Monster`. @@ -425,7 +450,10 @@ pub fn tick( } // Mob.tickHeadTurn -> BodyRotationControl.clientTick (a frozen // creaking's waits). - if m.alive() && (!super::creaking::is_creaking(m) || super::creaking::can_move(m)) { + if m.alive() + && (!super::creaking::is_creaking(m) || super::creaking::can_move(m)) + && !super::armadillo::scared(m) + { m.body_rotation_tick(); } events.append(&mut m.outbox); @@ -447,6 +475,9 @@ pub fn tick( if m.species() == Species::Bee { super::bee::tick(m, level_random); } + if m.species() == Species::Panda { + super::panda::tick(m, w, events); + } true } /// LivingEntity.updateSwingTime (6-tick swing duration). @@ -609,7 +640,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let t = m.ambient_timer; m.ambient_timer += 1; if roll < t { - m.ambient_timer = -m.kind.ambient_interval; + m.ambient_timer = -m.ambient_interval(); play_ambient(m, w, events); } } @@ -752,6 +783,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & .is_some_and(|t| t.position.distance_squared(m.position) > 121.0); super::witch::ai_step(m, events, far); } + if m.species() == Species::Fox { + super::fox::pre_ai_step(m); + } // AbstractHorse.aiStep: the tail swishes now and then (moveTail). if super::equine::is_equine(m.species()) { super::equine::tail_tick(m); @@ -1054,9 +1088,35 @@ fn server_ai_step( } m.jump_control_tick(); } +/// `Armadillo.pickNextScuteDropTime`: 5 to 10 minutes. +fn next_scute_time(m: &mut Mob) -> i32 { + m.random.next_int_bound(20 * 60 * 5).unwrap_or(0) + 20 * 60 * 5 +} +/// `Armadillo.customServerAiStep`: the scute timer keeps counting down and is +/// only reset once `shouldDropLoot` (not a baby, `mob_drops` on) lets it shed. +fn armadillo_server_ai_step(m: &mut Mob, mob_drops: bool, events: &mut Vec) { + if !m.alive() { + return; + } + m.extra.egg_time -= 1; + if m.extra.egg_time <= 0 && !m.is_baby() && mob_drops { + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + events.push(MobEvent::ShedScute { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + pitch, + }); + m.extra.egg_time = next_scute_time(m); + } +} fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { match m.species() { Species::Rabbit => super::rabbit::server_ai_step(m), + // Armadillo.customServerAiStep: the brain and its activity, then the scute. + Species::Armadillo => { + super::armadillo::server_ai_step(m, cx); + armadillo_server_ai_step(m, cx.w.mob_drops, cx.events); + } Species::Sheep => {} Species::Zombie | Species::Husk @@ -1077,6 +1137,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1, Species::Bat => super::bat::server_ai_step(m, cx.w, cx.events), Species::Bee => super::bee::server_ai_step(m, cx), + Species::Frog => super::frog::server_ai_step(m, cx.w), _ => {} } } @@ -1130,6 +1191,10 @@ fn species_ai_step( } Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Armadillo => super::armadillo::tick(m), + Species::Frog => super::frog::tick(m), + Species::Goat => super::goat::tick(m), + Species::Fox => super::fox::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; @@ -1149,6 +1214,19 @@ pub fn despawn_check(m: &mut Mob, w: &MobWorld) -> bool { } true } +/// `Mob.requiresCustomPersistence` and its overrides: a passenger or a leashed +/// mob, a raider in a raid, an enderman carrying a block, a tame nautilus, a +/// sulfur cube holding a block or let out of a bucket. The spawn caps do not +/// count these mobs either (`NaturalSpawner.createState`). +pub fn requires_custom_persistence(m: &Mob) -> bool { + super::riders::keeps_alive(m) + || m.extra.leash.is_some() + || super::raider::state(m).is_some_and(|s| s.raid_id.is_some()) + || m.species() == Species::Enderman && m.extra.carried.is_some() + || super::nautilus::is_nautilus(m.species()) && m.extra.tame + || m.species() == Species::SulfurCube + && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0) +} /// Mob.checkDespawn, before the tick (players are the only despawn /// reference). Returns false when the mob is discarded. fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { @@ -1164,12 +1242,7 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { return true; }; let d = m.distance_sqr(p); - // requiresCustomPersistence: raiders in a raid, a tame nautilus, a sulfur - // cube holding a block or let out of a bucket. - let persistent = m.persistent - || super::nautilus::is_nautilus(m.species()) && m.extra.tame - || m.species() == Species::SulfurCube - && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0); + let persistent = m.persistent || requires_custom_persistence(m); // removeWhenFarAway: animals, villagers, golems, patrols and raiders, // zombie villagers being cured and ridden mobs stay. let creature = m.kind.category == "creature"; @@ -1240,6 +1313,18 @@ pub fn voice_sounds(m: &Mob) -> [&'static str; 3] { match m.species() { Species::Nautilus | Species::ZombieNautilus => super::nautilus::sounds(m), Species::SulfurCube => super::sulfur_cube::sounds(m), + Species::Armadillo => super::armadillo::sounds(m), + // Panda.getAmbientSound. + Species::Panda => { + let ambient = if super::panda::is_aggressive(m) { + "entity.panda.aggressive_ambient" + } else if super::panda::is_worried(m) { + "entity.panda.worried_ambient" + } else { + m.kind.sounds[0] + }; + [ambient, m.kind.sounds[1], m.kind.sounds[2]] + } // The sound variant's baby_sounds (classic sets, like the rest here). Species::Pig if m.is_baby() => [ "entity.baby_pig.ambient", @@ -1262,6 +1347,10 @@ pub fn feed_animal( m: &mut Mob, level: &mut impl RandomSource, ) -> Option> { + // Armadillo.mobInteract: a ball takes no food. + if super::armadillo::scared(m) { + return None; + } if m.extra.age == 0 && m.extra.in_love <= 0 { m.extra.in_love = 600; m.extra.love_player = true; @@ -1438,6 +1527,11 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { super::bee::hurt(m); true } + // Panda.hurtServer: up first, whatever the damage. + Species::Panda => { + super::panda::hurt(m); + true + } Species::Enderman => super::enderman::on_damage(m, source), Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider if source.is_fire() => @@ -1452,6 +1546,7 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) { m.ai.no_action_time = 0; match m.species() { Species::Enderman => super::enderman::after_hurt(m, source), + Species::Armadillo => super::armadillo::after_hurt(m, source), Species::Shulker => super::shulker::after_hurt(m), Species::Warden => super::warden::hurt(m, source), Species::Wolf => super::tame::after_hurt(m, source), @@ -1465,7 +1560,16 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) { // PiglinAi.wasHurtBy: drop what is being admired, no admiring for // a while after a player's hit, and anger. Species::Piglin if source.attacker == Some(Who::Player) => { - m.extra.using_item = 0; + // stopHoldingOffHandItem(.., false): a gold ingot is not bartered + // and is gone; anything else ends its admiring next tick, as if + // the time ran out, and the game side puts it away. + if m.extra.off_hand.as_deref() == Some("minecraft:gold_ingot") { + m.extra.off_hand = None; + m.extra.using_item = 0; + } else { + m.extra.using_item = + i32::from(m.extra.off_hand.is_some() && m.extra.using_item > 0); + } m.extra.egg_time = 400; m.extra.anger = 600; } @@ -1489,24 +1593,37 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if m.species() == Species::Ravager { super::ravager::on_attack(m, cx.events); } + if m.species() == Species::Panda { + super::panda::bit(m); + } if super::creaking::is_creaking(m) { super::creaking::on_attack(m, cx.events); } let mut amount = m.attrs.attack_damage; let from = [m.position.x, m.position.y, m.position.z]; let source = Damage::mob(m.id, from); + let first_event = cx.events.len(); match m.species() { - // Difficulty NORMAL: cave spiders poison for 7 seconds. - Species::CaveSpider if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { - effect: "minecraft:poison", - ticks: 7 * 20, - amplifier: 0, - }), - Species::Husk if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { - effect: "minecraft:hunger", - ticks: 140, - amplifier: 0, - }), + // CaveSpider.doHurtTarget: poison for 7 s on normal, 15 s on hard. + Species::CaveSpider if who == Who::Player && cx.w.difficulty.base >= 2 => { + cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:poison", + ticks: if cx.w.difficulty.base == 2 { 7 } else { 15 } * 20, + amplifier: 0, + }) + } + // Husk.doHurtTarget: hunger for 140 ticks per whole point of the + // local difficulty, only with an empty main hand. + Species::Husk if who == Who::Player && m.extra.main_hand.is_none() => { + let ticks = 140 * cx.w.difficulty.effective as i32; + if ticks > 0 { + cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:hunger", + ticks, + amplifier: 0, + }) + } + } Species::WitherSkeleton if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { effect: "minecraft:wither", ticks: 200, @@ -1556,7 +1673,28 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { }); } match who { - Who::Player => cx.events.push(MobEvent::AttackPlayer(amount, from)), + // The effect picked above goes with the hit: it applies only when + // the player takes damage (a shield-blocked hit gives none). + Who::Player => { + let effect = cx.events[first_event..] + .iter() + .position(|e| matches!(e, MobEvent::EffectPlayer { .. })) + .map(|k| cx.events.remove(first_event + k)); + cx.events.push(match effect { + Some(MobEvent::EffectPlayer { + effect, + ticks, + amplifier, + }) => MobEvent::AttackPlayerWithEffect { + amount, + from, + effect, + ticks, + amplifier, + }, + _ => MobEvent::AttackPlayer(amount, from), + }); + } Who::Mob(id) => cx.events.push(MobEvent::AttackMob { target: id, amount, @@ -1567,6 +1705,12 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if super::creaking::is_creaking(m) { m.voice("entity.creaking.attack", cx.events); } + // Panda.playAttackSound: playSound(PANDA_BITE, 1.0, 1.0). + if m.species() == Species::Panda && !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events + .push(MobEvent::Sound("entity.panda.bite", at, 1.0, 1.0)); + } // Axolotl.playAttackSound: playSound(AXOLOTL_ATTACK, 1.0, 1.0). if m.species() == Species::Axolotl { let at = [m.position.x, m.position.y, m.position.z]; @@ -1656,25 +1800,31 @@ fn tick_effects(m: &mut Mob) { let mut effects = std::mem::take(&mut m.extra.effects); for (effect, ticks, amp) in &mut effects { let interval = |base: i32| (base >> (*amp).max(0)).max(1); + // MobEffectInstance.tickServer: an infinite (-1) effect times its + // ticks by the mob's tickCount and never counts down. + let infinite = *ticks == -1; + let count = if infinite { m.age as i32 } else { *ticks }; match *effect { "minecraft:poison" - if *ticks % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => + if count % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => { m.damage(1.0, Damage::of(DamageKind::Magic)); } - "minecraft:wither" if *ticks % interval(40) == 0 => { + "minecraft:wither" if count % interval(40) == 0 => { m.damage(1.0, Damage::of(DamageKind::Magic)); } "minecraft:regeneration" - if *ticks % interval(50) == 0 && !m.kind.flags.undead && m.alive() => + if count % interval(50) == 0 && !m.kind.flags.undead && m.alive() => { m.health = (m.health + 1.0).min(m.attrs.max_health); } _ => {} } - *ticks -= 1; + if !infinite { + *ticks -= 1; + } } - effects.retain(|e| e.1 > 0); + effects.retain(|e| e.1 > 0 || e.1 == -1); m.extra .hidden_effects .retain(|h| effects.iter().any(|e| e.0 == *h)); diff --git a/crates/horizon-client/src/mobs/allay.rs b/crates/horizon-client/src/mobs/allay.rs index 029ddb6e5..22461945d 100644 --- a/crates/horizon-client/src/mobs/allay.rs +++ b/crates/horizon-client/src/mobs/allay.rs @@ -133,6 +133,11 @@ pub fn ai_step(m: &mut Mob) { if m.extra.egg_time > 0 { m.extra.egg_time -= 1; } + animate(m); +} +/// `Allay.tick`'s client half: the hold and spin clocks (the server's and a +/// client's). +pub fn animate(m: &mut Mob) { let holding = m.extra.main_hand.is_some(); let v = &mut m.anim.v; v[HOLD] = (v[HOLD] + if holding { 1.0 } else { -1.0 }).clamp(0.0, 5.0); diff --git a/crates/horizon-client/src/mobs/ambient.rs b/crates/horizon-client/src/mobs/ambient.rs index cb4146e08..94589ffab 100644 --- a/crates/horizon-client/src/mobs/ambient.rs +++ b/crates/horizon-client/src/mobs/ambient.rs @@ -2,8 +2,10 @@ //! `level().isClientSide()` branches of `aiStep`: nothing of it reaches the //! server or goes over the network, so the window's game runs it, whether it //! simulates the world (in-frame) or follows a server. -use super::{Mob, MobEvent, Species}; +use super::{Mob, MobEvent, Species, bee}; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; +use std::f32::consts::PI; /// `Enderman.aiStep`, `Endermite.aiStep` and `Blaze.aiStep` on a client: /// two portal particles a tick around endermen and endermites; two large @@ -53,3 +55,67 @@ pub fn client_ai_step(m: &mut Mob, out: &mut Vec) { out.push(MobEvent::ParticleAt { kind, at, velocity }); } } + +/// `Phantom.tick` and `Bee.tick` on a client, which draw from the client +/// level's random (`random`) and never from the mob's own, so a window that +/// simulates the world keeps the mob's draws as the server has them: a +/// phantom's wings leave mycelium dust, a bee carrying nectar now and then +/// drips it. +pub fn client_particles(m: &Mob, random: &mut impl RandomSource, out: &mut Vec) { + match m.species() { + Species::Phantom => { + // The wings flap every phantom in a different phase + // (`getUniqueFlapTickOffset`). + let flap = ((m.id.wrapping_mul(3).wrapping_add(m.age)) as i32 as f32 + * 7.448451 + * (PI / 180.0) + + PI) + .mcos(); + let width = m.width() * 1.48; + let yaw = m.yaw * (PI / 180.0); + let (c, s) = (yaw.mcos() * width, yaw.msin() * width); + let h = (0.3 + flap * 0.45) * m.height() * 2.5; + let p = m.position; + for (dx, dz) in [(c, s), (-c, -s)] { + out.push(MobEvent::ParticleAt { + kind: "mycelium", + at: [p.x + f64::from(dx), p.y + f64::from(h), p.z + f64::from(dz)], + velocity: [0.0; 3], + }); + } + } + Species::Bee => { + if !bee::has_nectar(m) + || !bee::get(m).is_some_and(|b| b.crops_grown < 10) + || random.next_float() >= 0.05 + { + return; + } + // `for (i = 0; i < nextInt(2) + 1; i++)` rolls the bound each time. + let mut i = 0; + while i < random.next_int_bound(2).unwrap_or(0) + 1 { + // Mth.lerp(level.random.nextDouble(), x - 0.3F, x + 0.3F). + let spread = f64::from(0.3_f32); + let lerp = |delta: f64, from: f64, to: f64| from + delta * (to - from); + let x = lerp( + random.next_double(), + m.position.x - spread, + m.position.x + spread, + ); + let z = lerp( + random.next_double(), + m.position.z - spread, + m.position.z + spread, + ); + out.push(MobEvent::ParticleAt { + kind: "falling_nectar", + // getY(0.5). + at: [x, m.position.y + f64::from(m.height()) * 0.5, z], + velocity: [0.0; 3], + }); + i += 1; + } + } + _ => {} + } +} diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index bd0eb9c90..d928c34ee 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -625,8 +625,7 @@ fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { // TargetingConditions.forNonCombat(): in range (scaled by the // player's visibility, at least 2) and in sight. let Some(p) = &w.player else { return false }; - let visibility = if p.sneaking { 0.8 } else { 1.0 }; - let r = (range * visibility).max(2.0); + let r = (range * p.visibility_percent()).max(2.0); p.alive && !p.spectator && m.distance_sqr(p.position) <= r * r && m.sees(w, who) } Who::Mob(id) => { diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 59a73c605..fdc543e08 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -128,9 +128,12 @@ pub fn register(m: &mut Mob) { let g = &mut m.ai.goals; g.add(0, BreathAir); g.add(0, TryFindWater::default()); + g.add(1, super::dolphin::SwimToTreasure::default()); + g.add(2, super::dolphin::SwimWithPlayer::new(4.0)); g.add(4, Stroll::swimming(1.0, 10)); g.add(4, RandomLookAround::default()); g.add(5, LookAtPlayer::new(6.0)); + g.add(5, super::dolphin::Jump::new(10)); g.add(6, MeleeAttack::new(1.2, true)); m.ai.targets.add(1, HurtByTarget::new().alert()); m.ai.mov.kind = MoveKind::SmoothSwimming { @@ -244,11 +247,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { && m.ai.no_action_time % 10 == 0 { let amount = 1.0 + m.extra.size as f32; - events.push(MobEvent::AttackPlayer( + // Only when the sting hurt the player. + events.push(MobEvent::AttackPlayerWithEffect { amount, - [m.position.x, m.position.y, m.position.z], - )); - events.push(MobEvent::EffectPlayer { + from: [m.position.x, m.position.y, m.position.z], effect: "minecraft:poison", ticks: 60 * m.extra.size, amplifier: 0, diff --git a/crates/horizon-client/src/mobs/armadillo.rs b/crates/horizon-client/src/mobs/armadillo.rs new file mode 100644 index 000000000..8837d8cf8 --- /dev/null +++ b/crates/horizon-client/src/mobs/armadillo.rs @@ -0,0 +1,407 @@ +//! Armadillos (`Armadillo`, `ArmadilloAi`): a player who sprints or rides +//! nearby, an undead mob or the last attacker scares one into a ball (IDLE, +//! ROLLING, SCARED, UNROLLING); it peeks out now and then, and a ball takes +//! less damage. The brain's `ARMADILLO_SCARE_DETECTED` sensor, its +//! `DANGER_DETECTED_RECENTLY` memory and the `ArmadilloBallUp` behaviour are +//! kept in `State`; the walking behaviours are the goals of `register`. +//! AnimState states: roll out, roll up, peek. +use super::{ + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, + goals::{ + Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone, + }, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +pub const IDLE: u8 = 0; +pub const ROLLING: u8 = 1; +pub const SCARED: u8 = 2; +pub const UNROLLING: u8 = 3; + +const ROLL_OUT: usize = 0; +const ROLL_UP: usize = 1; +const PEEK: usize = 2; + +/// `ArmadilloState.animationDuration`. +fn animation_duration(state: u8) -> i32 { + match state { + ROLLING => 10, + SCARED => 50, + UNROLLING => 30, + _ => 0, + } +} + +/// `Armadillo.ARMADILLO_STATE` and the brain's memory and behaviour. +#[derive(Clone, Debug, Default)] +pub struct State { + pub state: u8, + /// `inStateTicks`. + pub in_state_ticks: i32, + /// `DANGER_DETECTED_RECENTLY`: ticks to live, 0 when absent. + danger: i32, + /// Ticks to the sensor's next scan. + sensor: i32, + /// `ArmadilloBallUp`: running, its peek timer and whether it saw the + /// danger around last tick. + ball_up: bool, + next_peek: i32, + danger_was_around: bool, + /// Whether the PANIC activity was the active one after the last tick. + panic_activity: bool, + /// `peekReceivedClient`. + peek_received: bool, +} + +pub fn register(m: &mut Mob) { + let mut panic = Panic::new(2.0); + panic.environmental = true; + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, ArmadilloPanic(panic)); + g.add(2, Rolled); + g.add(5, Stroll::avoiding_water(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); +} + +/// `Armadillo.isScared`. +pub fn scared(m: &Mob) -> bool { + m.extra.armadillo.state != IDLE +} +/// `ArmadilloState.shouldHideInShell`: the model shows its shell. +pub fn hiding_in_shell(m: &Mob) -> bool { + let a = &m.extra.armadillo; + match a.state { + ROLLING => a.in_state_ticks > 5, + SCARED => true, + UNROLLING => a.in_state_ticks < 26, + _ => false, + } +} +/// `Armadillo.getState`, as it is synched. +pub fn state(m: &Mob) -> u8 { + m.extra.armadillo.state +} +/// `Armadillo.switchToState` and `onSyncedDataUpdated(ARMADILLO_STATE)`. +pub fn set_state(m: &mut Mob, state: u8) { + let a = &mut m.extra.armadillo; + if a.state != state { + a.state = state; + a.in_state_ticks = 0; + } +} +/// `Armadillo.canStayRolledUp`. +fn can_stay_rolled_up(m: &Mob) -> bool { + !m.ai.panicking + && !m.fluids.in_water + && !m.fluids.in_lava + && m.extra.leash.is_none() + && m.extra.mount.is_none() + && m.extra.rider.is_none() +} +/// `Entity.playSound(sound)`. +fn play(m: &Mob, events: &mut Vec, sound: &'static str) { + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound(sound, at, 1.0, 1.0)); + } +} +/// `Armadillo.rollUp`. +fn roll_up(m: &mut Mob, events: &mut Vec) { + if !scared(m) { + super::creaking::stop_in_place(m); + m.extra.in_love = 0; + if !m.silent { + m.voice("entity.armadillo.roll", events); + } + set_state(m, ROLLING); + } +} +/// `Armadillo.rollOut`. +fn roll_out(m: &mut Mob, events: &mut Vec) { + if scared(m) { + if !m.silent { + m.voice("entity.armadillo.unroll_finish", events); + } + set_state(m, IDLE); + } +} + +/// `Armadillo.hurtServer`: a ball takes half of the damage past the first +/// point. +pub fn reduce_damage(m: &Mob, amount: f32) -> f32 { + if scared(m) { + ((amount - 1.0) / 2.0).max(0.0) + } else { + amount + } +} +/// `Armadillo.actuallyHurt`: a hit by a living thing curls it up (and keeps +/// the danger in mind for 80 ticks), a hit by fire and the like unrolls it. +pub fn after_hurt(m: &mut Mob, source: &Damage) { + if m.no_ai || m.health <= 0.0 { + return; + } + let mut events = Vec::new(); + if source.attacker.is_some() { + m.extra.armadillo.danger = 80; + if can_stay_rolled_up(m) { + roll_up(m, &mut events); + } + } else if environmental(source.kind) { + roll_out(m, &mut events); + } + m.outbox.append(&mut events); +} +/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES`. +pub fn environmental(kind: DamageKind) -> bool { + matches!( + kind, + DamageKind::Cactus | DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava + ) +} +/// The hurt sound: a ball's is muffled, and it has no ambient sound +/// (`getAmbientSound`, `getHurtSound`); empty is none. +pub fn sounds(m: &Mob) -> [&'static str; 3] { + let [ambient, hurt, death] = m.kind.sounds; + if scared(m) { + ["", "entity.armadillo.hurt_reduced", death] + } else { + [ambient, hurt, death] + } +} + +/// `EntityTypeTags.UNDEAD`. +fn undead(s: Species) -> bool { + matches!( + s, + Species::Skeleton + | Species::Stray + | Species::WitherSkeleton + | Species::SkeletonHorse + | Species::Bogged + | Species::Parched + | Species::ZombieHorse + | Species::CamelHusk + | Species::Zombie + | Species::ZombieVillager + | Species::ZombifiedPiglin + | Species::Zoglin + | Species::Drowned + | Species::Husk + | Species::ZombieNautilus + | Species::Wither + | Species::Phantom + ) +} +/// `Armadillo.isScaredBy` for the nearby living entities: within 7 blocks +/// sideways and 2 up and down, an undead mob, the last attacker, or a +/// player who sprints or rides. +fn scared_by_someone(m: &Mob, w: &MobWorld) -> bool { + let area = m.bounds().inflate(Vec3::new(7.0, 2.0, 7.0)); + let attacker = + m.ai.last_hurt_by + .filter(|_| m.age as i32 - m.ai.last_hurt_by_time <= 100); + if let Some(p) = &w.player + && p.alive + && !p.spectator + && p.bounds.intersects(area) + && (attacker == Some(Who::Player) || p.sprinting || p.riding) + { + return true; + } + w.others_near(area).any(|s| { + s.id != m.id + && s.alive + && s.bounds.intersects(area) + && (undead(s.species) || attacker == Some(Who::Mob(s.id))) + }) +} + +/// `Armadillo.customServerAiStep`'s brain: memories expire, the scare +/// sensor scans every fifth tick, the core's rolling out, then the +/// `ArmadilloBallUp` behaviour of the PANIC activity. +pub fn server_ai_step(m: &mut Mob, cx: &mut Cx) { + let events = &mut *cx.events; + let a = &mut m.extra.armadillo; + if a.danger > 0 { + a.danger -= 1; + } + a.sensor -= 1; + if a.sensor <= 0 { + a.sensor = 5; + if !can_stay_rolled_up(m) { + m.extra.armadillo.danger = 0; + } else if scared_by_someone(m, cx.w) { + m.extra.armadillo.danger = 80; + } + } + // ARMADILLO_ROLLING_OUT: no danger left in mind. + if m.extra.armadillo.danger == 0 && scared(m) { + roll_out(m, events); + } + if m.extra.armadillo.panic_activity && !m.extra.armadillo.ball_up && m.on_ground && !liquid(m) { + // ArmadilloBallUp.start. + m.extra.armadillo.ball_up = true; + roll_up(m, events); + } + if m.extra.armadillo.ball_up { + ball_up_tick(m, events); + } + let a = &mut m.extra.armadillo; + a.panic_activity = a.danger > 0 && !m.ai.panicking; +} +fn liquid(m: &Mob) -> bool { + m.fluids.in_water || m.fluids.in_lava +} +/// `ArmadilloBallUp.tickOrStop`. +fn ball_up_tick(m: &mut Mob, events: &mut Vec) { + if !scared(m) { + // canStillUse is false: stop. + m.extra.armadillo.ball_up = false; + if !can_stay_rolled_up(m) { + roll_out(m, events); + } + return; + } + let a = &mut m.extra.armadillo; + if a.next_peek > 0 { + a.next_peek -= 1; + } + if a.state == ROLLING && a.in_state_ticks > animation_duration(ROLLING) { + set_state(m, SCARED); + if m.on_ground { + play(m, events, "entity.armadillo.land"); + } + return; + } + let danger = m.extra.armadillo.danger; + let around = danger > 75; + if around != m.extra.armadillo.danger_was_around { + m.extra.armadillo.next_peek = next_peek_timer(m); + } + m.extra.armadillo.danger_was_around = around; + let state = m.extra.armadillo.state; + if state == SCARED { + if m.extra.armadillo.next_peek == 0 && m.on_ground && around { + peek(m, events); + m.extra.armadillo.next_peek = next_peek_timer(m); + } + if danger < animation_duration(UNROLLING) { + play(m, events, "entity.armadillo.unroll_start"); + set_state(m, UNROLLING); + } + } else if state == UNROLLING && danger > animation_duration(UNROLLING) { + set_state(m, SCARED); + } +} +/// `ArmadilloBallUp.pickNextPeekTimer`. +fn next_peek_timer(m: &mut Mob) -> i32 { + animation_duration(SCARED) + m.random.next_int_between_inclusive(100, 400).unwrap_or(100) +} +/// `level.broadcastEntityEvent(body, 64)`; the sound is the client's +/// `playLocalSound`, which the server plays for everyone here. +fn peek(m: &mut Mob, events: &mut Vec) { + entity_event(m, 64); + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 64, + at, + }); + events.push(MobEvent::Sound("entity.armadillo.peek", at, 1.0, 1.0)); +} +/// `Armadillo.handleEntityEvent`: 64 is a peek. +pub fn entity_event(m: &mut Mob, event: u8) { + if event == 64 { + m.extra.armadillo.peek_received = true; + } +} + +/// `Armadillo.tick`: the animation states on a client, the ball's head held +/// to its body, and `inStateTicks`. Server and client both run it. +pub fn tick(m: &mut Mob) { + animate(m); + if scared(m) { + // clampHeadRotationToBody with getMaxHeadYRot 0. + m.head_yaw += super::living::wrap(m.body_yaw - m.head_yaw); + } + m.extra.armadillo.in_state_ticks += 1; +} +/// `Armadillo.setupAnimationStates`. +fn animate(m: &mut Mob) { + let age = m.age as f32; + let a = &mut m.extra.armadillo; + let s = &mut m.anim.states; + match a.state { + ROLLING => { + s[ROLL_OUT].stop(); + s[ROLL_UP].start_if_stopped(age); + s[PEEK].stop(); + } + SCARED => { + s[ROLL_OUT].stop(); + s[ROLL_UP].stop(); + if a.peek_received { + s[PEEK].stop(); + a.peek_received = false; + } + if a.in_state_ticks == 0 { + s[PEEK].start(age); + s[PEEK].fast_forward(animation_duration(SCARED)); + } else { + s[PEEK].start_if_stopped(age); + } + } + UNROLLING => { + s[ROLL_OUT].start_if_stopped(age); + s[ROLL_UP].stop(); + s[PEEK].stop(); + } + _ => { + s[ROLL_OUT].stop(); + s[ROLL_UP].stop(); + s[PEEK].stop(); + } + } +} + +/// `ArmadilloAi.ArmadilloPanic`: it unrolls, then runs. +#[derive(Clone, Debug)] +struct ArmadilloPanic(Panic); +impl Goal for ArmadilloPanic { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn name(&self) -> &'static str { + "Panic" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + roll_out(m, cx.events); + self.0.start(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx); + } +} +/// The behaviours that do not run while the armadillo is a ball: its +/// `MoveToTargetSink` and the idle activity's walking and looking. +#[derive(Clone, Debug)] +struct Rolled; +impl Goal for Rolled { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + scared(m) + } +} diff --git a/crates/horizon-client/src/mobs/bee.rs b/crates/horizon-client/src/mobs/bee.rs index 27d8e7c84..e8e3ae0ae 100644 --- a/crates/horizon-client/src/mobs/bee.rs +++ b/crates/horizon-client/src/mobs/bee.rs @@ -103,6 +103,17 @@ pub fn has_stung(m: &Mob) -> bool { pub fn rolling(m: &Mob) -> bool { flag(m, FLAG_ROLL) } +/// A client's bee from the server's `DATA_FLAGS_ID` and `DATA_ANGER_END_TIME` +/// (the texture and the roll read them). +pub fn set_synced(m: &mut Mob, flags: Option, anger_end: Option) { + let b = st(m); + if let Some(flags) = flags { + b.flags = flags; + } + if let Some(anger_end) = anger_end { + b.anger_end = anger_end; + } +} /// `Bee.setHasNectar`: nectar resets the time without it. pub fn set_has_nectar(m: &mut Mob, value: bool) { if value { @@ -322,13 +333,24 @@ pub fn sting(m: &mut Mob, who: Who, cx: &mut Cx) { let amount = (m.attrs.attack_damage as i32) as f32; match who { Who::Player => { - cx.events.push(MobEvent::AttackPlayer(amount, from)); - let seconds = if cx.w.difficulty.hard { 18 } else { 10 }; - cx.events.push(MobEvent::EffectPlayer { - effect: "minecraft:poison", - ticks: seconds * 20, - amplifier: 0, - }); + // Bee.doHurtTarget: the poison only when the sting hurt, and + // only on normal (10 s) and hard (18 s). + let seconds = match cx.w.difficulty.id { + 2 => 10, + 3 => 18, + _ => 0, + }; + if seconds > 0 { + cx.events.push(MobEvent::AttackPlayerWithEffect { + amount, + from, + effect: "minecraft:poison", + ticks: seconds * 20, + amplifier: 0, + }); + } else { + cx.events.push(MobEvent::AttackPlayer(amount, from)); + } } Who::Mob(id) => cx.events.push(MobEvent::AttackMob { target: id, @@ -421,10 +443,10 @@ pub fn drop_off_nectar(m: &mut Mob) { set_has_nectar(m, false); st(m).crops_grown = 0; } -/// `Bee.setStayOutOfHiveCountdown`, which in 26.3 only resets the time -/// without nectar. +/// `Bee.setStayOutOfHiveCountdown`: the bee will not enter a hive for 400 +/// ticks (the hive passes that when a sedated hive lets its bees out). pub fn set_stay_out_of_hive_countdown(m: &mut Mob) { - st(m).ticks_without_nectar = 0; + st(m).stay_out_of_hive = 400; } fn drop_hive(m: &mut Mob) { let b = st(m); diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 360e1447f..3f458085b 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -59,11 +59,11 @@ pub struct Goat { pub ramming_x_head_rot: f32, } impl Goat { - pub fn from_mob(_m: &Mob) -> Self { + pub fn from_mob(m: &Mob) -> Self { Self { - left_horn: true, - right_horn: true, - ramming_x_head_rot: 0.0, + left_horn: !m.extra.lost_horns[0], + right_horn: !m.extra.lost_horns[1], + ramming_x_head_rot: super::goat::ramming_x_head_rot(m), } } } @@ -960,7 +960,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { match m.species() { Species::Goat => goat(p, s, &Goat::from_mob(m)), Species::PolarBear => polar_bear(p, s, super::polar_bear::standing_scale(m, s.partial)), - Species::Panda => panda(p, s, &Panda::default()), + Species::Panda => panda(p, s, &super::panda::pose(m, s.partial)), Species::Llama | Species::TraderLlama => { llama(p, s, m.extra.chested && !s.baby); } @@ -1008,7 +1008,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { p, s, &Armadillo { - hiding_in_shell: false, + hiding_in_shell: super::armadillo::hiding_in_shell(m), roll_out: st[0], roll_up: st[1], peek: st[2], @@ -1029,7 +1029,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { a, ), Species::Rabbit => rabbit(p, s, &st[0], &st[1], a), - Species::Fox => fox(p, s, &Fox::default(), a), + Species::Fox => fox(p, s, &super::fox::pose(m, s.partial), a), _ => return false, } true diff --git a/crates/horizon-client/src/mobs/breeze.rs b/crates/horizon-client/src/mobs/breeze.rs index 5d78fa8ab..dee48f3d0 100644 --- a/crates/horizon-client/src/mobs/breeze.rs +++ b/crates/horizon-client/src/mobs/breeze.rs @@ -31,6 +31,28 @@ pub fn pose(m: &Mob) -> u8 { pub(super) fn set_pose(m: &mut Mob, pose: u8) { m.extra.variant3 = pose; } +/// `Pose.id` of the pose (`sync::pose_id`), and its inverse. +pub fn pose_id(m: &Mob) -> u8 { + match pose(m) { + SHOOTING => 16, + INHALING => 17, + LONG_JUMPING => 6, + SLIDING => 15, + _ => 0, + } +} +pub(super) fn set_pose_id(m: &mut Mob, id: u8) { + set_pose( + m, + match id { + 16 => SHOOTING, + 17 => INHALING, + 6 => LONG_JUMPING, + 15 => SLIDING, + _ => STANDING, + }, + ); +} /// `Breeze.getFiringYPosition`. pub fn firing_y(m: &Mob) -> f64 { m.position.y + f64::from(m.height()) / 2.0 + f64::from(0.3_f32) diff --git a/crates/horizon-client/src/mobs/camel.rs b/crates/horizon-client/src/mobs/camel.rs index 21ebe9e16..427b4c5ca 100644 --- a/crates/horizon-client/src/mobs/camel.rs +++ b/crates/horizon-client/src/mobs/camel.rs @@ -24,12 +24,13 @@ pub fn register(m: &mut Mob) { m.extra.tame = true; let tempt = m.kind.tempt.clone(); let g = &mut m.ai.goals; + // CamelAi speed modifiers (times the 0.09 movement speed attribute). g.add(0, Float); - g.add(1, CamelPanic(Panic::new(4.0 * 0.25))); + g.add(1, CamelPanic(Panic::new(4.0))); g.add(2, Breed::new(1.0)); - g.add(3, Tempt::new(2.5 * 0.25, tempt, false)); - g.add(4, FollowParent::new(2.5 * 0.25)); - g.add(5, Stroll::new(2.0 * 0.25)); + g.add(3, Tempt::new(2.5, tempt, false)); + g.add(4, FollowParent::new(2.5)); + g.add(5, Stroll::new(2.0)); g.add(5, RandomSitting); g.add(6, LookAtPlayer::new(6.0)); g.add(7, RandomLookAround::default()); @@ -45,6 +46,25 @@ pub fn sitting(m: &Mob) -> bool { fn in_transition(m: &Mob) -> bool { pose_time(m) < if sitting(m) { SIT_DOWN } else { STAND_UP } } +/// `Camel.getPoseTime` of a client mob from the `LAST_POSE_CHANGE_TICK` it +/// was sent and the client's game time, and whether that value says it sits. +fn client_pose(m: &Mob, game_time: i64) -> (i64, bool) { + let tick = m.extra.pose_change_tick; + (game_time - tick.abs(), tick < 0) +} +/// The camel's `LAST_POSE_CHANGE_TICK` as the server sends it: in game time +/// (a mob counts its own age), negative while sitting. +pub fn synced_pose_tick(m: &Mob, game_time: i64) -> i64 { + let tick = (game_time - pose_time(m)).max(0); + if sitting(m) { -tick.max(1) } else { tick } +} +/// `Entity.onSyncedDataUpdated` for the pose tick of a client mob: its sign +/// is whether it sits. `client_tick` keeps `egg_time` (in the mob's age, for +/// `sitting` and `refuse_to_move`) with it. +pub fn set_synced_pose_tick(m: &mut Mob, tick: i64) { + m.extra.pose_change_tick = tick; + m.extra.egg_time = if tick < 0 { -1 } else { 0 }; +} /// `Camel.refuseToMove`: sitting or getting up or down. pub fn refuse_to_move(m: &Mob) -> bool { sitting(m) || in_transition(m) @@ -166,7 +186,29 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { m.ai.zza = 0.0; m.ai.nav.stop(); } - // setupAnimationStates. + animation_states(m, pose_time(m), sitting(m)); +} +/// `Camel.tick` on a client that is not the server: the dash cooldown, which +/// the dash flag starts, and the keyframe states from the synced pose tick. +pub fn client_tick(m: &mut Mob, game_time: i64) { + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } + let (pose_time, sitting) = client_pose(m, game_time); + let since = (i64::from(m.age) - pose_time).max(0) as i32; + m.extra.egg_time = if sitting { -since.max(1) } else { since }; + animation_states(m, pose_time, sitting); +} +/// `Camel.onSyncedDataUpdated(DASH)`: a dash starts the cooldown unless it +/// runs. Not on the first tick. +pub fn set_dashing(m: &mut Mob, dashing: bool) { + if m.age > 0 && m.extra.anim_ticks == 0 { + m.extra.anim_ticks = DASH_COOLDOWN; + } + m.extra.flag2 = dashing; +} +/// `Camel.setupAnimationStates` for a pose time and whether it sits. +fn animation_states(m: &mut Mob, pose_time: i64, sitting: bool) { let age = m.age as f32; if m.extra.ints[0] <= 0 { m.extra.ints[0] = m.random.next_int_bound(40).unwrap_or(0) + 80; @@ -175,9 +217,9 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { m.extra.ints[0] -= 1; } // isCamelVisuallySitting: (poseTime < 0) != sitting. - let visually_sitting = (pose_time(m) < 0) != sitting(m); - let sitting_down = sitting(m) && pose_time(m) < SIT_DOWN && pose_time(m) >= 0; - let transition = in_transition(m) && pose_time(m) >= 0; + let visually_sitting = (pose_time < 0) != sitting; + let sitting_down = sitting && (0..SIT_DOWN).contains(&pose_time); + let transition = (0..if sitting { SIT_DOWN } else { STAND_UP }).contains(&pose_time); let dashing = m.extra.flag2; let st = &mut m.anim.states; if visually_sitting { diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index bd17d7b5f..b142188da 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -146,6 +146,16 @@ impl Mob { if self.species() == super::Species::Rabbit { return super::rabbit::move_control(self, w); } + // Fox.FoxMoveControl.tick: still while asleep, sitting or faceplanted. + if self.species() == super::Species::Fox && !super::fox::can_move(self) { + return; + } + // Panda.PandaMoveControl: only while it can act. + if self.species() == super::Species::Panda + && !super::panda::can_perform_action(self, w.thundering) + { + return; + } if self.species() == super::Species::Turtle { return super::turtle::move_control(self); } @@ -328,6 +338,11 @@ impl Mob { /// LookControl.tick (and SmoothSwimmingLookControl). pub fn look_control_tick(&mut self) { let look = self.ai.look.clone(); + let fox = self.species() == super::Species::Fox; + // Fox.FoxLookControl: no turning in sleep. + if fox && super::fox::flag(self, super::fox::SLEEPING) { + return; + } if look.kind == LookKind::HappyGhast { return super::happy_ghast::look_control(self); } @@ -374,7 +389,8 @@ impl Mob { // clampHeadRotationToBody does nothing for a shulker. } LookKind::Default | LookKind::Fixed => { - if look.kind == LookKind::Default { + // FoxLookControl.resetXRotOnTick keeps a stalking or pouncing pitch. + if look.kind == LookKind::Default && (!fox || super::fox::resets_x_rot(self)) { self.head_pitch = 0.0; } if look.cooldown > 0 { @@ -417,6 +433,13 @@ impl Mob { } /// BodyRotationControl.clientTick (Mob.tickHeadTurn). pub fn body_rotation_tick(&mut self) { + // Shulker.ShulkerBodyRotationControl.clientTick is empty: the body + // stays at 0 (recreateFromPacket), only the head turns. + if self.species() == super::Species::Shulker { + self.body_yaw = 0.0; + self.previous_body_yaw = 0.0; + return; + } let dx = self.position.x - self.previous.x; let dz = self.position.z - self.previous.z; let max = self.kind.max_head_y_rot; diff --git a/crates/horizon-client/src/mobs/copper_golem.rs b/crates/horizon-client/src/mobs/copper_golem.rs index 5f4ffba13..c5e0dbece 100644 --- a/crates/horizon-client/src/mobs/copper_golem.rs +++ b/crates/horizon-client/src/mobs/copper_golem.rs @@ -70,6 +70,16 @@ pub fn sound(m: &Mob, what: &str) -> &'static str { } /// `CopperGolem.setupAnimationStates` (client) and the sound of the head spin. pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { + if animate(m) { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::LocalSound(sound(m, "spin"), at, 1.0, 1.0)); + } +} +/// `CopperGolem.setupAnimationStates`, for the server and a client alike; +/// returns whether the head spin sound plays now (a client's sound is the +/// server's `LocalSound`). +pub fn animate(m: &mut Mob) -> bool { + let mut spin = false; let age = m.age as f32; let state = m.extra.variant3; let st = &mut m.anim.states; @@ -93,8 +103,7 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { m.extra.ints[0] = tick + 200 + r.next_int_bound(40).unwrap_or(0); } if tick == m.extra.ints[0] + 10 { - let at = [m.position.x, m.position.y, m.position.z]; - events.push(MobEvent::LocalSound(sound(m, "spin"), at, 1.0, 1.0)); + spin = true; m.extra.ints[0] = 0; } } @@ -106,6 +115,7 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { } _ => {} } + spin } /// `CopperGolem.updateWeathering` on the level random: the first tick sets /// the next weathering tick, which advances the weather state; once diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs index fd6248d2b..e23cd817c 100644 --- a/crates/horizon-client/src/mobs/creaking.rs +++ b/crates/horizon-client/src/mobs/creaking.rs @@ -152,8 +152,26 @@ pub fn sway(m: &mut Mob, events: &mut Vec) { } /// `Creaking.doHurtTarget`: the attack animation (the sound is the /// `playAttackSound` that ends `Mob.doHurtTarget`). -pub fn on_attack(m: &mut Mob, _events: &mut Vec) { +pub fn on_attack(m: &mut Mob, events: &mut Vec) { m.extra.ints[ATTACKING] = ATTACK_TICKS; + broadcast(m, 4, events); +} +/// `Level.broadcastEntityEvent` for a creaking (guests run `entity_event`). +fn broadcast(m: &Mob, event: i8, events: &mut Vec) { + events.push(MobEvent::EntityEvent { + mob: m.id, + event, + at: [m.position.x, m.position.y, m.position.z], + }); +} +/// `Creaking.handleEntityEvent` on a client: 66 the invulnerability flash, +/// 4 the attack swing (the sounds are the server's). +pub fn entity_event(m: &mut Mob, event: u8) { + match event { + 66 => m.extra.ints[INVULNERABLE] = INVULNERABILITY_TICKS, + 4 => m.extra.ints[ATTACKING] = ATTACK_TICKS, + _ => {} + } } /// The heart this creaking is bound to protects it (`isProtector`); a link /// read from a save is trusted until the heart resolves it. @@ -176,15 +194,12 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if heart_bound(m) && m.alive() && !protected(m, w) { m.health = 0.0; } - for slot in [INVULNERABLE, ATTACKING] { - if m.extra.ints[slot] > 0 { - m.extra.ints[slot] -= 1; - } + // hurtServer set the invulnerability clock since the last tick: entity + // event 66. + if m.extra.ints[INVULNERABLE] == INVULNERABILITY_TICKS { + broadcast(m, 66, events); } - let age = m.age as f32; - m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age); - m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age); - m.anim.states[2].animate_when(tearing_down(m), age); + animate(m); if m.extra.counter & HURT != 0 { // hurtServer: sway, and the heart reacts to a player's hit. if protected(m, w) { @@ -200,18 +215,6 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } m.extra.counter &= !(HURT | HURT_BY_PLAYER); } - // checkEyeBlink: the eyes of a creaking falling apart flicker. - if m.death_time > m.extra.ints[NEXT_FLICKER] { - let glowing = m.extra.ints[EYES] != 0; - let (lo, hi) = if glowing { - (2, 8) - } else { - (m.death_time / 4, m.death_time / 2) - }; - let span = (hi - lo + 1).max(1); - m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0); - m.extra.ints[EYES] = i32::from(!glowing); - } if !m.alive() { return; } @@ -226,6 +229,31 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.extra.flag2 = !now; } } +/// The clocks and keyframe states `Creaking.aiStep`, `setupAnimationStates` +/// and `checkEyeBlink` run (the server's and a client's). +pub fn animate(m: &mut Mob) { + for slot in [INVULNERABLE, ATTACKING] { + if m.extra.ints[slot] > 0 { + m.extra.ints[slot] -= 1; + } + } + let age = m.age as f32; + m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age); + m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age); + m.anim.states[2].animate_when(tearing_down(m), age); + // checkEyeBlink: the eyes of a creaking falling apart flicker. + if m.death_time > m.extra.ints[NEXT_FLICKER] { + let glowing = m.extra.ints[EYES] != 0; + let (lo, hi) = if glowing { + (2, 8) + } else { + (m.death_time / 4, m.death_time / 2) + }; + let span = (hi - lo + 1).max(1); + m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0); + m.extra.ints[EYES] = i32::from(!glowing); + } +} /// `Mob.stopInPlace`. pub fn stop_in_place(m: &mut Mob) { m.nav_stop(); diff --git a/crates/horizon-client/src/mobs/dolphin.rs b/crates/horizon-client/src/mobs/dolphin.rs new file mode 100644 index 000000000..c9948f6fb --- /dev/null +++ b/crates/horizon-client/src/mobs/dolphin.rs @@ -0,0 +1,265 @@ +//! Dolphin goals: `DolphinSwimToTreasureGoal`, `DolphinSwimWithPlayerGoal` +//! and `DolphinJumpGoal`. `extra.flag` is `gotFish` and `extra.home` the +//! `treasurePos` the game found for it (`MobEvent::DolphinTreasure`). +use super::{ + Mob, MobEvent, Who, + goals::{Cx, Goal, JUMP, LOOK, MOVE, goal_clone, reduced}, +}; +use crate::blocks::Fluid; +use horizon_core::random::RandomSource; + +/// `Entity.getMotionDirection`: the horizontal step of the yaw +/// (`Direction.fromYRot`: south, west, north, east). +fn motion_step(yaw: f32) -> [i32; 2] { + match (yaw / 90.0 + 0.5).floor() as i32 & 3 { + 0 => [0, 1], + 1 => [-1, 0], + 2 => [0, -1], + _ => [1, 0], + } +} + +/// `DolphinSwimToTreasureGoal`: a dolphin that was fed a fish leads the way to +/// a shipwreck or an ocean ruin within 50 sectors. +#[derive(Clone, Debug, Default)] +pub struct SwimToTreasure { + stuck: bool, +} +impl SwimToTreasure { + /// `BlockPos.containing(x, dolphin.getY(), z).closerToCenterThan(position, 4)`. + fn arrived(m: &Mob) -> bool { + let Some(t) = m.extra.home else { return false }; + let d = [ + f64::from(t[0]) + 0.5 - m.position.x, + m.position.y.floor() + 0.5 - m.position.y, + f64::from(t[2]) + 0.5 - m.position.z, + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < 16.0 + } +} +impl Goal for SwimToTreasure { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn interruptable(&self) -> bool { + false + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.flag && m.air >= 100 + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.home.is_some() && !Self::arrived(m) && !self.stuck && m.air >= 100 + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.stuck = false; + m.nav_stop(); + // The game looks for the structure and sets the position, or none. + m.extra.home = None; + cx.events.push(MobEvent::DolphinTreasure { mob: m.id }); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + if m.extra.home.is_none() || Self::arrived(m) || self.stuck { + m.extra.flag = false; + } + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(t) = m.extra.home else { return }; + let close = m.ai.nav.target_pos.is_some_and(|p| { + let d = [ + f64::from(p[0]) + 0.5 - m.position.x, + f64::from(p[1]) + 0.5 - m.position.y, + f64::from(p[2]) + 0.5 - m.position.z, + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < 144.0 + }); + if !close && !m.ai.nav.is_done() { + return; + } + let treasure = [ + f64::from(t[0]) + 0.5, + f64::from(t[1]) + 0.5, + f64::from(t[2]) + 0.5, + ]; + let eighth = f64::from(std::f32::consts::FRAC_PI_8); + let half = f64::from(std::f32::consts::FRAC_PI_2); + let mut next = m.default_random_pos_towards(cx.w, 16, 1, treasure, eighth); + if next.is_none() { + next = m.default_random_pos_towards(cx.w, 8, 4, treasure, half); + } + // isPathfindable(WATER) is a water fluid state. + if let Some(n) = next + && cx.w.fluid( + n[0].floor() as i32, + n[1].floor() as i32, + n[2].floor() as i32, + ) != Fluid::Water + { + next = m.default_random_pos_towards(cx.w, 8, 5, treasure, half); + } + let Some(next) = next else { + self.stuck = true; + return; + }; + let (y, x) = (m.kind.max_head_y_rot + 20.0, m.kind.max_head_x_rot); + m.look_at_speed(next, y, x); + m.nav_move_to(cx.w, next, 1.3); + if m.random.next_int_bound(80).unwrap_or(1) == 0 { + // Entity event 38: happy villager particles about the dolphin. + cx.events.push(MobEvent::AroundSelf { + mob: m.id, + event: 38, + kind: "happy_villager", + feet: [m.position.x, m.position.y, m.position.z], + width: f64::from(m.width()), + height: f64::from(m.height()), + burst: crate::particles::Burst::DOLPHIN, + }); + } + } +} + +/// `DolphinSwimWithPlayerGoal`: swim up to a swimming player and give them +/// Dolphin's Grace. +#[derive(Clone, Debug)] +pub struct SwimWithPlayer { + speed: f64, +} +impl SwimWithPlayer { + pub fn new(speed: f64) -> Self { + Self { speed } + } +} +impl Goal for SwimWithPlayer { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // getNearestPlayer(forNonCombat().range(10).ignoreLineOfSight()). + m.can_see_player_through_walls(cx.w, 10.0) + && cx.w.player.as_ref().is_some_and(|p| p.swimming) + && m.ai.target != Some(Who::Player) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + cx.w.player + .as_ref() + .is_some_and(|p| p.swimming && m.distance_sqr(p.position) < 256.0) + } + fn start(&mut self, _: &mut Mob, cx: &mut Cx) { + cx.events.push(grace()); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.nav_stop(); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = cx.w.player.clone() else { return }; + let (y, x) = (m.kind.max_head_y_rot + 20.0, m.kind.max_head_x_rot); + m.look_at_speed(p.eye, y, x); + if m.distance_sqr(p.position) < 6.25 { + m.nav_stop(); + } else { + m.nav_move_to_entity( + cx.w, + [p.position.x, p.position.y, p.position.z], + 1, + self.speed, + ); + } + if p.swimming && m.random.next_int_bound(6).unwrap_or(1) == 0 { + cx.events.push(grace()); + } + } +} +/// `MobEffectInstance(DOLPHINS_GRACE, 100)`. +fn grace() -> MobEvent { + MobEvent::EffectPlayer { + effect: "minecraft:dolphins_grace", + ticks: 100, + amplifier: 0, + } +} + +/// `DolphinJumpGoal`: leap out of clear water and arc back in. +#[derive(Clone, Debug)] +pub struct Jump { + interval: i32, + breached: bool, +} +impl Jump { + pub fn new(interval: i32) -> Self { + Self { + interval: reduced(interval), + breached: false, + } + } +} +impl Goal for Jump { + goal_clone!(); + fn flags(&self) -> u8 { + JUMP | MOVE + } + fn interruptable(&self) -> bool { + false + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.random.next_int_bound(self.interval).unwrap_or(1) != 0 { + return false; + } + let [sx, sz] = motion_step(m.yaw); + let (bx, by, bz) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let w = cx.w; + [0, 1, 4, 5, 6, 7].into_iter().all(|i| { + let (x, z) = (bx + sx * i, bz + sz * i); + // waterIsClear, then surfaceIsClear. + w.fluid(x, by, z) == Fluid::Water + && !w.has_tag("minecraft:blocks_dolphin_jump", w.block_name(x, by, z)) + && w.facts.is_air(w.world.block(x, by + 1, z)) + && w.facts.is_air(w.world.block(x, by + 2, z)) + }) + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + let yd = m.velocity.y; + (yd * yd >= f64::from(0.03f32) + || m.head_pitch == 0.0 + || m.head_pitch.abs() >= 10.0 + || !m.fluids.in_water) + && !m.on_ground + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let [sx, sz] = motion_step(m.yaw); + m.velocity.x += f64::from(sx) * 0.6; + m.velocity.y += 0.7; + m.velocity.z += f64::from(sz) * 0.6; + m.nav_stop(); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.head_pitch = 0.0; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let already = self.breached; + if !already { + self.breached = cx.w.fluid( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ) == Fluid::Water; + } + if self.breached && !already { + m.sound("entity.dolphin.jump", cx.events); + } + let v = m.velocity; + if v.y * v.y < f64::from(0.03f32) && m.head_pitch != 0.0 { + // Mth.rotLerp(0.2, xRot, 0). + m.head_pitch += 0.2 * super::living::wrap(0.0 - m.head_pitch); + } else if v.length() > f64::from(1.0e-5f32) { + let horizontal = v.x.hypot(v.z); + m.head_pitch = ((-v.y).atan2(horizontal) * f64::from(180.0f32) + / f64::from(std::f32::consts::PI)) as f32; + } + } +} diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index 064cf0583..e20f991c1 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -244,7 +244,13 @@ pub fn slot_item(m: &Mob, slot: &str) -> Option { } _ => (None, None), }; - let mut stack = loot_stack(item?, 1); + // A panda keeps the whole stack it picked up in its mouth. + let count = if slot == "mainhand" && m.species() == Species::Panda { + super::panda::held_count(m) + } else { + 1 + }; + let mut stack = loot_stack(item?, count as i32); if let (Some(index), Some(g)) = (index, gear::gear(m)) { for (e, l) in &g.slots[index] { stack.enchantments.push((e.to_string(), *l as i32)); @@ -305,6 +311,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), } } /// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the @@ -403,6 +410,15 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec (Vec 0 { + out.push(Drop::Item(loot_stack(&item, carried))); + } + if let Some(stack) = slot_item(m, "mainhand") + && !d.loot.prevents_equipment_drop(&stack) + { + out.push(Drop::Item(stack)); + clear_slot(m, "mainhand"); + } + } // Piglin.dropCustomDeathLoot: everything in its inventory. if s == Species::Piglin { for stack in m.extra.inventory.drain(..) { @@ -482,13 +511,7 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec false, - Species::Hoglin => true, - s if is_monster(s) => true, - _ => !m.is_baby(), - }; - if killed_by_player && drops_experience && d.mob_drops { + if killed_by_player && drops_experience(m) && d.mob_drops { let mut amount = base_experience(m); while amount > 0 { let value = orb_value(amount); @@ -512,6 +535,16 @@ fn roll( None => Vec::new(), } } +/// `LivingEntity.shouldDropExperience`: babies drop none, except monsters and +/// hoglins; tadpoles never do. +pub fn drops_experience(m: &Mob) -> bool { + match m.species() { + Species::Tadpole => false, + Species::Hoglin => true, + s if is_monster(s) => true, + _ => !m.is_baby(), + } +} /// `getBaseExperienceReward` (no vanilla enchantment changes mob experience). pub fn base_experience(m: &mut Mob) -> i32 { use Species as S; diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index 17566fb65..b2ca6db9f 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -97,10 +97,26 @@ pub fn teleport_to( return false; } let old = m.center(); + let old_block = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; m.position = Vec3::new(x, ny, z); m.previous = m.position; m.velocity = Vec3::ZERO; m.ai.nav.stop(); + if !m.silent { + // Level event 2018: the portal trail, from the old block to the new + // one, packed as `BlockUtil.clampedPackDifferenceInPosition` does. + let new_block = [x.floor() as i32, ny.floor() as i32, z.floor() as i32]; + let packed = |k: usize| ((new_block[k] - old_block[k]).clamp(-127, 127) + 127) & 255; + events.push(MobEvent::LevelEvent { + id: 2018, + pos: old_block, + data: packed(0) << 16 | packed(1) << 8 | packed(2), + }); + } events.push(MobEvent::Sound("entity.enderman.teleport", old, 1.0, 1.0)); events.push(MobEvent::Sound( "entity.enderman.teleport", diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index ccf4564ca..b3532726e 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1691,13 +1691,7 @@ impl Ctx<'_, L, R> { let hidden = panda_gene(self.int(16)); m.extra.variant = main; m.extra.variant2 = hidden; - let shown = panda_variant(main, hidden); - if shown == 5 { - set_base(m, Attr::MaxHealth, 10.0); - } - if shown == 1 { - set_base(m, Attr::MovementSpeed, f64::from(0.07f32)); - } + super::panda::set_attributes(m); self.ageable(m, g.or(Some(Group::Ageable(Ageable::chance(0.2))))) } S::PolarBear | S::Ocelot => { @@ -1950,7 +1944,7 @@ fn set_memory(m: &mut Mob, name: &'static str, value: i64, ttl: i64) { } /// `Panda.Gene.getRandom` (enum order: normal, lazy, worried, playful, /// brown, weak, aggressive). -fn panda_gene(roll: i32) -> u8 { +pub fn panda_gene(roll: i32) -> u8 { match roll { 0 => 1, 1 => 2, diff --git a/crates/horizon-client/src/mobs/fox.rs b/crates/horizon-client/src/mobs/fox.rs new file mode 100644 index 000000000..833002b46 --- /dev/null +++ b/crates/horizon-client/src/mobs/fox.rs @@ -0,0 +1,845 @@ +//! Foxes (`net.minecraft.world.entity.animal.fox.Fox`): the goal list, the +//! flags byte (sleeping, sitting, crouching, interested, pouncing, +//! faceplanted), stalking and pouncing, napping in the shade by day, seeking +//! shelter, perching, eating berries and the food held in the mouth. +//! Picking up items, strolling through villages and trusting players (with +//! defending them) are not ported yet. +use super::{ + Mob, MobEvent, MobWorld, Seen, Species, + goals::{ + Avoid, AvoidEntity, Breed, Cx, Float, FollowParent, Goal, JUMP, LOOK, LeapAtTarget, + LookAtPlayer, MOVE, MeleeAttack, MoveToBlock, NearestTarget, Panic, Prey, Stroll, + goal_clone, hide_pos, reduced, + }, + living::wrap, +}; +use horizon_core::{ + geometry::{Axis, Vec3}, + jmath, + random::RandomSource, +}; +use horizon_world::registry::BlockStateId; + +// Fox.DATA_FLAGS_ID, kept in `extra.ints[0]` (and sent to clients as is). +pub const SITTING: i32 = 1; +pub const CROUCHING: i32 = 4; +pub const INTERESTED: i32 = 8; +pub const POUNCING: i32 = 16; +pub const SLEEPING: i32 = 32; +pub const FACEPLANTED: i32 = 64; +pub const DEFENDING: i32 = 128; +/// `Fox.ticksSinceEaten`. +const TICKS_SINCE_EATEN: usize = 1; +/// `Fox.interestedAngle` and `crouchAmount` in `anim.v`, the previous tick's +/// values in `anim.vo`. +const INTERESTED_ANGLE: usize = 0; +const CROUCH_AMOUNT: usize = 1; +/// `Fox.MAX_CROUCH_AMOUNT`. +const MAX_CROUCH_AMOUNT: f32 = 5.0; + +pub fn flag(m: &Mob, f: i32) -> bool { + m.extra.ints[0] & f != 0 +} +fn set_flag(m: &mut Mob, f: i32, on: bool) { + if on { + m.extra.ints[0] |= f; + } else { + m.extra.ints[0] &= !f; + } +} +/// `Fox.clearStates`. +fn clear_states(m: &mut Mob) { + m.extra.ints[0] = 0; +} +/// `Fox.canMove`, which `FoxMoveControl` waits for. +pub fn can_move(m: &Mob) -> bool { + !flag(m, SLEEPING | SITTING | FACEPLANTED) +} +/// `FoxLookControl.resetXRotOnTick`: stalking and pouncing keep their pitch. +pub fn resets_x_rot(m: &Mob) -> bool { + !flag(m, POUNCING | CROUCHING | INTERESTED | FACEPLANTED) +} + +/// `Fox.registerGoals` and `setTargetGoals` (the targets wait for the variant: +/// red foxes prefer chickens and rabbits, snow foxes fish). +pub fn register(m: &mut Mob) { + let countdown = m.random.next_int_bound(reduced(140)).unwrap_or(0); + let g = &mut m.ai.goals; + g.add(0, Wrap::new(Float).on_start(clear_states)); + g.add(1, Faceplant { countdown: 0 }); + g.add(2, Panic::new(2.2)); + g.add(3, Wrap::new(Breed::new(1.0)).on_start(clear_states)); + // AVOID_PLAYERS: not a sneaking player. + g.add( + 4, + AvoidEntity::new(Avoid::Player, 16.0, 1.6, 1.4) + .player_when(|p| !p.sneaking && !p.spectator), + ); + g.add( + 4, + AvoidEntity::new(Avoid::Species(vec![Species::Wolf]), 8.0, 1.6, 1.4).seen_when(|s| !s.tame), + ); + g.add( + 4, + AvoidEntity::new(Avoid::Species(vec![Species::PolarBear]), 8.0, 1.6, 1.4), + ); + g.add(5, StalkPrey); + g.add(6, Pounce); + g.add(6, SeekShelter::new(1.25)); + g.add( + 7, + Wrap::new(MeleeAttack::new(1.2, true)) + .when( + |m| !flag(m, SITTING | SLEEPING | CROUCHING | FACEPLANTED), + false, + ) + .on_start(|m| set_flag(m, INTERESTED, false)), + ); + g.add(7, Sleep { countdown }); + g.add(8, Wrap::new(FollowParent::new(1.25)).on_start(clear_states)); + g.add(10, EatBerries::new()); + g.add(10, LeapAtTarget::new(0.4)); + g.add(11, Stroll::avoiding_water(1.0)); + // FoxLookAtPlayerGoal: not with the nose in the snow or while stalking. + g.add( + 12, + Wrap::new(LookAtPlayer::new(24.0)).when(|m| !flag(m, FACEPLANTED | INTERESTED), true), + ); + g.add(13, Perch::default()); + let red = |m: &Mob, _: &MobWorld| m.extra.variant == 0; + let snow = |m: &Mob, _: &MobWorld| m.extra.variant != 0; + let land = || NearestTarget::new(Prey::Filter(chicken_or_rabbit), false).interval(10); + let turtle = || NearestTarget::new(Prey::Filter(baby_turtle_on_land), false).interval(10); + let fish = || NearestTarget::new(Prey::Filter(schooling_fish), false).interval(20); + let t = &mut m.ai.targets; + t.add(4, land().gate(red)); + t.add(4, turtle().gate(red)); + t.add(6, fish().gate(red)); + t.add(4, fish().gate(snow)); + t.add(6, land().gate(snow)); + t.add(6, turtle().gate(snow)); +} + +fn chicken_or_rabbit(s: &Seen) -> bool { + matches!(s.species, Species::Chicken | Species::Rabbit) +} +fn baby_turtle_on_land(s: &Seen) -> bool { + s.species == Species::Turtle && s.baby && !s.in_water +} +fn schooling_fish(s: &Seen) -> bool { + matches!( + s.species, + Species::Cod | Species::Salmon | Species::TropicalFish + ) +} + +/// The part of `Fox.tick` a client runs too: the head tilt eases toward the +/// interested flag and the crouch builds up to 5 while crouching. +pub fn client_tick(m: &mut Mob) { + let (interested, crouching) = (flag(m, INTERESTED), flag(m, CROUCHING)); + let v = &mut m.anim.v; + m.anim.vo[INTERESTED_ANGLE] = v[INTERESTED_ANGLE]; + v[INTERESTED_ANGLE] += (if interested { 1.0 } else { 0.0 } - v[INTERESTED_ANGLE]) * 0.4; + m.anim.vo[CROUCH_AMOUNT] = v[CROUCH_AMOUNT]; + v[CROUCH_AMOUNT] = if crouching { + (v[CROUCH_AMOUNT] + 0.2).min(MAX_CROUCH_AMOUNT) + } else { + 0.0 + }; +} +/// `Fox.isFullyCrouched`. +fn fully_crouched(m: &Mob) -> bool { + m.anim.v[CROUCH_AMOUNT] == MAX_CROUCH_AMOUNT +} + +/// `Fox.tick` and the eating part of `Fox.aiStep`. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + client_tick(m); + if !m.alive() { + return; + } + m.extra.ints[TICKS_SINCE_EATEN] += 1; + if let Some(item) = m.extra.main_hand.clone() + && eats(w, &item) + && m.ai.target.is_none() + && m.on_ground + && !flag(m, SLEEPING) + { + let eaten = m.extra.ints[TICKS_SINCE_EATEN]; + if eaten > 600 { + // ItemStack.finishUsingItem: the food is gone, a use remainder stays. + m.extra.main_hand = w + .items + .and_then(|i| i.items.get(&item)) + .and_then(|i| i.use_remainder.as_deref()) + .map(Into::into); + m.extra.ints[TICKS_SINCE_EATEN] = 0; + } else if eaten > 560 && m.random.next_float() < 0.1 { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound("entity.fox.eat", at, 1.0, 1.0)); + } + } + if !m.target_info(w).is_some_and(|t| t.alive) { + set_flag(m, CROUCHING | INTERESTED, false); + } + let in_water = m.fluids.in_water; + if in_water || m.ai.target.is_some() || w.thundering { + set_flag(m, SLEEPING, false); + } + if in_water || flag(m, SLEEPING) { + set_flag(m, SITTING, false); + } + // Faceplanted: crumbs of the snow now and then (level event 2001). + if flag(m, FACEPLANTED) && m.random.next_float() < 0.2 { + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + events.push(MobEvent::LevelEvent { + id: 2001, + pos: at, + data: w.world.block(at[0], at[1], at[2]).0 as i32, + }); + } +} +/// `Fox.aiStep` before the living step: a sleeping fox takes no input. +pub fn pre_ai_step(m: &mut Mob) { + if flag(m, SLEEPING) { + m.ai.jumping = false; + m.ai.xxa = 0.0; + m.ai.zza = 0.0; + } +} +/// `Fox.isConsumableFood`: the item has food and consumable components. +fn eats(w: &MobWorld, item: &str) -> bool { + w.items + .and_then(|i| i.items.get(item)) + .is_some_and(|i| i.food.is_some() && i.consumable.is_some()) +} + +/// `Fox.FoxBehaviorGoal.hasShelter`: out of the sky's sight and not a bad spot. +fn has_shelter(m: &Mob, w: &MobWorld) -> bool { + let at = [ + m.position.x.floor() as i32, + m.bounds().max(Axis::Y).floor() as i32, + m.position.z.floor() as i32, + ]; + !w.can_see_sky(at[0], at[1], at[2]) && m.walk_target_value(w, at) >= 0.0 +} +/// `Fox.FoxBehaviorGoal.alertable`: someone within 12 blocks the fox would +/// keep watch over (`FoxAlertableEntitiesSelector`). +fn alertable(m: &Mob, w: &MobWorld) -> bool { + let (from, id, y) = (m.position, m.id, m.position.y); + let mob = w + .nearby(from, 12.0, |s: &Seen| { + s.id != id + && (s.position.y - y).abs() <= 6.0 + && m.distance_sqr(s.position) <= 144.0 + && match s.species { + Species::Fox => false, + Species::Chicken | Species::Rabbit => true, + Species::Wolf | Species::Cat | Species::Parrot | Species::Nautilus => !s.tame, + _ => true, + } + }) + .next() + .is_some(); + mob || w.player.as_ref().is_some_and(|p| { + p.alive + && !p.creative + && !p.spectator + && !p.sneaking + && (p.position.y - y).abs() <= 6.0 + && m.distance_sqr(p.position) <= 144.0 + }) +} + +/// `Fox.SleepGoal`: nap in the shade by day when nothing is around. +#[derive(Clone, Debug)] +struct Sleep { + countdown: i32, +} +impl Sleep { + fn can_sleep(&mut self, m: &Mob, w: &MobWorld) -> bool { + if self.countdown > 0 { + self.countdown -= 1; + return false; + } + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + w.daylight + && has_shelter(m, w) + && !alertable(m, w) + && w.block_name(x, y, z) != "minecraft:powder_snow" + } +} +impl Goal for Sleep { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.ai.nav.is_done() && (self.can_sleep(m, cx.w) || flag(m, SLEEPING)) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.can_sleep(m, cx.w) + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, SITTING | CROUCHING | INTERESTED, false); + m.ai.jumping = false; + set_flag(m, SLEEPING, true); + m.nav_stop(); + let p = m.position; + m.ai.mov.set_wanted(p.x, p.y, p.z, 0.0); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + self.countdown = m.random.next_int_bound(reduced(140)).unwrap_or(0); + clear_states(m); + } +} + +/// A shared goal under the fox's own conditions and start-up: the extra +/// `canUse` of `FoxMeleeAttackGoal` and `FoxLookAtPlayerGoal` and the +/// `clearStates` or `setIsInterested(false)` its subclasses do in `start`. +#[derive(Clone, Debug)] +struct Wrap { + goal: G, + when: Option bool>, + /// The condition also applies to `canContinueToUse`. + both: bool, + on_start: Option, +} +impl Wrap { + fn new(goal: G) -> Self { + Self { + goal, + when: None, + both: false, + on_start: None, + } + } + fn when(mut self, f: fn(&Mob) -> bool, both: bool) -> Self { + (self.when, self.both) = (Some(f), both); + self + } + fn on_start(mut self, f: fn(&mut Mob)) -> Self { + self.on_start = Some(f); + self + } +} +impl Goal for Wrap { + goal_clone!(); + fn flags(&self) -> u8 { + self.goal.flags() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.when.is_none_or(|f| f(m)) && self.goal.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (!self.both || self.when.is_none_or(|f| f(m))) && self.goal.can_continue(m, cx) + } + fn interruptable(&self) -> bool { + self.goal.interruptable() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(f) = self.on_start { + f(m); + } + self.goal.start(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.stop(m, cx); + } + fn every_tick(&self) -> bool { + self.goal.every_tick() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.tick(m, cx); + } + fn name(&self) -> &'static str { + self.goal.name() + } +} + +/// `Fox.isPathClear`: six points along the way to the target, each with +/// nothing but replaceable blocks in the three above it. +fn path_clear(m: &Mob, w: &MobWorld, to: Vec3) -> bool { + let (zdiff, xdiff) = (to.z - m.position.z, to.x - m.position.x); + let slope = zdiff / xdiff; + for i in 0..6 { + let step = f64::from(i as f32 / 6.0); + let z = if slope == 0.0 { 0.0 } else { zdiff * step }; + let x = if slope == 0.0 { + xdiff * step + } else { + z / slope + }; + for j in 1..4 { + let at = [ + (m.position.x + x).floor() as i32, + (m.position.y + f64::from(j)).floor() as i32, + (m.position.z + z).floor() as i32, + ]; + if !w.facts.get(w.world.block(at[0], at[1], at[2])).replaceable { + return false; + } + } + } + true +} +fn signum(x: f64) -> f64 { + if x > 0.0 { + 1.0 + } else if x < 0.0 { + -1.0 + } else { + 0.0 + } +} + +/// `Fox.FaceplantGoal`: stay put for 40 ticks with the nose in the snow. +#[derive(Clone, Debug)] +struct Faceplant { + countdown: i32, +} +impl Goal for Faceplant { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK | JUMP + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + flag(m, FACEPLANTED) + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + flag(m, FACEPLANTED) && self.countdown > 0 + } + fn start(&mut self, _: &mut Mob, _: &mut Cx) { + self.countdown = reduced(40); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, FACEPLANTED, false); + } + fn tick(&mut self, _: &mut Mob, _: &mut Cx) { + self.countdown -= 1; + } +} + +/// `Fox.StalkPreyGoal`: creep up on a chicken or rabbit more than 6 blocks +/// away, then crouch and keep still once it is within 6. +#[derive(Clone, Debug)] +struct StalkPrey; +impl StalkPrey { + fn look(m: &mut Mob, eye: [f64; 3]) { + let (y, x) = (m.kind.max_head_y_rot, m.kind.max_head_x_rot); + m.look_at_speed(eye, y, x); + } +} +impl Goal for StalkPrey { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if flag(m, SLEEPING) { + return false; + } + let Some(t) = m.target_info(cx.w) else { + return false; + }; + let stalkable = match m.ai.target { + Some(super::Who::Mob(id)) => { + cx.w.seen(id) + .is_some_and(|s| matches!(s.species, Species::Chicken | Species::Rabbit)) + } + _ => false, + }; + t.alive + && stalkable + && m.distance_sqr(t.position) > 36.0 + && !flag(m, CROUCHING | INTERESTED) + && !m.ai.jumping + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, SITTING | FACEPLANTED, false); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + match m.target_info(cx.w) { + Some(t) if path_clear(m, cx.w, t.position) => { + set_flag(m, INTERESTED | CROUCHING, true); + m.nav_stop(); + Self::look(m, [t.position.x, t.eye_y, t.position.z]); + } + _ => set_flag(m, INTERESTED | CROUCHING, false), + } + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(t) = m.target_info(cx.w) else { return }; + Self::look(m, [t.position.x, t.eye_y, t.position.z]); + if m.distance_sqr(t.position) <= 36.0 { + set_flag(m, INTERESTED | CROUCHING, true); + m.nav_stop(); + } else { + let at = [t.position.x, t.position.y, t.position.z]; + m.nav_move_to_entity(cx.w, at, 0, 1.5); + } + } +} + +/// `Fox.FoxPounceGoal`: once fully crouched with a clear path, leap at the +/// target, tilt with the flight and bite when within 2 blocks, or end up with +/// the nose in snow. +#[derive(Clone, Debug)] +struct Pounce; +impl Goal for Pounce { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !fully_crouched(m) { + return false; + } + let Some(t) = m.target_info(cx.w).filter(|t| t.alive) else { + return false; + }; + let clear = path_clear(m, cx.w, t.position); + if !clear { + set_flag(m, CROUCHING | INTERESTED, false); + } + clear + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !m.target_info(cx.w).is_some_and(|t| t.alive) { + return false; + } + let yd = m.velocity.y; + (yd * yd >= f64::from(0.05f32) || m.head_pitch.abs() >= 15.0 || !m.on_ground) + && !flag(m, FACEPLANTED) + } + fn interruptable(&self) -> bool { + false + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.jumping = true; + set_flag(m, POUNCING, true); + set_flag(m, INTERESTED, false); + if let Some(t) = m.target_info(cx.w) { + m.look_at_speed([t.position.x, t.eye_y, t.position.z], 60.0, 30.0); + let u = m.position.vector_to(t.position).normalize(); + m.velocity = m.velocity.add_vector(Vec3::new(u.x * 0.8, 0.9, u.z * 0.8)); + } + m.nav_stop(); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, CROUCHING | INTERESTED | POUNCING, false); + m.anim.v[CROUCH_AMOUNT] = 0.0; + m.anim.vo[CROUCH_AMOUNT] = 0.0; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let target = m.target_info(cx.w); + if let Some(t) = &target { + m.look_at_speed([t.position.x, t.eye_y, t.position.z], 60.0, 30.0); + } + if !flag(m, FACEPLANTED) { + let v = m.velocity; + if v.y * v.y < f64::from(0.03f32) && m.head_pitch != 0.0 { + m.head_pitch += 0.2 * wrap(-m.head_pitch); + } else { + let horizontal = v.horizontal_distance(); + let bias = if m.ai.jumping && v.y > 0.0 { 6.5 } else { 1.0 }; + let y = v.y * bias; + let len = (horizontal * horizontal + y * y).sqrt(); + if len > f64::from(1.0e-5f32) { + let pitch = signum(-y) * jmath::acos(horizontal / len) * 180.0 + / f64::from(std::f32::consts::PI); + m.head_pitch = (pitch as f32 % 360.0).clamp(-90.0, 90.0); + } + } + } + if let (Some(t), Some(who)) = (&target, m.ai.target) + && m.distance_sqr(t.position) <= 4.0 + { + super::ai::do_hurt_target(m, who, cx); + } else if m.head_pitch > 0.0 + && m.on_ground + && m.velocity.y as f32 != 0.0 + && cx.w.block_name( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ) == "minecraft:snow" + { + m.head_pitch = 60.0; + m.ai.target = None; + set_flag(m, FACEPLANTED, true); + } + } +} + +/// `Fox.SeekShelterGoal`: by day, or in a thunderstorm, leave open sky for +/// somewhere the sky does not see. Villages are not told apart yet (vanilla +/// stays put in one). +#[derive(Clone, Debug)] +struct SeekShelter { + speed: f64, + interval: i32, + wanted: [f64; 3], +} +impl SeekShelter { + fn new(speed: f64) -> Self { + Self { + speed, + interval: reduced(100), + wanted: [0.0; 3], + } + } + fn set_wanted_pos(&mut self, m: &mut Mob, w: &MobWorld) -> bool { + hide_pos(m, w).is_some_and(|at| { + self.wanted = at; + true + }) + } +} +impl Goal for SeekShelter { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if flag(m, SLEEPING) || m.ai.target.is_some() { + return false; + } + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + let sees_sky = cx.w.can_see_sky(at[0], at[1], at[2]); + if cx.w.thundering && sees_sky { + self.set_wanted_pos(m, cx.w) + } else if self.interval > 0 { + self.interval -= 1; + false + } else { + self.interval = 100; + cx.w.daylight && sees_sky && self.set_wanted_pos(m, cx.w) + } + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + clear_states(m); + m.nav_move_to(cx.w, self.wanted, self.speed); + } +} + +/// `Fox.PerchAndSearchGoal`: now and then sit down and look around two to +/// four times when nothing is going on. +#[derive(Clone, Debug, Default)] +struct Perch { + rel: [f64; 2], + look_time: i32, + looks_remaining: i32, +} +impl Perch { + fn reset_look(&mut self, m: &mut Mob) { + let angle = std::f64::consts::TAU * m.random.next_double(); + self.rel = [angle.cos(), angle.sin()]; + self.look_time = reduced(80 + m.random.next_int_bound(20).unwrap_or(0)); + } +} +impl Goal for Perch { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.ai.last_hurt_by.is_none() + && m.random.next_float() < 0.02 + && !flag(m, SLEEPING) + && m.ai.target.is_none() + && m.ai.nav.is_done() + && !alertable(m, cx.w) + && !flag(m, POUNCING | CROUCHING) + } + fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + self.looks_remaining > 0 + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + self.reset_look(m); + self.looks_remaining = 2 + m.random.next_int_bound(3).unwrap_or(0); + set_flag(m, SITTING, true); + m.nav_stop(); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, SITTING, false); + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + self.look_time -= 1; + if self.look_time <= 0 { + self.looks_remaining -= 1; + self.reset_look(m); + } + let at = [ + m.position.x + self.rel[0], + m.eye_y(), + m.position.z + self.rel[1], + ]; + let (y, x) = (m.kind.max_head_y_rot, m.kind.max_head_x_rot); + m.look_at_speed(at, y, x); + } +} + +/// `BlockState` with one property changed. +fn with_prop(w: &MobWorld, p: [i32; 3], key: &str, value: &str) -> Option { + let mut s = w.registry.state(w.world.block(p[0], p[1], p[2]))?.clone(); + s.properties.insert(key.into(), value.into()); + w.registry.id(&s) +} +/// `FoxEatBerriesGoal.isValidTarget`: a ripe sweet berry bush or glow berries. +fn has_berries(w: &MobWorld, p: [i32; 3]) -> bool { + match w.block_name(p[0], p[1], p[2]) { + "minecraft:sweet_berry_bush" => w + .prop(p[0], p[1], p[2], "age") + .and_then(|a| a.parse::().ok()) + .is_some_and(|a| a >= 2), + "minecraft:cave_vines" | "minecraft:cave_vines_plant" => { + w.prop(p[0], p[1], p[2], "berries") == Some("true") + } + _ => false, + } +} + +/// `Fox.FoxEatBerriesGoal`: walk to a ripe berry bush and pick it after 40 ticks. +#[derive(Clone, Debug)] +struct EatBerries { + block: MoveToBlock, + waited: i32, +} +impl EatBerries { + fn new() -> Self { + Self { + block: MoveToBlock::new(1.2, 12, 1), + waited: 0, + } + } + fn pick(&mut self, m: &mut Mob, cx: &mut Cx) { + let p = self.block.block; + let at = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ]; + if cx.w.block_name(p[0], p[1], p[2]) == "minecraft:sweet_berry_bush" { + let age: i32 = + cx.w.prop(p[0], p[1], p[2], "age") + .and_then(|a| a.parse().ok()) + .unwrap_or(0); + let mut count = 1 + m.random.next_int_bound(2).unwrap_or(0) + i32::from(age == 3); + if m.extra.main_hand.is_none() { + m.extra.main_hand = Some("minecraft:sweet_berries".into()); + count -= 1; + } + if count > 0 { + cx.events.push(MobEvent::DropItem { + item: "minecraft:sweet_berries".into(), + count: count as u32, + at, + }); + } + if let Some(state) = with_prop(cx.w, p, "age", "1") { + cx.events.push(MobEvent::SetBlock { pos: p, state }); + } + cx.events.push(MobEvent::Sound( + "block.sweet_berry_bush.pick_berries", + at, + 1.0, + 1.0, + )); + } else { + // CaveVines.use: one glow berry, the vine goes back to bare. + cx.events.push(MobEvent::DropItem { + item: "minecraft:glow_berries".into(), + count: 1, + at, + }); + if let Some(state) = with_prop(cx.w, p, "berries", "false") { + cx.events.push(MobEvent::SetBlock { pos: p, state }); + } + let pitch = 0.8 + m.random.next_float() * 0.4; + cx.events.push(MobEvent::Sound( + "block.cave_vines.pick_berries", + at, + 1.0, + pitch, + )); + } + } +} +impl Goal for EatBerries { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if flag(m, SLEEPING) { + return false; + } + // MoveToBlockGoal.canUse draws the next delay only once the last one + // has run out. + if self.block.next_start > 0 { + self.block.next_start -= 1; + return false; + } + let next = reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); + self.block.can_use(m, cx.w, next, has_berries) + } + fn can_continue(&mut self, _: &mut Mob, cx: &mut Cx) -> bool { + self.block.can_continue(cx.w, has_berries) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.waited = 0; + set_flag(m, SITTING, false); + self.block.start(m, cx.w); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if self.block.reached { + if self.waited >= 40 { + if cx.w.mob_griefing { + self.pick(m, cx); + } + } else { + self.waited += 1; + } + } else if m.random.next_float() < 0.05 { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events + .push(MobEvent::Sound("entity.fox.sniff", at, 1.0, 1.0)); + } + self.block.tick_within(m, cx.w, 2.0); + } +} + +/// `FoxRenderState` as the renderer reads it: the flags, `getHeadRollAngle` +/// and `getCrouchAmount` at the partial tick. `FoxModel.legMotionPos` gains +/// 0.67 a frame; this takes 60 frames a second. +pub fn pose(m: &Mob, partial: f32) -> super::body_anim::Fox { + super::body_anim::Fox { + crouching: flag(m, CROUCHING), + sleeping: flag(m, SLEEPING), + sitting: flag(m, SITTING), + pouncing: flag(m, POUNCING), + faceplanted: flag(m, FACEPLANTED), + head_roll_angle: m.anim.lerp(INTERESTED_ANGLE, partial) * 0.11 * std::f32::consts::PI, + crouch_amount: m.anim.lerp(CROUCH_AMOUNT, partial), + leg_motion_pos: (m.age as f32 + partial) * 0.67 * 3.0, + } +} diff --git a/crates/horizon-client/src/mobs/frog.rs b/crates/horizon-client/src/mobs/frog.rs new file mode 100644 index 000000000..4fbb6a849 --- /dev/null +++ b/crates/horizon-client/src/mobs/frog.rs @@ -0,0 +1,312 @@ +//! Frogs (`Frog`, `FrogAi`): the `Croak` and `ShootTongue` behaviours as +//! goals, the poses they set and the client's animation states. +//! AnimState states: jump, croak, tongue, swim idle. +//! +//! The brain's idle `RunOne` picks a croak three times as often as a stroll +//! (weights 3 and 1; it also holds a do-nothing option that only repeats +//! the pick), so a frog that is not walking croaks in three of four idle +//! picks: `Croak` takes those, and the frog's stroll then follows at once. +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + goals::{ + Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone, + }, + sync, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +const JUMP: usize = 0; +const CROAK: usize = 1; +const TONGUE: usize = 2; +const SWIM_IDLE: usize = 3; + +/// `Croak.CROAK_TICKS`. +const CROAK_TICKS: i32 = 60; +/// `ShootTongue`'s duration and eating distance. +const TONGUE_TIME_OUT: i32 = 100; +const EATING_DISTANCE: f64 = 1.75; +/// `FrogAttackablesSensor.TARGET_DETECTION_DISTANCE` and the sensor's scan +/// rate. +const DETECTION_DISTANCE: f64 = 10.0; +const SCAN_RATE: i32 = 20; + +/// `ShootTongue.State`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Phase { + MoveToTarget, + CatchAnimation, + EatAnimation, + #[default] + Done, +} + +/// The frog's brain memories and `DATA_TONGUE_TARGET_ID`. +#[derive(Clone, Debug, Default)] +pub struct State { + croak: i32, + /// Ticks to the attackables sensor's next scan, and `NEAREST_ATTACKABLE`. + scan: i32, + nearest: Option, + /// `UNREACHABLE_TONGUE_TARGETS`: the mob and the ticks it stays in mind. + unreachable: Vec<(u32, i32)>, + /// `ATTACK_TARGET` while `ShootTongue` runs, and the synched tongue target. + target: Option, + pub tongue_target: Option, + phase: Phase, + eat_timer: i32, + path_counter: i32, + time: i32, +} + +pub fn register(m: &mut Mob) { + // `Frog()`: SmoothSwimmingMoveControl(85, 10, 0.02, 0.1, true). The + // frog's movement speed is 1.0, so the controller's 0.1 outside-water + // speed is what keeps a walking frog at vanilla's pace; the plain ground + // controller walks ten times too fast (#2213). + m.ai.mov.kind = super::control::MoveKind::SmoothSwimming { + max_turn_x: 85.0, + max_turn_y: 10.0, + in_water: 0.02, + outside: 0.1, + gravity: true, + }; + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, Panic::new(1.25)); + g.add(2, ShootTongue); + g.add(4, Croak); + g.add(5, Stroll::avoiding_water(1.0).interval(1)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); +} + +/// `Entity.setPose` and `Frog.onSyncedDataUpdated(DATA_POSE)`. +pub fn set_pose(m: &mut Mob, id: u8) { + let old = std::mem::replace(&mut m.extra.pose, id); + if old != id { + pose_changed(m); + } +} +/// The animation states of the pose the frog has taken. +pub fn pose_changed(m: &mut Mob) { + let age = m.age as f32; + let pose = m.extra.pose; + let states = &mut m.anim.states; + for (state, on) in [ + (JUMP, pose == sync::LONG_JUMPING), + (CROAK, pose == sync::CROAKING), + (TONGUE, pose == sync::USING_TONGUE), + ] { + if on { + states[state].start(age); + } else { + states[state].stop(); + } + } +} +/// `Frog.tick` on a client: the idle swim while it floats still. The server +/// runs it too, for a window that shows its own mobs. +pub fn tick(m: &mut Mob) { + let age = m.age as f32; + let still = m.fluids.in_water && m.limb_speed <= 1.0e-5; + m.anim.states[SWIM_IDLE].animate_when(still, age); +} + +/// `Frog.canEat`: a slime or magma cube of size 1. +fn can_eat(species: Species, size: i32) -> bool { + matches!(species, Species::Slime | Species::MagmaCube) && size == 1 +} + +/// `FrogAttackablesSensor` (every 20 ticks) and the memory timers. +pub fn server_ai_step(m: &mut Mob, w: &MobWorld) { + let f = &mut m.extra.frog; + f.unreachable.retain_mut(|(_, ttl)| { + *ttl -= 1; + *ttl > 0 + }); + f.scan -= 1; + if f.scan > 0 { + return; + } + f.scan = SCAN_RATE; + let unreachable: Vec = f.unreachable.iter().map(|u| u.0).collect(); + let eye = Vec3::new(m.position.x, m.eye_y(), m.position.z); + let nearest = w + .nearby(m.position, DETECTION_DISTANCE, |s| { + can_eat(s.species, s.size) + && !unreachable.contains(&s.id) + && w.line_of_sight(eye, Vec3::new(s.position.x, s.eye_y, s.position.z)) + }) + .find(|s| s.position.distance_squared(m.position) < DETECTION_DISTANCE * DETECTION_DISTANCE) + .map(|s| s.id); + m.extra.frog.nearest = nearest; +} + +/// `Croak`: the pose sync::CROAKING for 60 ticks (the croak is the frog's ambient +/// sound). +#[derive(Clone, Debug)] +struct Croak; +impl Goal for Croak { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + // checkExtraStartConditions (standing), no walk target, and not in + // a liquid (start does nothing there). + m.extra.pose == sync::STANDING + && m.on_ground + && !m.fluids.in_water + && !m.fluids.in_lava + && m.ai.nav.is_done() + && m.random.next_int_bound(4).unwrap_or(0) != 0 + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.extra.frog.croak < CROAK_TICKS + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.extra.frog.croak = 0; + set_pose(m, sync::CROAKING); + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + set_pose(m, sync::STANDING); + } + fn tick(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.extra.frog.croak += 1; + } + fn every_tick(&self) -> bool { + true + } +} + +/// `ShootTongue` with the tongue activity's `StartAttacking` and +/// `StopAttackingIfTargetInvalid`: walk up to a small slime or magma cube, +/// shoot the tongue, pull it in and eat it. +#[derive(Clone, Debug)] +struct ShootTongue; +impl Goal for ShootTongue { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(id) = m.extra.frog.nearest else { + return false; + }; + // The start conditions: no walk target, no panic, not croaking. + if m.ai.panicking || m.extra.pose == sync::CROAKING || !m.ai.nav.is_done() { + return false; + } + let Some(t) = cx.w.seen(id).filter(|t| t.alive) else { + m.extra.frog.nearest = None; + return false; + }; + // canPathfindToTarget: a path that ends at the target. + let at = [t.position.x, t.position.y, t.position.z]; + let ends = m + .create_path_to_entity(cx.w, at, 0) + .is_some_and(|p| f64::from(p.dist_to_target) < EATING_DISTANCE); + if !ends { + // The target is forgotten and not taken for 100 ticks. + let f = &mut m.extra.frog; + f.nearest = None; + if !f.unreachable.iter().any(|u| u.0 == id) { + if f.unreachable.len() == 5 { + f.unreachable.remove(0); + } + f.unreachable.push((id, 100)); + } + return false; + } + m.extra.frog.target = Some(id); + true + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let f = &m.extra.frog; + f.phase != Phase::Done + && f.time <= TONGUE_TIME_OUT + && !m.ai.panicking + && f.target + .is_some_and(|id| cx.w.seen(id).is_some_and(|t| t.alive)) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(t) = m.extra.frog.target.and_then(|id| cx.w.seen(id)) else { + return; + }; + let at = [t.position.x, t.position.y, t.position.z]; + let eye = [t.position.x, t.eye_y, t.position.z]; + m.look_at(eye); + m.extra.frog.tongue_target = m.extra.frog.target; + m.nav_move_to_entity(cx.w, at, 0, 2.0); + let f = &mut m.extra.frog; + f.path_counter = 10; + f.time = 0; + f.phase = Phase::MoveToTarget; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + let f = &mut m.extra.frog; + f.target = None; + f.tongue_target = None; + f.phase = Phase::Done; + set_pose(m, sync::STANDING); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(id) = m.extra.frog.target else { + return; + }; + let Some(t) = cx.w.seen(id) else { + return; + }; + let (at, pos) = ([t.position.x, t.position.y, t.position.z], t.position); + m.look_at([t.position.x, t.eye_y, t.position.z]); + m.extra.frog.tongue_target = Some(id); + m.extra.frog.time += 1; + let here = [m.position.x, m.position.y, m.position.z]; + match m.extra.frog.phase { + Phase::MoveToTarget => { + if pos.distance_squared(m.position) < EATING_DISTANCE * EATING_DISTANCE { + cx.events + .push(MobEvent::Sound("entity.frog.tongue", here, 2.0, 1.0)); + set_pose(m, sync::USING_TONGUE); + // The target is drawn in at 0.75 a tick. + let pull = m.position.subtract(pos).normalize().scale(0.75); + cx.events.push(MobEvent::Push { + target: Who::Mob(id), + velocity: [pull.x, pull.y, pull.z], + }); + let f = &mut m.extra.frog; + f.eat_timer = 0; + f.phase = Phase::CatchAnimation; + } else if m.extra.frog.path_counter <= 0 { + m.nav_move_to_entity(cx.w, at, 0, 2.0); + m.extra.frog.path_counter = 10; + } else { + m.extra.frog.path_counter -= 1; + } + } + Phase::CatchAnimation => { + let f = &mut m.extra.frog; + f.eat_timer += 1; + if f.eat_timer > 6 { + f.phase = Phase::EatAnimation; + // eatEntity. + cx.events + .push(MobEvent::Sound("entity.frog.eat", here, 2.0, 1.0)); + super::ai::do_hurt_target(m, Who::Mob(id), cx); + } + } + Phase::EatAnimation => { + let f = &mut m.extra.frog; + if f.eat_timer >= 10 { + f.phase = Phase::Done; + } else { + f.eat_timer += 1; + } + } + Phase::Done => {} + } + } +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 3d9709ac4..11dd40d6b 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -588,24 +588,43 @@ impl Mob { if p.creative || p.allies.contains(&self.id) { return false; } - self.player_in_range(w, range, check_sight) + self.player_in_range(w, range, check_sight, true) + } + /// forCombat().ignoreInvisibilityTesting() for the player: the check for + /// a target the mob already has, which ignores the visibility scaling. + pub fn can_keep_target_player(&mut self, w: &MobWorld, range: f64) -> bool { + let Some(p) = &w.player else { return false }; + if p.creative || p.allies.contains(&self.id) { + return false; + } + self.player_in_range(w, range, true, false) } /// TargetingConditions.forNonCombat().range(range).test for the player /// (seen by anyone, within range scaled by visibility, in sight). pub fn can_see_player(&mut self, w: &MobWorld, range: f64) -> bool { - self.player_in_range(w, range, true) + self.player_in_range(w, range, true, true) } - fn player_in_range(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool { + /// `TargetingConditions.forNonCombat().range(range).ignoreLineOfSight()` + /// for the player (still scaled by visibility). + pub fn can_see_player_through_walls(&mut self, w: &MobWorld, range: f64) -> bool { + self.player_in_range(w, range, false, true) + } + /// `scale` is `TargetingConditions.testInvisible`: scale the range by + /// the player's visibility. + fn player_in_range( + &mut self, + w: &MobWorld, + range: f64, + check_sight: bool, + scale: bool, + ) -> bool { let Some(p) = &w.player else { return false }; if !p.alive || p.spectator { return false; } // LivingEntity.getVisibilityPercent - let mut visibility = 1.0; - if p.sneaking { - visibility *= 0.8; - } - if let Some(head) = &p.head { + let mut visibility = if scale { p.visibility_percent() } else { 1.0 }; + if let Some(head) = p.head.as_ref().filter(|_| scale) { let skull = match self.species() { Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager => { "minecraft:zombie_head" @@ -654,12 +673,15 @@ impl Goal for Float { #[derive(Clone, Debug)] pub struct Panic { pub speed: f64, + /// Only the damage of `#panic_environmental_causes` (an armadillo). + pub environmental: bool, pos: [f64; 3], } impl Panic { pub fn new(speed: f64) -> Self { Self { speed, + environmental: false, pos: [0.0; 3], } } @@ -675,7 +697,14 @@ impl Goal for Panic { MOVE } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if !should_panic(m) { + let wanted = if self.environmental { + m.last_damage.is_some_and(|(d, t)| { + super::armadillo::environmental(d.kind) && i64::from(m.age) - t <= 40 + }) || m.fire_ticks > 0 && !m.kind.flags.fire_immune + } else { + should_panic(m) + }; + if !wanted { return false; } if m.fire_ticks > 0 { @@ -1442,6 +1471,9 @@ pub struct HurtByTarget { /// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others /// only when the attacker is in sight. pub bee: bool, + /// Whom `alertOther` calls: a filter on the mob (`PandaHurtByTargetGoal` + /// calls aggressive pandas only). + pub alert_if: Option bool>, /// `PolarBear.PolarBearHurtByTargetGoal`: a hurt cub only calls the /// adult bears and drops the target itself. pub polar_bear: bool, @@ -1455,6 +1487,7 @@ impl HurtByTarget { alert_except: vec![], ignore: vec![], bee: false, + alert_if: None, polar_bear: false, timestamp: 0, st: TargetState { @@ -1475,6 +1508,10 @@ impl HurtByTarget { self.bee = true; self } + pub fn alert_if(mut self, f: fn(&Seen) -> bool) -> Self { + self.alert_if = Some(f); + self + } pub fn polar_bear(mut self) -> Self { self.polar_bear = true; self @@ -1552,6 +1589,7 @@ impl Goal for HurtByTarget { && (s.position.z - pos.z).abs() <= range + 1.0 }) .filter(|s| !self.alert_except.contains(&s.species)) + .filter(|s| self.alert_if.is_none_or(|f| f(s))) // PolarBearHurtByTargetGoal.alertOther: adults only. .filter(|s| !(self.polar_bear && s.baby)) .filter(|s| Who::Mob(s.id) != by) @@ -1591,6 +1629,10 @@ pub struct AvoidEntity { pub sprint: f64, /// Extra condition on the avoider (e.g. untamed cats only). pub when: Option bool>, + /// Extra condition on the player or mob avoided (`AvoidEntityGoal`'s + /// predicate: a sneaking player, a tame wolf). + pub player_when: Option bool>, + pub seen_when: Option bool>, from: Vec3, /// The mob being avoided (`toAvoid`), when it is one. pub found: Option, @@ -1603,6 +1645,8 @@ impl AvoidEntity { walk, sprint, when: None, + player_when: None, + seen_when: None, from: Vec3::ZERO, found: None, } @@ -1611,6 +1655,14 @@ impl AvoidEntity { self.when = Some(f); self } + pub fn player_when(mut self, f: fn(&super::PlayerView) -> bool) -> Self { + self.player_when = Some(f); + self + } + pub fn seen_when(mut self, f: fn(&Seen) -> bool) -> Self { + self.seen_when = Some(f); + self + } } impl Goal for AvoidEntity { goal_clone!(); @@ -1631,6 +1683,7 @@ impl Goal for AvoidEntity { .filter(|p| { p.alive && !p.creative + && self.player_when.is_none_or(|f| f(p)) && m.distance_sqr(p.position) <= max * max && (p.position.y - m.position.y).abs() <= max + 3.0 }) @@ -1639,10 +1692,12 @@ impl Goal for AvoidEntity { Avoid::Species(list) => { let id = m.id; let y = m.position.y; + let seen_when = self.seen_when; let hit = cx.w.nearby(m.position, max, move |s| { s.id != id && list.contains(&s.species) + && seen_when.is_none_or(|f| f(s)) && (s.position.y - y).abs() <= 3.0 + max }) .map(|s| (s.id, s.position)) @@ -2021,6 +2076,30 @@ impl Goal for RestrictSun { m.ai.nav.avoid_sun = false; } } +/// `FleeSunGoal.getHidePos`: a spot within 10 blocks that the sky does not +/// see and the mob likes. +pub fn hide_pos(m: &mut Mob, w: &MobWorld) -> Option<[f64; 3]> { + let (bx, by, bz) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + for _ in 0..10 { + let p = [ + bx + m.random.next_int_bound(20).unwrap_or(0) - 10, + by + m.random.next_int_bound(6).unwrap_or(0) - 3, + bz + m.random.next_int_bound(20).unwrap_or(0) - 10, + ]; + if !w.can_see_sky(p[0], p[1], p[2]) && m.walk_target_value(w, p) < 0.0 { + return Some([ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ]); + } + } + None +} /// FleeSunGoal: find shade while burning. #[derive(Clone, Debug)] pub struct FleeSun { @@ -2052,22 +2131,13 @@ impl Goal for FleeSun { if !cx.w.can_see_sky(bx, by, bz) { return false; } - for _ in 0..10 { - let p = [ - bx + m.random.next_int_bound(20).unwrap_or(0) - 10, - by + m.random.next_int_bound(6).unwrap_or(0) - 3, - bz + m.random.next_int_bound(20).unwrap_or(0) - 10, - ]; - if !cx.w.can_see_sky(p[0], p[1], p[2]) && m.walk_target_value(cx.w, p) < 0.0 { - self.wanted = [ - f64::from(p[0]) + 0.5, - f64::from(p[1]), - f64::from(p[2]) + 0.5, - ]; - return true; + match hide_pos(m, cx.w) { + Some(at) => { + self.wanted = at; + true } + None => false, } - false } fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { !m.ai.nav.is_done() diff --git a/crates/horizon-client/src/mobs/goat.rs b/crates/horizon-client/src/mobs/goat.rs new file mode 100644 index 000000000..058f0e697 --- /dev/null +++ b/crates/horizon-client/src/mobs/goat.rs @@ -0,0 +1,467 @@ +//! Goats (`Goat`, `GoatAi`): the lowered head (`lowerHeadTick`, entity +//! events 58 and 59) and the ram activity: `PrepareRamNearestTarget` picks +//! the nearest living thing it can see, walks to a spot four to seven +//! blocks away in a straight line and waits there 20 ticks with its head +//! down; `RamTarget` then charges at it, knocks it back, or breaks a horn +//! on a log, stone or ore. Both are one goal here. +use super::{ + Damage, Mob, MobEvent, MobWorld, Who, + goals::{Cx, Goal, LOOK, MOVE, goal_clone}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +/// `GoatAi.TIME_BETWEEN_RAMS` and `TIME_BETWEEN_RAMS_SCREAMER`. +const RAMS: (i32, i32) = (600, 6000); +const RAMS_SCREAMER: (i32, i32) = (100, 300); +const RAM_PREPARE_TIME: i64 = 20; +const MIN_RAM_DISTANCE: i32 = 4; +const MAX_RAM_DISTANCE: i32 = 7; +/// `PrepareRamNearestTarget.TIME_OUT_DURATION` and `RamTarget`'s. +const PREPARE_TIME_OUT: i32 = 160; +const RAM_TIME_OUT: i32 = 200; +/// `NEAREST_VISIBLE_LIVING_ENTITIES` reaches 16 blocks. +const SENSE_RANGE: f64 = 16.0; + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Phase { + #[default] + Done, + Prepare, + /// `RAM_TARGET` is set; `RamTarget` starts on the next tick. + RamStart, + Ram, +} +#[derive(Clone, Copy, Debug)] +struct Candidate { + start: [i32; 3], + target_pos: [i32; 3], + target: Who, +} + +/// The lowered head and the ram behaviours' state. `RAM_COOLDOWN_TICKS` is a +/// brain memory (`ram_cooldown`), saved with the others. +#[derive(Clone, Debug, Default)] +pub struct State { + lower_head_tick: i32, + lowering_head: bool, + phase: Phase, + candidate: Option, + reached_at: Option, + /// `RAM_TARGET`, and the direction of the charge. + ram_target: Option, + ram_direction: Vec3, + time: i32, +} + +pub fn register(m: &mut Mob) { + m.ai.goals.add(2, Ram); +} + +/// `Goat.handleEntityEvent`: 58 lowers the head, 59 raises it. +pub fn entity_event(m: &mut Mob, event: u8) { + match event { + 58 => m.extra.goat.lowering_head = true, + 59 => m.extra.goat.lowering_head = false, + _ => {} + } +} +/// `Goat.aiStep`'s `lowerHeadTick`; a client runs it too. +pub fn tick(m: &mut Mob) { + let g = &mut m.extra.goat; + g.lower_head_tick += if g.lowering_head { 1 } else { -2 }; + g.lower_head_tick = g.lower_head_tick.clamp(0, 20); + // `CountDownCooldownTicks(RAM_COOLDOWN_TICKS)`: one less each tick, erased + // once it runs out. + let cooldown = ram_cooldown(m); + if cooldown > 0 { + set_ram_cooldown(m, cooldown - 1); + } +} +/// `RAM_COOLDOWN_TICKS`: 0 when absent. +pub fn ram_cooldown(m: &Mob) -> i32 { + m.extra + .memories + .iter() + .find(|x| x.0 == RAM_COOLDOWN) + .map_or(0, |x| x.1 as i32) +} +fn set_ram_cooldown(m: &mut Mob, ticks: i32) { + let memories = &mut m.extra.memories; + match memories.iter().position(|x| x.0 == RAM_COOLDOWN) { + Some(i) if ticks > 0 => memories[i].1 = i64::from(ticks), + Some(i) => { + memories.remove(i); + } + None if ticks > 0 => memories.push((RAM_COOLDOWN, i64::from(ticks), i64::MAX)), + None => {} + } +} +const RAM_COOLDOWN: &str = "ram_cooldown"; +/// `Goat.getRammingXHeadRot`. +pub fn ramming_x_head_rot(m: &Mob) -> f32 { + let max = if m.is_baby() { 52.5_f32 } else { 30.0 }; + m.extra.goat.lower_head_tick as f32 / 20.0 * max * (std::f32::consts::PI / 180.0) +} +/// A server's `level.broadcastEntityEvent(goat, 58 or 59)`, sent when it +/// changes what the goat does. +fn lower_head(m: &mut Mob, events: &mut Vec, lower: bool) { + if m.extra.goat.lowering_head != lower { + let event: i8 = if lower { 58 } else { 59 }; + entity_event(m, event as u8); + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::EntityEvent { + mob: m.id, + event, + at, + }); + } +} +fn between(m: &mut Mob, (min, max): (i32, i32)) -> i32 { + m.random.next_int_between_inclusive(min, max).unwrap_or(min) +} +fn rams(m: &Mob) -> (i32, i32) { + if m.extra.screaming { + RAMS_SCREAMER + } else { + RAMS + } +} +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} +fn play(m: &Mob, events: &mut Vec, sound: &'static str, pitch: f32) { + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound(sound, at, 1.0, pitch)); + } +} + +/// `PrepareRamNearestTarget.isWalkableBlock`. +fn walkable(m: &Mob, w: &MobWorld, p: [i32; 3]) -> bool { + m.stable_destination(w, p) && m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0 +} +/// `PrepareRamNearestTarget.calculateRammingStartPosition`. +fn ramming_start(m: &mut Mob, w: &MobWorld, target: [i32; 3]) -> Option<[i32; 3]> { + if !walkable(m, w, target) { + return None; + } + // Direction.Plane.HORIZONTAL: north, east, south, west. + let mut starts = Vec::new(); + for (dx, dz) in [(0, -1), (1, 0), (0, 1), (-1, 0)] { + let mut p = target; + for _ in 0..MAX_RAM_DISTANCE { + p = [p[0] + dx, p[1], p[2] + dz]; + if !walkable(m, w, p) { + p = [p[0] - dx, p[1], p[2] - dz]; + break; + } + } + let manhattan = + (p[0] - target[0]).abs() + (p[1] - target[1]).abs() + (p[2] - target[2]).abs(); + if manhattan >= MIN_RAM_DISTANCE { + starts.push(p); + } + } + let here = block_of(m.position); + let sqr = |p: &[i32; 3]| { + (0..3) + .map(|i| i64::from(p[i] - here[i]).pow(2)) + .sum::() + }; + starts.sort_by_key(sqr); + starts + .into_iter() + .find(|&p| m.create_path_to(w, p, 0).is_some_and(|path| path.reached)) +} +/// `PrepareRamNearestTarget.chooseRamPosition`. +fn choose(m: &mut Mob, w: &MobWorld, target: Who) { + let g = &mut m.extra.goat; + g.reached_at = None; + let Some(t) = w.target_info(target) else { + g.candidate = None; + return; + }; + let target_pos = block_of(t.position); + m.extra.goat.candidate = ramming_start(m, w, target_pos).map(|start| Candidate { + start, + target_pos, + target, + }); +} +/// The nearest living thing the goat sees that `RAM_TARGET_CONDITIONS` +/// allow: not a goat, a player who is not creative or a spectator. +fn nearest_target(m: &mut Mob, w: &MobWorld) -> Option { + let mut best: Option<(Who, f64)> = None; + if let Some(p) = &w.player + && p.alive + && !p.creative + && !p.spectator + && !p.allies.contains(&m.id) + && m.distance_sqr(p.position) <= SENSE_RANGE * SENSE_RANGE + && m.sees(w, Who::Player) + { + best = Some((Who::Player, m.distance_sqr(p.position))); + } + let id = m.id; + let mobs: Vec<(u32, f64)> = w + .nearby(m.position, SENSE_RANGE, |s| { + s.id != id && s.species != super::Species::Goat && !s.playing_dead + }) + .map(|s| (s.id, m.distance_sqr(s.position))) + .collect(); + for (mob, d) in mobs { + if best.is_none_or(|b| d < b.1) && m.sees(w, Who::Mob(mob)) { + best = Some((Who::Mob(mob), d)); + } + } + best.map(|b| b.0) +} + +/// `PrepareRamNearestTarget` and `RamTarget` of the ram activity. +#[derive(Clone, Debug)] +struct Ram; +impl Goal for Ram { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + // The ram activity needs the cooldown to be over (it also waits for + // no tempting player and no breed target, which goats lack here). + ram_cooldown(m) <= 0 + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let g = &m.extra.goat; + match g.phase { + Phase::Done => false, + Phase::Prepare => { + g.time <= PREPARE_TIME_OUT + && g.candidate + .is_some_and(|c| cx.w.target_info(c.target).is_some_and(|t| t.alive)) + } + Phase::RamStart | Phase::Ram => g.ram_target.is_some() && g.time <= RAM_TIME_OUT, + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.extra.goat.phase = Phase::Prepare; + m.extra.goat.time = 0; + m.extra.goat.reached_at = None; + m.extra.goat.candidate = None; + if let Some(target) = nearest_target(m, cx.w) { + choose(m, cx.w, target); + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + match m.extra.goat.phase { + // PrepareRamNearestTarget.stop: no ram target, so the head comes + // up and the cooldown starts. + Phase::Prepare => { + lower_head(m, cx.events, false); + let wait = rams(m).0; + set_ram_cooldown(m, wait); + } + // RamTarget.finishRam (also what its timeout leaves undone). + Phase::RamStart | Phase::Ram => finish_ram(m, cx.events), + Phase::Done => {} + } + m.extra.goat.phase = Phase::Done; + m.extra.goat.candidate = None; + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + m.extra.goat.time += 1; + match m.extra.goat.phase { + Phase::Prepare => prepare_tick(m, cx), + Phase::RamStart => { + // RamTarget.start: charge from here at the ram target. + let (Some(target), here) = (m.extra.goat.ram_target, block_of(m.position)) else { + return; + }; + let d = Vec3::new( + f64::from(here[0]) - target.x, + 0.0, + f64::from(here[2]) - target.z, + ); + m.extra.goat.ram_direction = d.normalize(); + m.extra.goat.phase = Phase::Ram; + m.extra.goat.time = 0; + m.nav_move_to_entity(cx.w, [target.x, target.y, target.z], 0, 3.0); + ram_tick(m, cx); + } + Phase::Ram => ram_tick(m, cx), + Phase::Done => {} + } + } +} +/// `PrepareRamNearestTarget.tick`. +fn prepare_tick(m: &mut Mob, cx: &mut Cx) { + let Some(c) = m.extra.goat.candidate else { + return; + }; + let Some(t) = cx.w.target_info(c.target) else { + return; + }; + m.look_at([t.position.x, t.eye_y, t.position.z]); + let now = m.age as i32; + let at = [ + f64::from(c.start[0]) + 0.5, + f64::from(c.start[1]), + f64::from(c.start[2]) + 0.5, + ]; + if m.ai.nav.is_done() && block_of(m.position) != c.start { + m.nav_move_to_entity(cx.w, at, 0, 1.25); + } + if block_of(t.position) != c.target_pos { + // The target moved: the head comes up and a new spot is chosen. + lower_head(m, cx.events, false); + m.nav_stop(); + choose(m, cx.w, c.target); + } else if block_of(m.position) == c.start { + lower_head(m, cx.events, true); + let since = *m.extra.goat.reached_at.get_or_insert(now); + if i64::from(now - since) >= RAM_PREPARE_TIME { + // getEdgeOfBlock. + let (x, z) = ( + f64::from(c.target_pos[0]) + + 0.5 + + 0.5 * f64::from(sign(c.target_pos[0] - c.start[0])), + f64::from(c.target_pos[2]) + + 0.5 + + 0.5 * f64::from(sign(c.target_pos[2] - c.start[2])), + ); + m.extra.goat.ram_target = Some(Vec3::new(x, f64::from(c.target_pos[1]), z)); + let sound = if m.extra.screaming { + "entity.goat.screaming.prepare_ram" + } else { + "entity.goat.prepare_ram" + }; + let pitch = m.voice_pitch(); + play(m, cx.events, sound, pitch); + m.extra.goat.candidate = None; + m.extra.goat.phase = Phase::RamStart; + } + } +} +fn sign(v: i32) -> i32 { + v.signum() +} +/// `RamTarget.tick`. +fn ram_tick(m: &mut Mob, cx: &mut Cx) { + let impact = if m.extra.screaming { + "entity.goat.screaming.ram_impact" + } else { + "entity.goat.ram_impact" + }; + let from = [m.position.x, m.position.y, m.position.z]; + if let Some(target) = rammed(m, cx.w) { + // hurtServer by `noAggroMobAttack`, then the knockback. + let amount = m.attrs.attack_damage; + match target { + Who::Player => cx.events.push(MobEvent::DamagePlayer { + amount, + from, + kind: "minecraft:mob_attack_no_aggro", + }), + Who::Mob(id) => cx.events.push(MobEvent::AttackMob { + target: id, + amount, + source: Damage::mob(m.id, from), + }), + } + let level = |effect: &str| { + m.extra + .effects + .iter() + .find(|e| e.0 == effect) + .map_or(0, |e| e.2 + 1) + }; + let boost = 0.25 * (level("minecraft:speed") - level("minecraft:slowness")) as f32; + let factor = (m.ai.speed * 1.65).clamp(0.2, 3.0) + boost; + let force = if m.is_baby() { 1.0 } else { 2.5 }; + let d = m.extra.goat.ram_direction; + cx.events.push(MobEvent::Knockback { + target, + power: f64::from(factor * force), + x: d.x, + z: d.z, + }); + finish_ram(m, cx.events); + play(m, cx.events, impact, 1.0); + } else if rammed_horn_block(m, cx.w) { + play(m, cx.events, impact, 1.0); + if drop_horn(m, cx.events) { + play(m, cx.events, "entity.goat.horn_break", 1.0); + } + finish_ram(m, cx.events); + } else if m.ai.nav.is_done() || m.extra.goat.ram_target.is_none() { + // The walk target is gone: the charge ended where it could. + finish_ram(m, cx.events); + } +} +/// The first living thing in the goat's box that `RAM_TARGET_CONDITIONS` +/// allow. +fn rammed(m: &Mob, w: &MobWorld) -> Option { + let bounds = m.bounds(); + if let Some(p) = &w.player + && p.alive + && !p.creative + && !p.spectator + && !p.allies.contains(&m.id) + && p.bounds.intersects(bounds) + { + return Some(Who::Player); + } + w.others_near(bounds) + .find(|s| { + s.id != m.id + && s.alive + && s.species != super::Species::Goat + && !s.playing_dead + && s.bounds.intersects(bounds) + }) + .map(|s| Who::Mob(s.id)) +} +/// `RamTarget.hasRammedHornBreakingBlock`: the block one step ahead, or the +/// one above it, snaps a horn. +fn rammed_horn_block(m: &Mob, w: &MobWorld) -> bool { + let ahead = Vec3::new(m.velocity.x, 0.0, m.velocity.z).normalize(); + let at = block_of(m.position.add_vector(ahead)); + let snaps = + |p: [i32; 3]| w.has_tag("minecraft:snaps_goat_horn", w.block_name(p[0], p[1], p[2])); + snaps(at) || snaps([at[0], at[1] + 1, at[2]]) +} +/// `Goat.dropHorn`: one of the horns it still has comes off and drops. +fn drop_horn(m: &mut Mob, events: &mut Vec) -> bool { + if m.is_baby() { + return false; + } + let [left_lost, right_lost] = m.extra.lost_horns; + if left_lost && right_lost { + return false; + } + let lose_left = if left_lost { + false + } else if right_lost { + true + } else { + m.random.next_boolean() + }; + m.extra.lost_horns[usize::from(!lose_left)] = true; + events.push(MobEvent::DropItem { + item: "minecraft:goat_horn".into(), + count: 1, + at: [m.position.x, m.position.y, m.position.z], + }); + true +} +/// `RamTarget.finishRam`. +fn finish_ram(m: &mut Mob, events: &mut Vec) { + lower_head(m, events, false); + let wait = rams(m); + let cooldown = between(m, wait); + set_ram_cooldown(m, cooldown); + m.extra.goat.ram_target = None; + m.extra.goat.phase = Phase::Done; +} diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index c41c34f11..ae73ef854 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -157,12 +157,16 @@ impl Goal for OfferFlower { fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { self.ticks > 0 } - fn start(&mut self, m: &mut Mob, _: &mut Cx) { + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { self.ticks = 400; m.extra.counter = 400; + // IronGolem.offerFlower(true): entity event 11. + entity_event(m, 11, cx); } fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { m.extra.counter = 0; + // IronGolem.offerFlower(false): entity event 34. + entity_event(m, 34, cx); // A copper golem the offer ran out beside takes the poppy on its // antenna (#accepts_iron_golem_gift) when it has none. if self.ticks == 0 @@ -198,6 +202,7 @@ impl Goal for OfferFlower { /// the target is thrown upward. pub fn iron_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { m.extra.anim_ticks = 10; + entity_event(m, 4, cx); let attack = m.attrs.attack_damage; let amount = if attack as i32 > 0 { attack / 2.0 + m.random.next_int_bound(attack as i32).unwrap_or(0) as f32 @@ -224,6 +229,33 @@ pub fn iron_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { 1.0, )); } +/// `Level.broadcastEntityEvent` for an iron golem (guests run `client_event`). +fn entity_event(m: &Mob, event: i8, cx: &mut Cx) { + cx.events.push(MobEvent::EntityEvent { + mob: m.id, + event, + at: [m.position.x, m.position.y, m.position.z], + }); +} +/// `IronGolem.handleEntityEvent` on a client: 4 the swing, 11 and 34 the +/// poppy offer starting and stopping. +pub fn client_event(m: &mut Mob, event: u8) { + match event { + 4 => m.extra.anim_ticks = 10, + 11 => m.extra.counter = 400, + 34 => m.extra.counter = 0, + _ => {} + } +} +/// The swing and offer clocks of `IronGolem.aiStep` on a client. +pub fn client_tick(m: &mut Mob) { + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } + if m.extra.counter > 0 { + m.extra.counter -= 1; + } +} /// `IronGolem.aiStep` timers and anger. pub fn iron_ai_step(m: &mut Mob) { if m.extra.anim_ticks > 0 { diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index 880655361..ea70ecb41 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -214,12 +214,9 @@ pub fn travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec } true } -/// `Guardian.aiStep`: the client animations, air, flopping on land, the -/// beam's clock, and the spikes' thorns. -pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { - if !m.alive() { - return; - } +/// `Guardian.aiStep`'s `clientSideTailAnimation` and +/// `clientSideSpikesAnimation` (the server's and a client's). +pub fn tail_and_spikes(m: &mut Mob) { let moving = m.extra.flag2; let in_water = m.fluids.in_water; // Tail and spikes (clientSideTailAnimation / clientSideSpikesAnimation). @@ -244,6 +241,16 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } else { a.v[SPIKES] += (1.0 - a.v[SPIKES]) * 0.06; } +} +/// `Guardian.aiStep`: the client animations, air, flopping on land, the +/// beam's clock, and the spikes' thorns. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if !m.alive() { + return; + } + let moving = m.extra.flag2; + let in_water = m.fluids.in_water; + tail_and_spikes(m); client_tick(m); if in_water { m.air = 300; @@ -276,17 +283,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { None => w.player.as_ref().map(|p| p.eye), }; if let Some(look) = look { - m.anim.v[EYE_Y] = if look[1] - m.eye_y() > 0.0 { 0.0 } else { 1.0 }; - let yaw = m.head_yaw.to_radians(); - let pitch = m.head_pitch.to_radians(); - let view = [-yaw.msin() * pitch.mcos(), yaw.mcos() * pitch.mcos()]; - let d = [m.position.x - look[0], m.position.z - look[2]]; - let len = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-9); - let (dx, dz) = ((d[0] / len) as f32, (d[1] / len) as f32); - // Vec3.yRot(pi / 2) of the direction from the target. - let side = [dz, -dx]; - let dot = view[0] * side[0] + view[1] * side[1]; - m.anim.v[EYE_X] = dot.abs().sqrt() * 2.0 * dot.signum(); + look_at(m, look); } // Guardian.hurtServer: a still guardian's spikes hurt a melee attacker. if m.hurt_time == 10 @@ -317,6 +314,21 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } } +/// `GuardianModel.setupAnim`'s eye: it follows `look` (the attack target's +/// eye, else the camera's), from where the guardian faces. +pub fn look_at(m: &mut Mob, look: [f64; 3]) { + m.anim.v[EYE_Y] = if look[1] - m.eye_y() > 0.0 { 0.0 } else { 1.0 }; + let yaw = m.head_yaw.to_radians(); + let pitch = m.head_pitch.to_radians(); + let view = [-yaw.msin() * pitch.mcos(), yaw.mcos() * pitch.mcos()]; + let d = [m.position.x - look[0], m.position.z - look[2]]; + let len = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-9); + let (dx, dz) = ((d[0] / len) as f32, (d[1] / len) as f32); + // Vec3.yRot(pi / 2) of the direction from the target. + let side = [dz, -dx]; + let dot = view[0] * side[0] + view[1] * side[1]; + m.anim.v[EYE_X] = dot.abs().sqrt() * 2.0 * dot.signum(); +} /// `ElderGuardian.customServerAiStep`: every minute, mining fatigue III for /// players within 50 blocks; a home within 16 blocks. pub fn elder_server_ai_step(m: &mut Mob, cx: &mut Cx) { @@ -399,6 +411,8 @@ pub fn beam_geometry( layer: 0, color, light: 240 | 240 << 8, + + glint_uv: [0.0, 0.0], }); }; // Sides: one quad per texture repeat. diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index 296644acc..418556750 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -364,8 +364,7 @@ impl Goal for GhastTempt { let Some(p) = &cx.w.player else { return false }; // getNearestPlayer(TargetingConditions.forNonCombat() // .ignoreLineOfSight().range(TEMPT_RANGE 16)): creative players too. - let visibility = if p.sneaking { 0.8 } else { 1.0 }; - let range = (16.0_f64 * visibility).max(2.0); + let range = (16.0_f64 * p.visibility_percent()).max(2.0); p.alive && !p.spectator && (Self::wants(m, &p.main_hand) || Self::wants(m, &p.off_hand)) diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index f1c990c48..689301e14 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -77,7 +77,8 @@ impl Goal for SpiderAttack { self.0.flags() } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.0.can_use(m, cx) + // SpiderAttackGoal.canUse: not while it carries a rider. + self.0.can_use(m, cx) && m.extra.rider.is_none() } fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { if mob_brightness(m, cx.w) >= 0.5 && m.random.next_int_bound(100).unwrap_or(1) == 0 { @@ -184,6 +185,7 @@ pub fn creeper_tick(m: &mut Mob, events: &mut Vec) { events.push(MobEvent::Explode( [m.position.x, m.position.y, m.position.z], radius, + m.species(), )); m.removed = true; } diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 00581d6d3..f4cb18af8 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -13,18 +13,6 @@ use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; -/// The species raiders do not fight (`Raider`'s allies). -fn raider(s: Species) -> bool { - matches!( - s, - Species::Pillager - | Species::Vindicator - | Species::Witch - | Species::Evoker - | Species::Illusioner - | Species::Ravager - ) -} fn targets(m: &mut Mob, villagers_seen: bool) { let mut hurt = HurtByTarget::new().alert(); hurt.ignore = vec![ @@ -80,10 +68,11 @@ pub fn register_vindicator(m: &mut Mob) { g.add(9, LookAtPlayer::new(3.0).probability(1.0)); g.add(10, LookAtPlayer::mobs(8.0)); targets(m, true); - // VindicatorJohnnyAttackGoal: a vindicator named Johnny attacks anything. + // VindicatorJohnnyAttackGoal: a vindicator named Johnny attacks any + // living entity, other raiders included. m.ai.targets.add( 4, - NearestTarget::new(Prey::Filter(|s| !raider(s.species)), true) + NearestTarget::new(Prey::Filter(|_| true), true) .interval(0) .when(|m, _| m.custom_name.as_deref() == Some("Johnny")), ); diff --git a/crates/horizon-client/src/mobs/keyframes.rs b/crates/horizon-client/src/mobs/keyframes.rs index e070210ec..edcee8835 100644 --- a/crates/horizon-client/src/mobs/keyframes.rs +++ b/crates/horizon-client/src/mobs/keyframes.rs @@ -165,6 +165,12 @@ impl AnimationState { pub fn stop(&mut self) { self.started = None; } + /// `AnimationState.fastForward`: the animation is `ticks` further on. + pub fn fast_forward(&mut self, ticks: i32) { + if let Some(s) = &mut self.started { + *s -= ticks as f32; + } + } pub fn animate_when(&mut self, condition: bool, age: f32) { if condition { self.start_if_stopped(age) diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 389457a11..612ab0dbb 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -9,8 +9,15 @@ use crate::{ }; use horizon_core::{ geometry::{Aabb, Vec3, trig}, + position::BlockPos, random::RandomSource, }; +use horizon_world::{ + entity_fluid::{CurrentAccumulator, CurrentTarget}, + fluid::{FluidKind, FluidState}, + fluid_flow::{FluidFlowWorld, flow_at}, + registry::BlockStateId, +}; /// `Entity.moveDist`, `flyDist` and `nextStep`. #[derive(Clone, Copy, Debug)] @@ -36,6 +43,50 @@ pub struct Fluids { pub in_lava: bool, pub eye_in_water: bool, } +/// `FluidFlowWorld` over the mob's scene: the neighbours a flow vector reads. +struct FlowScene<'a, 'w>(&'a MobWorld<'w>); +impl FluidFlowWorld for FlowScene<'_, '_> { + type Error = std::convert::Infallible; + type Block = BlockStateId; + fn fluid(&mut self, p: BlockPos) -> Result { + Ok(self.0.fluid_tables.fluid(self.0.world.block(p.x, p.y, p.z))) + } + fn block(&mut self, p: BlockPos) -> Result { + Ok(self.0.world.block(p.x, p.y, p.z)) + } + fn blocks_fluid_flow(&self, s: BlockStateId) -> bool { + self.0.fluid_tables.blocks_flow(s) + } + fn is_ice_class(&self, s: BlockStateId) -> bool { + self.0.fluid_tables.ice(s) + } + fn is_face_sturdy( + &mut self, + s: BlockStateId, + _: BlockPos, + d: horizon_core::geometry::Direction, + ) -> Result { + Ok(self.0.fluid_tables.sturdy(s, d)) + } +} +/// The mob's velocity, for `CurrentAccumulator::apply_to`. +struct Pushed<'a>(&'a mut Vec3); +impl CurrentTarget for Pushed<'_> { + type Error = std::convert::Infallible; + fn is_player_class(&self) -> bool { + false + } + fn velocity(&mut self) -> Result { + Ok(*self.0) + } + fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Self::Error> { + let sum = Vec3::new(self.0.x + delta.x, self.0.y + delta.y, self.0.z + delta.z); + if delta.is_finite() && sum.is_finite() { + *self.0 = sum; + } + Ok(()) + } +} pub fn wrap(a: f32) -> f32 { let mut a = a % 360.0; if a >= 180.0 { @@ -140,6 +191,40 @@ impl MobWorld<'_> { } out } + /// Entity.updateFluidHeightAndDoFluidPushing's currents over the deflated + /// box: the flow of every water and lava block it touches, summed (a thin + /// fluid layer scales its flow down), as (water, lava). + fn fluid_currents(&self, bounds: Aabb) -> (CurrentAccumulator, CurrentAccumulator) { + let base_y = bounds.min_position().y; + let b = bounds.deflate(Vec3::new(0.001, 0.001, 0.001)); + let (lo, hi) = (b.min_position(), b.max_position()); + let mut scene = FlowScene(self); + let (mut water, mut lava) = (CurrentAccumulator::default(), CurrentAccumulator::default()); + for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) { + for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { + for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) { + let p = BlockPos::new(x, y, z); + let state = self.fluid_tables.fluid(self.world.block(x, y, z)); + let current = match state.kind() { + FluidKind::Empty => continue, + FluidKind::Water | FluidKind::FlowingWater => &mut water, + FluidKind::Lava | FluidKind::FlowingLava => &mut lava, + }; + let surface = f64::from(y) + self.fluid_height(x, y, z).1; + if surface < lo.y { + continue; + } + current.height = current.height.max(surface - base_y); + let mut flow = flow_at(&mut scene, state, p).unwrap_or(Vec3::ZERO); + if current.height < 0.4 { + flow = flow.scale(current.height); + } + current.accumulate(flow); + } + } + } + (water, lava) + } /// `BlockState.getCollisionShape(level, pos)` (the empty collision /// context) as boxes in the world. pub fn block_collision_boxes(&self, x: i32, y: i32, z: i32) -> Vec { @@ -363,6 +448,27 @@ impl Mob { pub fn is_in_liquid(&self) -> bool { self.fluids.in_water || self.fluids.in_lava } + /// `Entity.isPushedByFluid`: water animals, turtles, axolotls, frogs and + /// nautiluses keep their own course. + fn pushed_by_fluid(&self) -> bool { + use super::Species as S; + !matches!( + self.species(), + S::Tadpole + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Squid + | S::GlowSquid + | S::Dolphin + | S::Turtle + | S::Axolotl + | S::Frog + | S::Nautilus + | S::ZombieNautilus + ) + } fn affected_by_fluids(&self) -> bool { true } @@ -440,23 +546,60 @@ impl Mob { } else if !matches!(self.kind.species, super::Species::Bat | super::Species::Bee) { self.check_fall_damage(w, moved, events); } - // restituteMovementAfterCollisions with no bounciness: the colliding - // components become (signed) zero. + // Entity.restituteMovementAfterCollisions: the colliding components + // bounce back by the entity's bounciness (zero for most mobs, so they + // become signed zero). Block bounciness is not modelled for mobs. if moved_vertically && vertical || self.horizontal_collision { let v = self.velocity; + let restitution = self.entity_bounciness(); + let mut after = v; if x_hit { - self.velocity.x = -v.x * 0.0; + after.x = -v.x * restitution; } if z_hit { - self.velocity.z = -v.z * 0.0; + after.z = -v.z * restitution; } if vertical { - self.velocity.y = (0.0 - v.y) * 1.0 * 0.0; + let mut restitution = restitution; + if self.vertical_collision_below { + // Only a hard enough landing bounces, and never on honey. + let on = ( + self.position.x.floor() as i32, + (self.position.y - f64::from(0.2_f32)).floor() as i32, + self.position.z.floor() as i32, + ); + if -v.y <= self.gravity() + || restitution > 0.0 + && w.block_name(on.0, on.1, on.2) == "minecraft:honey_block" + { + restitution = 0.0; + } + } + let (compensation, drag) = if restitution > 0.0 { + let portion = moved.y / v.y; + let air_drag = f64::from(self.air_drag()); + (portion * self.gravity(), 1.0 + portion * (air_drag - 1.0)) + } else { + (0.0, 1.0) + }; + after.y = (compensation - v.y) * drag * restitution; } + self.velocity = after; } // Entity.checkSupportingBlock self.supporting = self.supporting_block(w, moved); self.movement_emission(w, moved, events); + // Entity.applyEffectsFromBlocks: bubble columns push the mob. + if crate::motion::bubble_column_push( + w.world, + w.registry, + w.facts, + w.collision, + self.bounds(), + &mut self.velocity, + ) { + self.fall_distance = 0.0; + } } /// LivingEntity.checkFallDamage: the fluid state refreshed out of water /// (touching water resets the fall), then Entity.checkFallDamage. @@ -469,16 +612,57 @@ impl Mob { } if self.on_ground { if self.fall_distance > 0.0 { + self.trample_farmland(w, events); self.cause_fall_damage(events); } self.fall_distance = 0.0; } } + /// `FarmlandBlock.fallOn`: a landing on farmland turns it to dirt with + /// chance `fallDistance - 0.5`, if mobs may grief and the mob's + /// `width * width * height` is over 0.512. `Block.pushEntitiesUp` lifts + /// the mob onto the dirt, which is a full block. + fn trample_farmland(&mut self, w: &MobWorld, events: &mut Vec) { + let p = self.block_on_legacy(w); + if w.block_name(p[0], p[1], p[2]) != "minecraft:farmland" { + return; + } + let roll = f64::from(self.random.next_float()); + let Some(dirt) = w.registry.default_state("minecraft:dirt") else { + return; + }; + if roll < self.fall_distance - 0.5 + && w.mob_griefing + && self.width() * self.width() * self.height() > 0.512 + { + events.push(MobEvent::SetBlock { + pos: p, + state: dirt, + }); + self.position.y = self.position.y.max(f64::from(p[1]) + 1.0); + } + } /// Entity.updateFluidInteraction: the fluid state, then touching water /// resets the fall and entering it (after the first tick) splashes. pub(super) fn update_fluids(&mut self, w: &MobWorld, events: &mut Vec) { let was_touching_water = self.fluids.in_water; self.fluids = w.fluids(self.bounds(), self.eye_y()); + // EntityFluidInteraction.applyCurrentTo: the flow pushes the mob. + if (self.fluids.in_water || self.fluids.in_lava) && self.pushed_by_fluid() { + let (water, lava) = w.fluid_currents(self.bounds()); + let lava_scale = if w.nether { + 0.007 + } else { + 0.0023333333333333335 + }; + let mut pushed = Pushed(&mut self.velocity); + if water.height > 0.0 { + let _ = water.apply_to(&mut pushed, 0.014); + } + if lava.height > 0.0 { + let _ = lava.apply_to(&mut pushed, lava_scale); + } + } if self.fluids.in_water { self.fall_distance = 0.0; if !was_touching_water && !self.first_tick { @@ -656,11 +840,20 @@ impl Mob { let at = [self.position.x, self.position.y, self.position.z]; events.push(MobEvent::Sound("entity.breeze.land", at, 1.0, 1.0)); } + // Creeper.causeFallDamage: the fall swells the fuse, up to five ticks + // short of exploding. + if self.species() == super::Species::Creeper { + self.swell = (self.swell + (self.fall_distance * 1.5) as i32).min(30 - 5); + } if self.kind.flags.fall_immune { return; } let power = self.fall_distance + 1.0e-6 - self.kind.safe_fall_distance; - let damage = (power * self.kind.fall_damage_multiplier).floor(); + let mut damage = (power * self.kind.fall_damage_multiplier).floor(); + // Frog.calculateFallDamage: five points less than the base damage. + if self.species() == super::Species::Frog { + damage -= 5.0; + } if damage > 0.0 { let at = [self.position.x, self.position.y, self.position.z]; let sound = if damage > 4.0 { @@ -747,9 +940,33 @@ impl Mob { let y = (self.position.y - 0.500_001).floor() as i32; w.facts.get(w.world.block(x, y, z)).friction } + /// `getAttributeValue(BOUNCINESS)`. + fn entity_bounciness(&self) -> f64 { + super::sulfur_cube::physics(self).map_or(0.0, |a| f64::from(a.bounciness.clamp(0.0, 1.0))) + } + /// `LivingEntity.computeModifiedFriction`. + fn modified_friction(friction: f32, modifier: f32) -> f32 { + (1.0 - (1.0 - friction) * modifier).clamp(0.0, 1.0) + } + /// `LivingEntity.getAirDrag`: what vertical air drag a bounce applies. + fn air_drag(&self) -> f32 { + let base = if self.kind.flags.omnidirectional { + 0.91 + } else { + 0.98 + }; + Self::modified_friction(base, self.air_drag_modifier()) + } + /// `getAttributeValue(AIR_DRAG_MODIFIER)`. + fn air_drag_modifier(&self) -> f32 { + super::sulfur_cube::physics(self).map_or(1.0, |a| a.air_drag_modifier.clamp(0.0, 2048.0)) + } fn travel_in_air(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { let friction = if self.on_ground { - self.block_friction(w) + // FRICTION_MODIFIER scales the block's slipperiness. + let modifier = super::sulfur_cube::physics(self) + .map_or(1.0, |a| a.friction_modifier.clamp(0.0, 2048.0)); + Self::modified_friction(self.block_friction(w), modifier) } else { 1.0 }; @@ -783,12 +1000,13 @@ impl Mob { self.velocity = Vec3::new(movement.x, y, movement.z); return; } - let drag = 0.91f32; + let air_drag_modifier = self.air_drag_modifier(); + let drag = Self::modified_friction(0.91, air_drag_modifier); let f = friction * drag; let vertical = if self.kind.flags.omnidirectional { drag } else { - 0.98 + Self::modified_friction(0.98, air_drag_modifier) }; self.velocity = Vec3::new( movement.x * f64::from(f), diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 9456c00a1..8be270ec1 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -359,11 +359,14 @@ fn can_attack(m: &Mob, w: &MobWorld, who: Who) -> bool { /// `Sensor.isEntityAttackable`: `TargetingConditions.forCombat()` within the /// follow range, in sight. fn attackable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + // The current ATTACK_TARGET is tested with ignoreInvisibilityTesting. + let current = mem_ref(m).attack_target.value() == Some(who); let range = m.attrs.follow_range; if !can_attack(m, w, who) { return false; } match who { + Who::Player if current => m.can_keep_target_player(w, range), Who::Player => m.can_target_player(w, range, true), Who::Mob(id) => { let Some(s) = w.seen(id) else { return false }; @@ -1137,6 +1140,7 @@ struct Quarry { position: Vec3, head_yaw: f32, height: f64, + passenger: bool, } fn quarry(w: &MobWorld, who: Who) -> Option { let t = w.target_info(who)?; @@ -1148,6 +1152,7 @@ fn quarry(w: &MobWorld, who: Who) -> Option { position: t.position, head_yaw, height: t.bounds.max_position().y - t.bounds.min_position().y, + passenger: t.passenger, }) } /// `BreezeUtil.randomPointBehindTarget`. @@ -1233,7 +1238,8 @@ fn shoot_tick(m: &mut Mob, cx: &mut Bx) { let firing = super::breeze::firing_y(m); let (xd, yd, zd) = ( q.position.x - m.position.x, - q.position.y + q.height * 0.3 - firing, + // target.getY(target.isPassenger() ? 0.8 : 0.3). + q.position.y + q.height * if q.passenger { 0.8 } else { 0.3 } - firing, q.position.z - m.position.z, ); let start = Vec3::new(m.position.x, firing, m.position.z); @@ -1242,14 +1248,19 @@ fn shoot_tick(m: &mut Mob, cx: &mut Bx) { start, Some(Who::Mob(m.id)), ); - // The new entity's own random spreads the shot (5 - difficulty * 4 at - // normal): not the breeze's. + // The new entity's own random spreads the shot (5 - difficulty id * 4): + // not the breeze's. let mut own = LegacyRandom::new( cx.now .wrapping_mul(0x5DEE_CE66) .wrapping_add(i64::from(m.id)), ); - p.shoot(&mut own, [xd, yd, zd], 0.7, -3.0); + p.shoot( + &mut own, + [xd, yd, zd], + 0.7, + 5.0 - f32::from(cx.w.difficulty.id) * 4.0, + ); cx.events.push(MobEvent::Projectile(p)); breeze_sound(m, cx, "entity.breeze.shoot", 1.5); } diff --git a/crates/horizon-client/src/mobs/panda.rs b/crates/horizon-client/src/mobs/panda.rs new file mode 100644 index 000000000..a5b8e2944 --- /dev/null +++ b/crates/horizon-client/src/mobs/panda.rs @@ -0,0 +1,1090 @@ +//! Pandas (`Panda`): the genes and what they show, the sit, lie-on-back, roll +//! and sneeze states with their goals, the unhappy and eat counters, and the +//! client side of the three amounts `PandaModel.setupAnim` reads. +//! +//! `extra.variant` and `extra.variant2` are the main and the hidden gene +//! (`MAIN_GENE_ID`, `HIDDEN_GENE_ID`); the rest is [`State`], whose `flags`, +//! `unhappy`, `sneeze` and `eat` are the synched data a server sends. +use super::{ + DamageKind, Mob, MobEvent, MobWorld, Species, Who, + body_anim::Panda as Pose, + finalize::{self, Attr}, + goals::{ + Avoid, AvoidEntity, Breed, Cx, Float, FollowParent, Goal, HurtByTarget, JUMP, LOOK, MOVE, + MeleeAttack, Panic, RandomLookAround, Stroll, Tempt, goal_clone, reduced, + }, +}; +use horizon_core::{ + geometry::{ + Vec3, + trig::{DEG_TO_RAD, Mth}, + }, + jmath, + random::{LegacyRandom, RandomSource}, +}; + +/// `Panda.Gene` ids (the order of `Gene.values()`). +pub const LAZY: u8 = 1; +pub const WORRIED: u8 = 2; +pub const PLAYFUL: u8 = 3; +pub const WEAK: u8 = 5; +pub const AGGRESSIVE: u8 = 6; +/// `Gene.getSerializedName`, by id. +pub const GENES: [&str; 7] = [ + "normal", + "lazy", + "worried", + "playful", + "brown", + "weak", + "aggressive", +]; + +/// `DATA_ID_FLAGS`. +pub const FLAG_SNEEZE: u8 = 2; +pub const FLAG_ROLL: u8 = 4; +pub const FLAG_SIT: u8 = 8; +pub const FLAG_ON_BACK: u8 = 16; + +/// The crumbs of one bite: where and how fast each one flies. +pub type Crumbs = Vec<([f64; 3], [f64; 3])>; + +#[derive(Clone, Debug, Default)] +pub struct State { + /// `DATA_ID_FLAGS` (sneezing, rolling, sitting, on its back). + pub flags: u8, + /// `UNHAPPY_COUNTER`, `SNEEZE_COUNTER` and `EAT_COUNTER`. + pub unhappy: i32, + pub sneeze: i32, + pub eat: i32, + got_bamboo: bool, + did_bite: bool, + /// `rollCounter`, which a client counts for itself. + pub roll_counter: i32, + roll_delta: [f64; 2], + /// `sitAmount`, `onBackAmount` and `rollAmount` with the tick before. + sit_amount: [f32; 2], + on_back_amount: [f32; 2], + roll_amount: [f32; 2], + /// `isScared` as of the last tick (the model and the item layer read it). + scared: bool, + /// `PandaLookAtPlayerGoal.lookAt`, which the breed goal can set. + look_at: Option, + /// What the game saw on the ground: any food within 6 blocks, and the + /// first within 8. + pub food_near: bool, + pub food_at: Option<[f64; 3]>, + /// The size of the stack in its mouth (the mob holds one item id). + pub held_count: u32, + /// What a window draws of the last bite and sneeze, taken by `effects`. + crumbs: Option, + sneezed: Option<([f64; 3], [f64; 3])>, +} + +fn st(m: &mut Mob) -> &mut State { + m.extra.panda.get_or_insert_with(Default::default) +} +pub fn get(m: &Mob) -> Option<&State> { + m.extra.panda.as_deref() +} +fn flag(m: &Mob, f: u8) -> bool { + get(m).is_some_and(|s| s.flags & f != 0) +} +fn set_flag(m: &mut Mob, f: u8, on: bool) { + let s = st(m); + if on { + s.flags |= f; + } else { + s.flags &= !f; + } +} + +// ---- genes ---------------------------------------------------------------- + +/// `Panda.getVariant`: the gene a panda shows. +pub fn variant(m: &Mob) -> u8 { + finalize::panda_variant(m.extra.variant, m.extra.variant2) +} +pub fn is_lazy(m: &Mob) -> bool { + variant(m) == LAZY +} +pub fn is_worried(m: &Mob) -> bool { + variant(m) == WORRIED +} +pub fn is_playful(m: &Mob) -> bool { + variant(m) == PLAYFUL +} +pub fn is_weak(m: &Mob) -> bool { + variant(m) == WEAK +} +/// `Panda.isAggressive`: the gene, not the mob flag. +pub fn is_aggressive(m: &Mob) -> bool { + variant(m) == AGGRESSIVE +} +/// `Panda.Gene.getRandom`. +fn random_gene(random: &mut impl RandomSource) -> u8 { + finalize::panda_gene(random.next_int_bound(16).unwrap_or(0)) +} +/// `Panda.setAttributes`: a weak panda has 10 health, a lazy one is slow. +pub fn set_attributes(m: &mut Mob) { + if is_weak(m) { + finalize::set_base(m, Attr::MaxHealth, 10.0); + } + if is_lazy(m) { + finalize::set_base(m, Attr::MovementSpeed, f64::from(0.07_f32)); + } +} +/// `Panda.getBreedOffspring`: `setGeneFromParents`, then `setAttributes`, on +/// a baby the game made (its attributes go back to the type's first). +pub fn inherit(child: &mut Mob, parent: &Mob, partner: &Mob) { + let r = &mut child.random; + let one_of = |p: &Mob, r: &mut LegacyRandom| { + if r.next_boolean() { + p.extra.variant + } else { + p.extra.variant2 + } + }; + let (mut main, mut hidden) = if r.next_boolean() { + let main = one_of(parent, r); + (main, one_of(partner, r)) + } else { + let main = one_of(partner, r); + (main, one_of(parent, r)) + }; + if r.next_int_bound(32).unwrap_or(1) == 0 { + main = random_gene(r); + } + if r.next_int_bound(32).unwrap_or(1) == 0 { + hidden = random_gene(r); + } + child.extra.variant = main; + child.extra.variant2 = hidden; + for a in [Attr::MaxHealth, Attr::MovementSpeed] { + if let Some(value) = finalize::default_value(child, a) { + finalize::set_base(child, a, value); + } + } + set_attributes(child); + child.health = finalize::max_health(child); +} +/// `Panda.Gene.CODEC` for `MainGene` and `HiddenGene`. +pub fn gene_from_name(name: &str) -> u8 { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + GENES.iter().position(|g| *g == name).unwrap_or(0) as u8 +} + +// ---- state ---------------------------------------------------------------- + +pub fn is_sitting(m: &Mob) -> bool { + flag(m, FLAG_SIT) +} +fn is_rolling(m: &Mob) -> bool { + flag(m, FLAG_ROLL) +} +fn is_on_back(m: &Mob) -> bool { + flag(m, FLAG_ON_BACK) +} +fn is_eating(m: &Mob) -> bool { + get(m).is_some_and(|s| s.eat > 0) +} +/// `Panda.isScared`: a worried panda in a thunderstorm. +fn is_scared(m: &Mob, thundering: bool) -> bool { + is_worried(m) && thundering +} +/// `Panda.canPerformAction`. +pub fn can_perform_action(m: &Mob, thundering: bool) -> bool { + !is_on_back(m) && !is_scared(m, thundering) && !is_eating(m) && !is_rolling(m) && !is_sitting(m) +} +fn sit(m: &mut Mob, on: bool) { + set_flag(m, FLAG_SIT, on); +} +fn eat(m: &mut Mob, on: bool) { + st(m).eat = i32::from(on); +} +/// `Panda.sneeze`: ending it resets the counter. +fn sneeze(m: &mut Mob, on: bool) { + set_flag(m, FLAG_SNEEZE, on); + if !on { + st(m).sneeze = 0; + } +} +/// `Panda.tryToSit`. +pub fn try_to_sit(m: &mut Mob) { + if !m.fluids.in_water { + m.ai.zza = 0.0; + m.nav_stop(); + sit(m, true); + } +} +/// `Panda.mobInteract` with bamboo in hand while it has a target. +pub fn got_bamboo(m: &mut Mob) { + st(m).got_bamboo = true; +} +/// `Panda.hurtServer`: any hurt gets it up. +pub fn hurt(m: &mut Mob) { + sit(m, false); +} +/// `Panda.doHurtTarget`: a bite that is not an aggressive panda's. +pub fn bit(m: &mut Mob) { + if !is_aggressive(m) { + st(m).did_bite = true; + } +} +/// `Panda.setOnBack(false)` from a click on a panda on its back. +pub fn get_up(m: &mut Mob) -> bool { + let was = is_on_back(m); + if was { + set_flag(m, FLAG_ON_BACK, false); + } + was +} +/// `Panda.eat(true)` at the first bite of what a player gave it. +pub fn start_eating(m: &mut Mob) { + eat(m, true); +} +/// `isScared` as of its last tick, for a click or a sneeze. +pub fn scared(m: &Mob) -> bool { + get(m).is_some_and(|s| s.scared) +} +/// `setItemSlot(MAINHAND, stack)` and `setGuaranteedDrop`, or just the size +/// of a stack it was given. +pub fn hold(m: &mut Mob, item: &str, count: u32, guaranteed: bool) { + finalize::set_item(m, super::gear::MAIN, item); + if guaranteed { + finalize::set_drop_chance(m, super::gear::MAIN, 2.0); + } + st(m).held_count = count; +} +/// What its goals look for on the ground, found by the game each tick. +pub fn set_food(m: &mut Mob, near: bool, at: Option<[f64; 3]>) { + let s = st(m); + s.food_near = near; + s.food_at = at; +} +/// The size of the stack in its mouth, for what it drops. +pub fn held_count(m: &Mob) -> u32 { + get(m).map_or(1, |s| s.held_count.max(1)) +} + +// ---- synched data --------------------------------------------------------- + +/// `DATA_ID_FLAGS` from a server: a sneeze that ends is a sneeze that was +/// done (`afterSneeze`'s particle). +pub fn set_flags(m: &mut Mob, flags: u8) { + if flag(m, FLAG_SNEEZE) && flags & FLAG_SNEEZE == 0 { + let at = [m.position.x, m.position.y, m.position.z]; + let particle = sneeze_particle(at, m.width(), m.body_yaw, m.eye_y(), m.velocity); + st(m).sneezed = Some(particle); + } + st(m).flags = flags; +} +/// `UNHAPPY_COUNTER` and `SNEEZE_COUNTER` from a server. +pub fn set_unhappy(m: &mut Mob, unhappy: i32) { + st(m).unhappy = unhappy; +} +pub fn set_sneeze(m: &mut Mob, sneeze: i32) { + st(m).sneeze = sneeze; +} +/// `EAT_COUNTER` from a server: a bite every five. +pub fn set_eat(m: &mut Mob, eat: i32) { + let bite = eat > 0 && eat % 5 == 0 && st(m).eat != eat && m.extra.main_hand.is_some(); + st(m).eat = eat; + if bite { + let crumbs = crumbs(m); + st(m).crumbs = Some(crumbs); + } +} +/// What the window draws since the last call: the crumbs of a bite and the +/// sneeze's particle (position, velocity). +pub fn effects(m: &mut Mob) -> (Option, Option<([f64; 3], [f64; 3])>) { + match m.extra.panda.as_deref_mut() { + Some(s) => (s.crumbs.take(), s.sneezed.take()), + None => (None, None), + } +} + +// ---- the tick -------------------------------------------------------------- + +/// `Entity.playSound`: at the feet, never from a silent mob. +fn play(m: &Mob, sound: &'static str, volume: f32, pitch: f32, events: &mut Vec) { + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound(sound, at, volume, pitch)); + } +} +fn lerp(a: f32, o: f32, n: f32) -> f32 { + o + a * (n - o) +} +/// `updateSitAmount`, `updateOnBackAnimation` and `updateRollAmount`. +fn step_amount(amount: &mut [f32; 2], on: bool) { + amount[0] = amount[1]; + amount[1] = if on { + (amount[1] + 0.15).min(1.0) + } else { + (amount[1] - 0.19).max(0.0) + }; +} +fn update_amounts(m: &mut Mob) { + let (sit, back, roll) = (is_sitting(m), is_on_back(m), is_rolling(m)); + let s = st(m); + step_amount(&mut s.sit_amount, sit); + step_amount(&mut s.on_back_amount, back); + step_amount(&mut s.roll_amount, roll); +} +/// `Panda.handleRoll`; a client counts the roll and leaves the motion to the +/// server. +fn handle_roll(m: &mut Mob, server: bool) { + let counter = { + let s = st(m); + s.roll_counter += 1; + s.roll_counter + }; + if counter > 32 { + set_flag(m, FLAG_ROLL, false); + } else if server { + let movement = m.velocity; + if counter == 1 { + let angle = m.yaw * DEG_TO_RAD; + let multiplier = if m.is_baby() { 0.1_f32 } else { 0.2_f32 }; + let delta = [ + movement.x + f64::from(-angle.msin() * multiplier), + movement.z + f64::from(angle.mcos() * multiplier), + ]; + st(m).roll_delta = delta; + m.velocity = Vec3::new(delta[0], 0.27, delta[1]); + } else if counter != 7 && counter != 15 && counter != 23 { + let [x, z] = st(m).roll_delta; + m.velocity = Vec3::new(x, movement.y, z); + } else { + let y = if m.on_ground { 0.27 } else { movement.y }; + m.velocity = Vec3::new(0.0, y, 0.0); + } + } +} +fn rnd(m: &mut Mob, bound: i32) -> i32 { + m.random.next_int_bound(bound).unwrap_or(0) +} +/// `Panda.handleEating`: the bite's sound and crumbs, and the end of a meal. +fn handle_eating(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let holds = m.extra.main_hand.is_some(); + if !is_eating(m) && is_sitting(m) && !is_scared(m, w.thundering) && holds && rnd(m, 80) == 1 { + eat(m, true); + } else if !holds || !is_sitting(m) { + eat(m, false); + } + if !is_eating(m) { + return; + } + // addEatingParticles + if st(m).eat % 5 == 0 { + let volume = 0.5 + 0.5 * rnd(m, 2) as f32; + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + play(m, "entity.panda.eat", volume, pitch, events); + if holds { + let crumbs = crumbs(m); + st(m).crumbs = Some(crumbs); + } + } + let count = st(m).eat; + if count > 80 && rnd(m, 20) == 1 { + let eats_from_ground = m.extra.main_hand.as_deref().is_some_and(|item| { + w.items + .and_then(|i| i.item_tags.get("minecraft:panda_eats_from_ground")) + .is_some_and(|tag| tag.contains(item)) + }); + if count > 100 && eats_from_ground { + super::drops::clear_slot(m, "mainhand"); + sit(m, false); + } + eat(m, false); + return; + } + st(m).eat += 1; +} +/// The six crumbs of `addEatingParticles`, drawn as the server draws them. +fn crumbs(m: &mut Mob) -> Crumbs { + let (x_rot, y_rot) = (-m.head_pitch * DEG_TO_RAD, -m.yaw * DEG_TO_RAD); + let body = -m.body_yaw * DEG_TO_RAD; + let (x, y, z) = (m.position.x, m.eye_y() + 1.0, m.position.z); + (0..6) + .map(|_| { + let r = &mut m.random; + let mut f = || f64::from(r.next_float()); + let v = Vec3::new((f() - 0.5) * 0.1, f() * 0.1 + 0.1, (f() - 0.5) * 0.1) + .rotate_x(x_rot) + .rotate_y(y_rot); + let p = Vec3::new((f() - 0.5) * 0.8, -f() * 0.6 - 0.3, 1.0 + (f() - 0.5) * 0.4) + .rotate_y(body); + ([p.x + x, p.y + y, p.z + z], [v.x, v.y + 0.05, v.z]) + }) + .collect() +} +/// `afterSneeze`'s particle, from the nose. +fn sneeze_particle( + at: [f64; 3], + width: f32, + body_yaw: f32, + eye: f64, + movement: Vec3, +) -> ([f64; 3], [f64; 3]) { + let reach = f64::from(width + 1.0) * 0.5; + let angle = body_yaw * DEG_TO_RAD; + ( + [ + at[0] - reach * f64::from(angle.msin()), + eye - f64::from(0.1_f32), + at[2] + reach * f64::from(angle.mcos()), + ], + [movement.x, 0.0, movement.z], + ) +} +/// `Panda.afterSneeze`: the particle, the sound, a start for the grown pandas +/// about, and a slime ball one sneeze in 700. +fn after_sneeze(m: &mut Mob, events: &mut Vec) { + let at = [m.position.x, m.position.y, m.position.z]; + let particle = sneeze_particle(at, m.width(), m.body_yaw, m.eye_y(), m.velocity); + st(m).sneezed = Some(particle); + play(m, "entity.panda.sneeze", 1.0, 1.0, events); + events.push(MobEvent::PandaSneezed { mob: m.id }); + events.push(MobEvent::GiftLoot { + mob: m.id, + table: "minecraft:gameplay/panda_sneeze", + at, + }); +} +/// `Panda.tick` after `super.tick()`. +pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let thundering = w.thundering; + if is_worried(m) { + if thundering && !m.fluids.in_water { + sit(m, true); + eat(m, false); + } else if !is_eating(m) { + sit(m, false); + } + } + if m.ai.target.is_none() { + let s = st(m); + s.got_bamboo = false; + s.did_bite = false; + } + let unhappy = st(m).unhappy; + if unhappy > 0 { + if let Some(t) = m.target_info(w) { + m.turn_to([t.position.x, t.eye_y, t.position.z], 90.0, 90.0); + } + if unhappy == 29 || unhappy == 14 { + play(m, "entity.panda.cant_breed", 1.0, 1.0, events); + } + st(m).unhappy -= 1; + } + if flag(m, FLAG_SNEEZE) { + let count = { + let s = st(m); + s.sneeze += 1; + s.sneeze + }; + if count > 20 { + sneeze(m, false); + after_sneeze(m, events); + } else if count == 1 { + play(m, "entity.panda.pre_sneeze", 1.0, 1.0, events); + } + } + if is_rolling(m) { + handle_roll(m, true); + } else { + st(m).roll_counter = 0; + } + if is_sitting(m) { + m.head_pitch = 0.0; + } + st(m).scared = is_scared(m, thundering); + update_amounts(m); + handle_eating(m, w, events); + // updateOnBackAnimation and updateRollAmount ran with the others. +} +/// `Panda.tick` for a panda a client only displays: the flags and counters +/// are the server's; the amounts and the roll count are the client's own. +pub fn client_tick(m: &mut Mob, thundering: bool) { + if is_rolling(m) { + handle_roll(m, false); + } else { + st(m).roll_counter = 0; + } + if is_sitting(m) { + m.head_pitch = 0.0; + } + st(m).scared = is_scared(m, thundering); + update_amounts(m); +} + +// ---- drawing --------------------------------------------------------------- + +/// `PandaRenderer.getTextureLocation`. +pub fn texture(m: &Mob) -> String { + let v = usize::from(variant(m)).min(GENES.len() - 1); + let gene = GENES[v]; + match (m.is_baby(), gene) { + (false, "normal") => "entity/panda/panda".into(), + (false, g) => format!("entity/panda/panda_{g}"), + (true, "normal") => "entity/panda/panda_baby".into(), + (true, g) => format!("entity/panda/{g}_panda_baby"), + } +} +/// What `PandaRenderState` gives `PandaModel.setupAnim`. +pub fn pose(m: &Mob, partial: f32) -> Pose { + let Some(s) = get(m) else { + return Pose::default(); + }; + let amount = |a: &[f32; 2]| lerp(partial, a[0], a[1]); + Pose { + unhappy: s.unhappy > 0, + sneezing: s.flags & FLAG_SNEEZE != 0, + sneeze_time: s.sneeze, + eating: s.eat > 0, + scared: s.scared, + sit_amount: amount(&s.sit_amount), + lie_on_back_amount: amount(&s.on_back_amount), + roll_amount: if m.is_baby() { + 0.0 + } else { + amount(&s.roll_amount) + }, + } +} +/// `PandaRenderer.setupRotations` after the common ones: the roll over, the +/// sit up and the lie on its back, and a scared panda's shiver. +pub fn rotations(m: &Mob, partial: f32) -> glam::Mat4 { + use glam::{Mat4, Vec3}; + let Some(s) = get(m) else { + return Mat4::IDENTITY; + }; + let baby = m.is_baby(); + let x_rot = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * partial; + let mut t = Mat4::IDENTITY; + let translate = |y: f32| Mat4::from_translation(Vec3::new(0.0, y, 0.0)); + let tilt = |degrees: f32| Mat4::from_rotation_x(degrees.to_radians()); + if s.roll_counter > 0 { + let time = s.roll_counter as f32 + partial; + let (pos, frac) = (time.floor() as i32, time.fract()); + let next = pos + 1; + let y = if baby { 0.3 } else { 0.8 }; + // getAngle: the angle between this step and the next, except in the + // last step of a quarter. + let angle = |this: f32, next_angle: f32, threshold: i32| { + if next < threshold { + lerp(frac, this, next_angle) + } else { + this + } + }; + let quarter = pos / 8; + if (0..4).contains(&quarter) { + let base = 90.0 * quarter as f32; + let step = |p: i32| base + 90.0 * (p - quarter * 8) as f32 / 7.0; + let a = angle(step(pos), step(next), (quarter + 1) * 8); + let lift = match quarter { + 0 => (y + 0.2) * (a / 90.0), + 1 => y + 0.2 + (y - 0.2) * (a - 90.0) / 90.0, + 2 => y + y * (270.0 - a) / 90.0, + _ => y * ((360.0 - a) / 90.0), + }; + t = t * translate(lift) * tilt(-a); + } + } + let sit = s.sit_amount; + let sit = lerp(partial, sit[0], sit[1]); + if sit > 0.0 { + t = t * translate(0.8 * sit) * tilt(lerp(sit, x_rot, x_rot + 90.0)) * translate(-sit); + if s.scared { + let age = m.age as f32 + partial; + let shake = (jmath::cos(f64::from(age * 1.25)) + * std::f64::consts::PI + * f64::from(0.05_f32)) as f32; + t *= Mat4::from_rotation_y(shake.to_radians()); + if baby { + t *= Mat4::from_translation(Vec3::new(0.0, 0.8, 0.55)); + } + } + } + let back = lerp(partial, s.on_back_amount[0], s.on_back_amount[1]); + if back > 0.0 { + let y = if baby { 0.5 } else { 1.3 }; + t = t * translate(y * back) * tilt(lerp(back, x_rot, x_rot + 180.0)); + } + t +} +/// `PandaHoldsItemLayer`: where the item in its mouth sits, in the model's +/// space, while it sits and eats. +pub fn item_offset(m: &Mob, partial: f32) -> Option { + let s = get(m)?; + if m.extra.main_hand.is_none() || s.flags & FLAG_SIT == 0 || s.scared { + return None; + } + let (mut y, mut z) = (1.4_f32, -0.6_f32); + if s.eat > 0 { + let bite = ((m.age as f32 + partial) * 0.6).msin(); + z -= 0.2 * bite + 0.2; + y -= 0.09 * bite; + } + Some(glam::Mat4::from_translation(glam::Vec3::new(0.1, y, z))) +} + +// ---- goals ----------------------------------------------------------------- + +/// A goal that starts only when `when` allows it (`PandaAttackGoal`, +/// `PandaAvoidGoal`). +#[derive(Clone, Debug)] +struct When { + goal: G, + when: fn(&Mob, &MobWorld) -> bool, +} +impl Goal for When { + goal_clone!(); + fn flags(&self) -> u8 { + self.goal.flags() + } + fn name(&self) -> &'static str { + self.goal.name() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (self.when)(m, cx.w) && self.goal.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.goal.can_continue(m, cx) + } + fn interruptable(&self) -> bool { + self.goal.interruptable() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.stop(m, cx) + } + fn every_tick(&self) -> bool { + self.goal.every_tick() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.tick(m, cx) + } +} +fn acts(m: &Mob, w: &MobWorld) -> bool { + can_perform_action(m, w.thundering) +} +fn avoids(m: &Mob, w: &MobWorld) -> bool { + is_worried(m) && acts(m, w) +} + +/// `PandaPanicGoal`: panics at the environment only, and not while sitting. +#[derive(Clone, Debug)] +struct PandaPanic(Panic); +impl Goal for PandaPanic { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn name(&self) -> &'static str { + "Panic" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + environmental(m) && self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if is_sitting(m) { + m.nav_stop(); + false + } else { + self.0.can_continue(m, cx) + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } +} +/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES`, or burning. +fn environmental(m: &Mob) -> bool { + m.fire_ticks > 0 && !m.kind.flags.fire_immune + || m.last_damage.is_some_and(|(d, t)| { + matches!( + d.kind, + DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Cactus + ) && i64::from(m.age) - t <= 40 + }) +} + +/// `PandaBreedGoal`: a panda in love finds no mate happy unless there is +/// bamboo about. +#[derive(Clone, Debug)] +struct PandaBreed { + breed: Breed, + unhappy_cooldown: i64, +} +impl PandaBreed { + /// `canFindBamboo`: any bamboo within 7 blocks and 2 up. + fn can_find_bamboo(m: &Mob, w: &MobWorld) -> bool { + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + (0..3).any(|y| { + (-7..=7).any(|x| { + (-7..=7) + .any(|z| w.block_name(at[0] + x, at[1] + y, at[2] + z) == "minecraft:bamboo") + }) + }) + } +} +impl Goal for PandaBreed { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn name(&self) -> &'static str { + "Breed" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !self.breed.can_use(m, cx) || st(m).unhappy != 0 { + return false; + } + if Self::can_find_bamboo(m, cx.w) { + return true; + } + if self.unhappy_cooldown <= i64::from(m.age) { + st(m).unhappy = 32; + self.unhappy_cooldown = i64::from(m.age) + 600; + // The nearest player it looks at while it sulks. + let seen = m.can_see_player(cx.w, 8.0); + st(m).look_at = seen.then_some(Who::Player); + } + false + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.breed.can_continue(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.breed.stop(m, cx) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.breed.tick(m, cx) + } +} + +/// `PandaHurtByTargetGoal`: a panda that was fed bamboo or bit lets go. +#[derive(Clone, Debug)] +struct PandaHurtBy(HurtByTarget); +impl Goal for PandaHurtBy { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn name(&self) -> &'static str { + self.0.name() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let s = st(m); + if s.got_bamboo || s.did_bite { + m.ai.target = None; + false + } else { + self.0.can_continue(m, cx) + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } +} + +/// What `PandaSitGoal` and `PandaLieOnBackGoal` ask each tick of their run. +fn rest_goes_on(m: &mut Mob) -> bool { + if !m.fluids.in_water && (is_lazy(m) || rnd(m, reduced(600)) != 1) { + rnd(m, reduced(2000)) != 1 + } else { + false + } +} + +/// `PandaSitGoal`: sit down with bamboo or cake in the mouth, or go to get +/// some from the ground. +#[derive(Clone, Debug, Default)] +struct PandaSit { + cooldown: i64, +} +impl Goal for PandaSit { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.cooldown > i64::from(m.age) + || m.is_baby() + || m.fluids.in_water + || !acts(m, cx.w) + || st(m).unhappy > 0 + { + return false; + } + m.extra.main_hand.is_some() || st(m).food_near + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + rest_goes_on(m) + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + if !is_sitting(m) && m.extra.main_hand.is_some() { + try_to_sit(m); + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.extra.main_hand.is_none() { + if let Some(at) = st(m).food_at { + m.nav_move_to_entity(cx.w, at, 0, f64::from(1.2_f32)); + } + } else { + try_to_sit(m); + } + self.cooldown = 0; + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(item) = m.extra.main_hand.clone() { + let count = held_count(m); + cx.events.push(MobEvent::DropItem { + item, + count, + at: [m.position.x, m.position.y, m.position.z], + }); + super::drops::clear_slot(m, "mainhand"); + let wait = if is_lazy(m) { + rnd(m, 50) + 10 + } else { + rnd(m, 150) + 10 + }; + self.cooldown = i64::from(m.age) + i64::from(wait) * 20; + } + sit(m, false); + } +} + +/// `PandaLieOnBackGoal`: a lazy panda now and then lies down. +#[derive(Clone, Debug, Default)] +struct PandaLieOnBack { + cooldown: i64, +} +impl Goal for PandaLieOnBack { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.cooldown < i64::from(m.age) && is_lazy(m) && acts(m, cx.w) && rnd(m, reduced(400)) == 1 + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + rest_goes_on(m) + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, FLAG_ON_BACK, true); + self.cooldown = 0; + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, FLAG_ON_BACK, false); + self.cooldown = i64::from(m.age) + 200; + } +} + +/// `PandaSneezeGoal`: a cub sneezes now and then, a weak one more. +#[derive(Clone, Debug)] +struct PandaSneeze; +impl Goal for PandaSneeze { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !(m.is_baby() && acts(m, cx.w)) { + return false; + } + if is_weak(m) && rnd(m, reduced(500)) == 1 { + true + } else { + rnd(m, reduced(6000)) == 1 + } + } + fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + false + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + sneeze(m, true); + } +} + +/// `PandaLookAtPlayerGoal`: looks at the nearest player, or at the one the +/// breed goal sulks at. +#[derive(Clone, Debug, Default)] +struct PandaLook { + look_time: i32, +} +impl PandaLook { + fn target(m: &Mob, cx: &Cx) -> Option<(Vec3, f64)> { + match get(m)?.look_at? { + Who::Player => { + cx.w.player + .as_ref() + .filter(|p| p.alive) + .map(|p| (p.position, p.eye[1])) + } + Who::Mob(id) => { + cx.w.seen(id) + .filter(|s| s.alive) + .map(|s| (s.position, s.eye_y)) + } + } + } +} +impl Goal for PandaLook { + goal_clone!(); + fn flags(&self) -> u8 { + LOOK + } + fn name(&self) -> &'static str { + "LookAtPlayer" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.random.next_float() >= 0.02 { + return false; + } + if st(m).look_at.is_none() { + let seen = m.can_see_player(cx.w, 6.0); + st(m).look_at = seen.then_some(Who::Player); + } + acts(m, cx.w) && st(m).look_at.is_some() + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some((at, _)) = Self::target(m, cx) else { + return false; + }; + m.distance_sqr(at) <= 36.0 && self.look_time > 0 + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + self.look_time = reduced(40 + rnd(m, 40)); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + st(m).look_at = None; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some((at, eye)) = Self::target(m, cx) { + m.look_at([at.x, eye, at.z]); + self.look_time -= 1; + } + } +} + +/// `PandaRollGoal`: a cub, or a playful panda, rolls over when it faces a +/// drop and now and then at random. +#[derive(Clone, Debug)] +struct PandaRoll; +impl Goal for PandaRoll { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !((m.is_baby() || is_playful(m)) && m.on_ground) || !acts(m, cx.w) { + return false; + } + let angle = m.yaw * DEG_TO_RAD; + let (x_dir, z_dir) = (-angle.msin(), angle.mcos()); + let step = |d: f32| if d.abs() > 0.5 { d.signum() as i32 } else { 0 }; + let (x, z) = ( + m.position.x.floor() as i32 + step(x_dir), + m.position.z.floor() as i32 + step(z_dir), + ); + let below = m.position.y.floor() as i32 - 1; + if cx.w.facts.is_air(cx.w.world.block(x, below, z)) { + return true; + } + if is_playful(m) && rnd(m, reduced(60)) == 1 { + true + } else { + rnd(m, reduced(500)) == 1 + } + } + fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + false + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, FLAG_ROLL, true); + } + fn interruptable(&self) -> bool { + false + } +} + +/// `Panda.registerGoals`. +pub fn register(m: &mut Mob) { + let food = m.kind.food.clone(); + let monsters = super::species::ALL + .iter() + .map(|d| d.species) + .filter(|s| super::ai::is_monster(*s)) + .collect::>(); + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(2, PandaPanic(Panic::new(2.0))); + g.add( + 2, + PandaBreed { + breed: Breed::new(1.0), + unhappy_cooldown: 0, + }, + ); + g.add( + 3, + When { + goal: MeleeAttack::new(f64::from(1.2_f32), true), + when: acts, + }, + ); + g.add(4, Tempt::new(1.0, food, false)); + g.add( + 6, + When { + goal: AvoidEntity::new(Avoid::Player, 8.0, 2.0, 2.0), + when: avoids, + }, + ); + g.add( + 6, + When { + goal: AvoidEntity::new(Avoid::Species(monsters), 4.0, 2.0, 2.0), + when: avoids, + }, + ); + g.add(7, PandaSit::default()); + g.add(8, PandaLieOnBack::default()); + g.add(8, PandaSneeze); + g.add(9, PandaLook::default()); + g.add(10, RandomLookAround::default()); + g.add(12, PandaRoll); + g.add(13, FollowParent::new(1.25)); + g.add(14, Stroll::avoiding_water(1.0)); + // alertOther: only an aggressive panda joins in. + m.ai.targets.add( + 1, + PandaHurtBy( + HurtByTarget::new() + .alert() + .alert_if(|s| s.species == Species::Panda && s.variant == AGGRESSIVE), + ), + ); +} diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index b62262bb0..f8bc9acfe 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -466,9 +466,44 @@ fn find_piglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { || w.prop(p[0], p[1], p[2], "lit") == Some("true")) }) } +/// `HoglinBase.throwTarget`: a shove away and up of the attack knockback less +/// the target's knockback resistance (none at all when that is used up). +fn throw_target(m: &mut Mob, who: Who, cx: &mut Cx) { + let resistance = match who { + Who::Mob(id) => cx.w.seen(id).map_or(0.0, |s| s.knockback_resistance), + Who::Player => 0.0, + }; + let power = m.kind.attack_knockback - resistance; + let Some(t) = cx.w.target_info(who) else { + return; + }; + if power <= 0.0 { + return; + } + let away = Vec3::new( + t.position.x - m.position.x, + 0.0, + t.position.z - m.position.z, + ); + // `yRot` takes the random whole number of degrees as radians, as vanilla does. + let angle = (m.random.next_int_bound(21).unwrap_or(10) - 10) as f32; + let scale = power * f64::from(m.random.next_float() * 0.5 + 0.2); + let push = away.normalize().scale(scale).rotate_y(angle); + let up = power * f64::from(m.random.next_float()) * 0.5; + cx.events.push(MobEvent::Push { + target: who, + velocity: [push.x, up, push.z], + }); +} /// `HoglinBase.hurtAndThrowTarget`. pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { m.extra.anim_ticks = 10; + // Entity event 4: clients start the headbutt. + cx.events.push(MobEvent::EntityEvent { + mob: m.id, + event: 4, + at: [m.position.x, m.position.y, m.position.z], + }); let attack = m.attrs.attack_damage; let amount = if !m.is_baby() && attack as i32 > 0 { attack / 2.0 + m.random.next_int_bound(attack as i32).unwrap_or(0) as f32 @@ -485,11 +520,7 @@ pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { }), } if !m.is_baby() { - // throwTarget: a strong shove up and away. - cx.events.push(MobEvent::Launch { - target: who, - up: 0.5 * f64::from(m.random.next_float()) + 0.3, - }); + throw_target(m, who, cx); } let sound = if m.species() == Species::Zoglin { "entity.zoglin.attack" @@ -603,6 +634,19 @@ pub fn piglin_pose( _ => {} } } +/// `Hoglin.handleEntityEvent` and `Zoglin`'s event 4 on a client: the +/// headbutt, which `aiStep` then counts down. +pub fn client_event(m: &mut Mob, event: u8) { + if event == 4 { + m.extra.anim_ticks = 10; + } +} +/// The headbutt's countdown (`Hoglin.aiStep`, `Zoglin.aiStep`) on a client. +pub fn client_tick(m: &mut Mob) { + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } +} /// `HoglinModel.setupAnim`. pub fn hoglin_anim(m: &Mob, s: &State, p: &mut Poses) { let (pos, sp) = (s.pos, s.speed); diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index d2ed62374..9b1d17eed 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -41,6 +41,11 @@ pub struct State { pub in_village: bool, /// A dropped ominous banner this raider may fetch. pub banner_at: Option<[f64; 3]>, + /// The item entity of `banner_at`. + pub banner_item: u32, + /// Banners with no path to them, and until when (game time): + /// `unreachableBannerCache`. + pub unreachable_banners: Vec<(u32, i64)>, /// Beds around the raid's centre. pub homes: Option>>, /// A ravager carrying a raider, set every tick from `Extra::rider`. @@ -116,7 +121,7 @@ pub fn register(m: &mut Mob) { } m.extra.raider = Some(Box::default()); m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); - m.ai.goals.add(1, ObtainBanner); + m.ai.goals.add(1, ObtainBanner::default()); m.ai.goals.add(3, PathfindToRaid); m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0)); m.ai.goals.add(5, Celebration); @@ -339,23 +344,37 @@ fn close_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { /// `Raider.ObtainRaidLeaderBannerGoal`: walk to a fallen ominous banner when /// the wave has no living leader (the game finds the banner and picks it up). -#[derive(Clone, Debug)] -pub struct ObtainBanner; +#[derive(Clone, Debug, Default)] +pub struct ObtainBanner { + path_to_banner: Option, +} impl Goal for ObtainBanner { goal_clone!(); fn flags(&self) -> u8 { MOVE } - fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { - state(m).is_some_and(|s| s.banner_at.is_some()) + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some((at, item)) = state(m).and_then(|s| s.banner_at.map(|at| (at, s.banner_item))) + else { + return false; + }; + // A banner with no path to it is skipped for 600 ticks. + let path = m.create_path_to_entity(cx.w, at, 1); + if path.as_ref().is_some_and(|p| p.reached) { + self.path_to_banner = path; + return true; + } + let now = cx.w.game_time; + let s = state_mut(m); + s.unreachable_banners.retain(|&(_, until)| now < until); + s.unreachable_banners.push((item, now + 600)); + false } fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { !m.ai.nav.is_done() && state(m).is_some_and(|s| s.banner_at.is_some()) } - fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some(at) = state(m).and_then(|s| s.banner_at) { - m.nav_move_to(cx.w, at, 1.15); - } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.nav_move_to_path(self.path_to_banner.take(), 1.15); } } diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index 49bac4d9f..4c179aeda 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -49,9 +49,14 @@ pub fn register(m: &mut Mob) { pub fn immobile(m: &Mob) -> bool { m.extra.counter > 0 || m.extra.counter2 > 0 || m.extra.anim_ticks > 0 } -/// `Ravager.doHurtTarget`: the bite animation. +/// `Ravager.doHurtTarget`: the bite animation (entity event 4 for clients). pub fn on_attack(m: &mut Mob, events: &mut Vec) { m.extra.counter = 10; + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 4, + at: [m.position.x, m.position.y, m.position.z], + }); events.push(MobEvent::Sound( "entity.ravager.attack", [m.position.x, m.position.y, m.position.z], @@ -67,6 +72,12 @@ pub fn blocked(m: &mut Mob, events: &mut Vec) -> bool { } if m.random.next_double() < 0.5 { m.extra.counter2 = 40; + // Entity event 39: the stun starts on clients. + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 39, + at: [m.position.x, m.position.y, m.position.z], + }); events.push(MobEvent::Sound( "entity.ravager.stunned", [m.position.x, m.position.y, m.position.z], @@ -155,6 +166,34 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } } +/// `Ravager.handleEntityEvent` 4 and 39 on a client. +pub fn entity_event(m: &mut Mob, event: u8) { + match event { + 4 => m.extra.counter = 10, + 39 => m.extra.counter2 = 40, + _ => {} + } +} +/// `Ravager.aiStep`'s clocks on a client: the bite and roar run down, and +/// the end of the stun starts the roar (the sounds, particles and the roar's +/// damage are the server's). +pub fn client_tick(m: &mut Mob) { + if !m.alive() { + return; + } + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } + if m.extra.counter > 0 { + m.extra.counter -= 1; + } + if m.extra.counter2 > 0 { + m.extra.counter2 -= 1; + if m.extra.counter2 == 0 { + m.extra.anim_ticks = 20; + } + } +} /// `Ravager.roar`: 6 damage to everything but illagers within 4 blocks, /// and a strong knockback (players too, through the client). fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec) { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 46eb14cc1..ee319caf6 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -14,6 +14,12 @@ use std::f32::consts::PI; /// A texture lookup into the shared atlas (name without namespace -> uv rect). pub type Atlas<'a> = &'a dyn Fn(&str) -> Option<[f32; 4]>; +/// The overlay code of an enchanted armour layer's glint. 7 and 8 are the +/// item glint and 9 to 12 Horizon's End-portal and breaking overlays, so 13 +/// marks the `ARMOR_ENTITY_GLINT_TEXTURING` sample: entity.wgsl transforms +/// the model UV and reads `enchanted_glint_armor`. +pub const ARMOR_GLINT: u32 = 13; + /// One draw of a model with a texture. pub struct Layer { pub model: String, @@ -137,6 +143,10 @@ pub fn body(m: &Mob) -> (String, String) { baby_or(m, "wolf#main", "wolf_baby#main"), super::tame::texture(m), ), + S::Panda => ( + baby_or(m, "panda#main", "panda_baby#main"), + super::panda::texture(m), + ), S::HappyGhast => ( baby_or(m, "happy_ghast#main", "happy_ghast_baby#main"), if baby { @@ -244,6 +254,20 @@ pub fn body(m: &Mob) -> (String, String) { baby_or(m, "armadillo#main", "armadillo_baby#main"), b(&m.kind.texture), ), + // FoxRenderer.getTextureLocation: snow variant, sleeping, baby. + S::Fox => ( + baby_or(m, "fox#main", "fox_baby#main"), + format!( + "entity/fox/fox{}{}{}", + if m.extra.variant == 0 { "" } else { "_snow" }, + if super::fox::flag(m, super::fox::SLEEPING) { + "_sleep" + } else { + "" + }, + if baby { "_baby" } else { "" }, + ), + ), S::Pig => { let model = if baby { "pig_baby#main".into() @@ -664,14 +688,6 @@ pub fn layers(m: &Mob) -> Vec { white, false, ), - // EnergySwirlLayer (the scroll is not reproduced: atlas sprites do not wrap). - S::Creeper if m.extra.charged => push( - &mut v, - "creeper#armor", - "entity/creeper/creeper_armor", - 0x80FF_FFFF, - true, - ), S::TropicalFish => { // TropicalFishPatternLayer: the pattern tinted with the pattern colour. let (model, letter, n) = if m.extra.variant < 6 { @@ -929,7 +945,13 @@ fn flip_degrees(m: &Mob) -> f32 { fn species_rotations(m: &Mob, alpha: f32) -> glam::Mat4 { match m.species() { Species::Cat => super::tame::cat_rotations(m, alpha), + Species::Panda => super::panda::rotations(m, alpha), Species::Shulker => super::shulker::rotations(m), + // FoxRenderer.setupRotations: the body follows a pounce's pitch. + Species::Fox if super::fox::flag(m, super::fox::POUNCING | super::fox::FACEPLANTED) => { + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + glam::Mat4::from_rotation_x((-pitch).to_radians()) + } _ => glam::Mat4::IDENTITY, } } @@ -1033,6 +1055,13 @@ fn draw_normals( let normal = poly.vertex_normal(normals); for v in poly.vertices { let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0); + // The armour glint scrolls the layer's model UV in the shader; + // the item path already passed its transformed UV. + let glint_uv = if overlay == ARMOR_GLINT { + [v[3], v[4]] + } else { + [0.0, 0.0] + }; out.push(Vertex { normal, pos: pos.to_array(), @@ -1043,6 +1072,7 @@ fn draw_normals( layer: overlay, color, light, + glint_uv, }); } } @@ -1203,9 +1233,9 @@ fn render_visible( light }; // EquipmentLayerRenderer draws armour with OverlayTexture.NO_OVERLAY: never - // the hurt tint, the glint (7) when enchanted. + // the hurt tint, the armour glint (13) when enchanted. let overlay = match armor_slot(&layer.model) { - Some(slot) if super::gear::enchanted(m, slot) => 7, + Some(slot) if super::gear::enchanted(m, slot) => ARMOR_GLINT, Some(_) => 0, None => overlay, }; @@ -1226,10 +1256,50 @@ fn render_visible( } } } + // EnergySwirlLayer: the armour model, additive, scrolling over the sprite. + if let Some((model, texture, x_offset)) = energy_swirl(m, s.age) + && let Some(part) = m.kind.layer(model) + && let Some([u0, v0, u1, v1]) = atlas(texture) + { + layer_poses.reset(part); + anim::setup(m, &s, &mut layer_poses, &data.animations); + // `RenderTypes.energySwirl`'s texture offset, as the sprite-local UV. + let (du, dv) = (x_offset % 1.0, s.age * 0.01 % 1.0); + let start = out.len(); + draw( + part, + base, + &layer_poses, + [du, dv, 1.0 + du, 1.0 + dv], + crate::breaking::stage_light([u1 - u0, v1 - v0]), + crate::breaking::stage_light([u0, v0]), + crate::gfx::ENERGY_SWIRL_OVERLAY, + out, + ); + // No lighting: the colour bytes carry the sprite's size (fs_energy_swirl). + for vertex in &mut out[start..] { + vertex.normal = [0; 4]; + } + } if shell_last { draw_body(out); } } +/// `EnergySwirlLayer`'s model, texture and `xOffset(t)` for a charged creeper +/// (`CreeperPowerLayer`) or a powered wither (`WitherArmorLayer`); `t` is `ageInTicks`. +fn energy_swirl(m: &Mob, t: f32) -> Option<(&'static str, &'static str, f32)> { + match m.species() { + Species::Creeper if m.extra.charged => { + Some(("creeper#armor", "entity/creeper/creeper_armor", t * 0.01)) + } + Species::Wither if super::wither::powered(m) => Some(( + "wither#armor", + "entity/wither/wither_armor", + (t * 0.02).mcos() * 3.0, + )), + _ => None, + } +} /// The equipment slot of a `HumanoidArmorLayer` model (`zombie#helmet`). fn armor_slot(model: &str) -> Option { Some(match model.rsplit('#').next()? { @@ -1363,6 +1433,12 @@ pub fn held_item_transform( data: &MobData, left: bool, ) -> Option { + // PandaHoldsItemLayer: the main hand's item in its mouth. + if m.species() == Species::Panda { + return super::panda::item_offset(m, alpha) + .filter(|_| !left) + .map(|offset| base_transform(m, alpha, camera) * offset); + } if !super::illager::shows_item(m) { return None; } diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index 32f952e15..3a962241c 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -49,7 +49,7 @@ pub fn register(m: &mut Mob) { // attach axis. m.ai.targets.add( 2, - NearestTarget::player(true).when(|m, w| { + NearestTarget::player(true).gate(peaceful_off).when(|m, w| { let Some(p) = &w.player else { return false }; let d = p.position.subtract(m.position); let axis = match m.extra.variant3 { @@ -325,6 +325,13 @@ pub fn look_yaw(m: &Mob, at: [f64; 3]) -> Option { f64::from(delta_forward), )) } +/// `Shulker.tick` on a client that is not the server: the lid eases to the +/// peek it was sent, and its body stays square (`ShulkerBodyRotationControl`). +pub fn client_tick(m: &mut Mob) { + m.anim.vo = m.anim.v; + ease_peek(m); + m.body_yaw = 0.0; +} /// `Shulker.hurtServer` before the damage: arrows bounce off a closed shell. pub fn accepts(m: &Mob, source: &Damage) -> bool { !(m.extra.counter == 0 && source.kind == DamageKind::Arrow) @@ -419,6 +426,11 @@ impl ProjectileWorld for Probe<'_, '_> { .full_collision } } +/// `level().getDifficulty() != Difficulty.PEACEFUL`, which the shulker's +/// attack goal and target goal check. +fn peaceful_off(_m: &Mob, w: &MobWorld) -> bool { + w.difficulty.effective != 0.0 +} /// `ShulkerAttackGoal`: open up and fire a bullet every one to five and a /// half seconds at a target within 20 blocks. #[derive(Clone, Debug)] @@ -434,7 +446,7 @@ impl Goal for ShulkerAttack { true } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - m.target_info(cx.w).is_some_and(|t| t.alive) + m.target_info(cx.w).is_some_and(|t| t.alive) && peaceful_off(m, cx.w) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { self.attack_time = 20; @@ -444,6 +456,9 @@ impl Goal for ShulkerAttack { set_peek(m, 0, cx.events); } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if !peaceful_off(m, cx.w) { + return; + } self.attack_time -= 1; let (Some(who), Some(t)) = (m.ai.target, m.target_info(cx.w)) else { return; diff --git a/crates/horizon-client/src/mobs/sniffer.rs b/crates/horizon-client/src/mobs/sniffer.rs index c0c8d8155..72aa76cc2 100644 --- a/crates/horizon-client/src/mobs/sniffer.rs +++ b/crates/horizon-client/src/mobs/sniffer.rs @@ -74,23 +74,8 @@ pub fn head_block(m: &Mob) -> [i32; 3] { /// the dropped seed and the water malus. pub fn ai_step(m: &mut Mob, events: &mut Vec) { use super::path::PathType; - let age = m.age as f32; let current = state(m); - if current != m.extra.scratch[0] as u8 { - // resetAnimations, then the state's own. - for s in &mut m.anim.states[..5] { - s.stop(); - } - match current { - FEELING_HAPPY => m.anim.states[0].start_if_stopped(age), - SCENTING => m.anim.states[1].start_if_stopped(age), - SNIFFING => m.anim.states[2].start_if_stopped(age), - DIGGING => m.anim.states[3].start_if_stopped(age), - RISING => m.anim.states[4].start_if_stopped(age), - _ => {} - } - m.extra.scratch[0] = i32::from(current); - } + animate(m); if current == DIGGING && now(m) == m.extra.ints[3] { let h = head_block(m); events.push(MobEvent::GiftLoot { @@ -110,6 +95,27 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { let wet = m.fluids.in_water || m.fire_ticks > 0; m.set_malus(PathType::Water, if wet { 0.0 } else { -1.0 }); } +/// `Sniffer.onSyncedDataUpdated(DATA_STATE)`: the animation states of the +/// state it changed to (on a client, each tick for the state it has). +pub fn animate(m: &mut Mob) { + let age = m.age as f32; + let current = state(m); + if current != m.extra.scratch[0] as u8 { + // resetAnimations, then the state's own. + for s in &mut m.anim.states[..5] { + s.stop(); + } + match current { + FEELING_HAPPY => m.anim.states[0].start_if_stopped(age), + SCENTING => m.anim.states[1].start_if_stopped(age), + SNIFFING => m.anim.states[2].start_if_stopped(age), + DIGGING => m.anim.states[3].start_if_stopped(age), + RISING => m.anim.states[4].start_if_stopped(age), + _ => {} + } + m.extra.scratch[0] = i32::from(current); + } +} /// The brain memory holding the explored positions /// (`SNIFFER_EXPLORED_POSITIONS`). pub fn to_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) { diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 58118d2c2..867869070 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -34,11 +34,15 @@ pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> b /// `DifficultyInstance`: the local difficulty at a position. #[derive(Clone, Copy, Debug)] pub struct LocalDifficulty { + /// The world difficulty id, 0 peaceful to 3 hard. + pub base: u8, pub effective: f32, /// The world difficulty is normal. pub normal: bool, /// The world difficulty is hard. pub hard: bool, + /// `Difficulty.getId`: 0 peaceful to 3 hard. + pub id: u8, } /// `DimensionType.MOON_BRIGHTNESS_PER_PHASE`. pub const MOON_BRIGHTNESS: [f32; 8] = [1.0, 0.75, 0.5, 0.25, 0.0, 0.25, 0.5, 0.75]; @@ -50,9 +54,11 @@ impl LocalDifficulty { let normal = base == 2; if base == 0 { return Self { + base, effective: 0.0, normal, hard, + id: base, }; } let global = ((total as f32 - 72000.0) / 1_440_000.0).clamp(0.0, 1.0) * 0.25; @@ -63,9 +69,11 @@ impl LocalDifficulty { local *= 0.5; } Self { + base, effective: f32::from(base) * (0.75 + global + local), normal, hard, + id: base, } } /// `getSpecialMultiplier`. @@ -101,6 +109,19 @@ pub fn armor_stats(item: &str) -> (f32, f32) { }; (points[slot], toughness) } +/// The armour and toughness a horse armor item adds in the body slot +/// (`ArmorMaterial.createAttributes(ArmorType.BODY)`). +pub fn horse_armor_stats(item: &str) -> (f32, f32) { + match item.strip_prefix("minecraft:") { + Some("leather_horse_armor") => (3.0, 0.0), + Some("copper_horse_armor") => (4.0, 0.0), + Some("iron_horse_armor") => (5.0, 0.0), + Some("golden_horse_armor") => (7.0, 0.0), + Some("diamond_horse_armor") => (11.0, 2.0), + Some("netherite_horse_armor") => (19.0, 3.0), + _ => (0.0, 0.0), + } +} /// `Mob.populateDefaultEquipmentSlots`: sometimes a set of armour, from the /// head down, of one random material. fn populate_armor(m: &mut Mob, d: &LocalDifficulty) { diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 92d1f21cd..64106574b 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1447,7 +1447,6 @@ impl Def { | S::IronGolem | S::Cat | S::Ocelot - | S::Frog | S::Slime | S::MagmaCube | S::Wither @@ -1581,7 +1580,7 @@ impl Def { S::Bee => "bee_food", S::Turtle => "turtle_food", S::Armadillo => "armadillo_food", - S::Frog => "frog_food", + S::Frog | S::Tadpole => "frog_food", S::Axolotl => "axolotl_food", S::Hoglin => "hoglin_food", S::Strider => "strider_food", @@ -1662,6 +1661,12 @@ impl Def { | S::Camel | S::CamelHusk => 400, S::Ocelot => 900, + // Guardian.getAmbientSoundInterval (the elder too). + S::Guardian | S::ElderGuardian => 160, + // Hoglin extends Animal; Shulker extends AbstractGolem. + S::Hoglin | S::Shulker => 120, + // Allay is a PathfinderMob: the Mob default. + S::Allay => 80, S::Squid | S::GlowSquid | S::Cod diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs index e97134505..9a71e9682 100644 --- a/crates/horizon-client/src/mobs/sulfur_cube.rs +++ b/crates/horizon-client/src/mobs/sulfur_cube.rs @@ -32,6 +32,12 @@ pub struct Archetype { pub contact_damage: Option, /// The knockback resistance modifier (the attribute clamps to 0..1). pub knockback_resistance: f64, + /// `Attributes.BOUNCINESS` (the modifier added to a base of 0). + pub bounciness: f32, + /// `Attributes.FRICTION_MODIFIER` and `AIR_DRAG_MODIFIER` (base 1 times + /// the archetype's factor). + pub friction_modifier: f32, + pub air_drag_modifier: f32, pub horizontal_power: f32, pub vertical_power: f32, pub hit_sound: &'static str, @@ -40,13 +46,16 @@ pub struct Archetype { pub push_threshold: f32, } macro_rules! arch { - ($n:literal, $b:expr, $e:expr, $c:expr, $k:expr, $h:expr, $v:expr, $cd:expr, $t:expr) => { + ($n:literal, $b:expr, $e:expr, $c:expr, $k:expr, $phys:expr, $h:expr, $v:expr, $cd:expr, $t:expr) => { Archetype { name: $n, buoyant: $b, explosion: $e, contact_damage: $c, knockback_resistance: $k, + bounciness: $phys.0, + friction_modifier: $phys.1, + air_drag_modifier: $phys.2, horizontal_power: $h, vertical_power: $v, hit_sound: concat!("entity.sulfur_cube.", $n, ".hit"), @@ -58,13 +67,25 @@ macro_rules! arch { } /// `data/minecraft/sulfur_cube_archetype/*.json`. pub const ARCHETYPES: [Archetype; 12] = [ - arch!("bouncy", true, None, None, -2.0, 0.4125, 0.105, 0.7, 0.3), + arch!( + "bouncy", + true, + None, + None, + -2.0, + (0.9, 0.3, 0.01), + 0.4125, + 0.105, + 0.7, + 0.3 + ), arch!( "explosive", true, Some((120, 3.0, false)), None, -1.0, + (0.5, 0.3, 0.3), 0.4125, 0.09, 0.7, @@ -76,6 +97,7 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, -1.0, + (0.5, 0.2, 0.01), 0.9125, 0.09, 0.9, @@ -87,6 +109,7 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, 0.5, + (0.1, 0.05, 0.01), 0.6625, 0.09, 1.0, @@ -98,20 +121,55 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, 0.7, + (0.2, 1.0, 0.01), 0.4125, 0.09, 0.7, 0.03 ), - arch!("hot", true, None, Some(1.0), -1.0, 0.4125, 0.09, 0.7, 0.2), - arch!("light", true, None, None, -1.0, 0.4125, 0.18, 0.7, 0.2), - arch!("regular", true, None, None, -1.0, 0.4125, 0.09, 0.5, 0.2), + arch!( + "hot", + true, + None, + Some(1.0), + -1.0, + (0.5, 0.3, 0.1), + 0.4125, + 0.09, + 0.7, + 0.2 + ), + arch!( + "light", + true, + None, + None, + -1.0, + (1.0, 0.3, 1.8), + 0.4125, + 0.18, + 0.7, + 0.2 + ), + arch!( + "regular", + true, + None, + None, + -1.0, + (0.5, 0.3, 0.1), + 0.4125, + 0.09, + 0.5, + 0.2 + ), arch!( "slow_bouncy", false, None, None, 0.4, + (0.6, 0.3, 0.05), 0.4125, 0.24, 0.5, @@ -123,6 +181,7 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, 0.5, + (0.4, 0.4, 0.1), 0.4125, 0.105, 0.9, @@ -134,12 +193,24 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, 0.8, + (0.1, 0.05, 0.01), 0.4125, 0.09, 1.0, 0.02 ), - arch!("sticky", false, None, None, -2.0, 0.4125, 0.09, 0.5, 0.05), + arch!( + "sticky", + false, + None, + None, + -2.0, + (0.0, 2.0, 0.01), + 0.4125, + 0.09, + 0.5, + 0.05 + ), ]; /// `SulfurCubeArchetype.DEFAULT_*`: no block swallowed. const DEFAULT_PUSH: (&str, f32, f32) = ("entity.sulfur_cube.regular.push", 0.5, 0.2); @@ -178,6 +249,15 @@ pub fn has_body(m: &Mob) -> bool { pub fn archetype(m: &Mob) -> Option<&'static Archetype> { m.extra.head.as_deref().and_then(archetype_of) } +/// The archetype whose bounciness, friction and air drag attributes a +/// sulfur cube's physics use (no other mob has those modifiers). +pub fn physics(m: &Mob) -> Option<&'static Archetype> { + if m.species() == super::Species::SulfurCube { + archetype(m) + } else { + None + } +} pub fn fuse(m: &Mob) -> i32 { m.extra.counter2 - 1 } @@ -371,6 +451,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { events.push(MobEvent::Explode( [m.position.x, m.position.y + 0.0625, m.position.z], power, + m.species(), )); m.removed = true; return; diff --git a/crates/horizon-client/src/mobs/sync.rs b/crates/horizon-client/src/mobs/sync.rs new file mode 100644 index 000000000..16cd2b30c --- /dev/null +++ b/crates/horizon-client/src/mobs/sync.rs @@ -0,0 +1,123 @@ +//! A server's mobs as a client animates them. The server thread, a LAN host +//! and a dedicated server run each mob's animation state (`ai::tick`); a +//! client of a server only gets synched data and entity events, and runs the +//! animation steps vanilla runs on the client (`Entity.onSyncedDataUpdated`, +//! `handleEntityEvent` and the per tick animation states). The server's half +//! is `game/lan.rs` (`mob_meta`, with `pose_id` here for index 6) and +//! `MobEvent::EntityEvent`; the client's half is `game/remote_mob_data.rs`, +//! `game/remote.rs` (`C::EntityEvent`) and `client_tick` here. +//! +//! To animate another species for a client: +//! - send its synched data in `mob_meta` and read it in +//! `remote_mob_data::apply`; +//! - send its poses in `pose_id` and read them in `set_pose`; +//! - broadcast its entity events with `MobEvent::EntityEvent` and handle +//! them in `entity_event`; +//! - run its client side animation in `client_tick`, sharing the function +//! with the server's `ai_step` where the server computes the same. +use super::{ + Mob, Species, allay, armadillo, axolotl, breeze, camel, copper_golem, creaking, frog, goat, + golem, guardian, piglin, ravager, shulker, sniffer, warden, +}; + +// `Pose.id` of the poses mobs take. +pub const STANDING: u8 = 0; +pub const LONG_JUMPING: u8 = 6; +pub const CROAKING: u8 = 8; +pub const USING_TONGUE: u8 = 9; +pub const SITTING: u8 = 10; +pub const ROARING: u8 = 11; +pub const SNIFFING: u8 = 12; +pub const EMERGING: u8 = 13; +pub const DIGGING: u8 = 14; +pub const SLIDING: u8 = 15; +pub const SHOOTING: u8 = 16; +pub const INHALING: u8 = 17; + +/// `Entity.DATA_POSE` (index 6) of a mob of a server: the pose its species +/// keeps in its own fields. +pub fn pose_id(m: &Mob) -> u8 { + match m.species() { + Species::Warden => warden::pose_id(m), + Species::Breeze => breeze::pose_id(m), + Species::Camel | Species::CamelHusk if camel::sitting(m) => SITTING, + Species::Frog => m.extra.pose, + _ => STANDING, + } +} + +/// `Entity.onSyncedDataUpdated(DATA_POSE)` on a client. +pub fn set_pose(m: &mut Mob, id: u8) { + let old = std::mem::replace(&mut m.extra.pose, id); + match m.species() { + Species::Frog if old != id => frog::pose_changed(m), + Species::Warden => warden::set_pose_id(m, id), + Species::Breeze => breeze::set_pose_id(m, id), + _ => {} + } +} + +/// The per tick animation steps of a client's mobs (after `m.age` moved on), +/// for the species whose server runs them in `ai_step`. `game_time` is the +/// client level's. +pub fn client_tick(m: &mut Mob, game_time: i64) { + match m.species() { + Species::Warden => warden::client_tick(m), + Species::Sniffer => sniffer::animate(m), + Species::Breeze => breeze::ai_step(m), + Species::Camel | Species::CamelHusk => camel::client_tick(m, game_time), + Species::Shulker => shulker::client_tick(m), + Species::Ravager => ravager::client_tick(m), + Species::Hoglin | Species::Zoglin => piglin::client_tick(m), + Species::IronGolem => golem::client_tick(m), + Species::Creaking => creaking::animate(m), + Species::Allay => { + m.anim.vo = m.anim.v; + allay::animate(m); + } + Species::Axolotl => axolotl::tick_animation(m), + Species::Guardian | Species::ElderGuardian => { + m.anim.vo = m.anim.v; + guardian::tail_and_spikes(m); + } + // The head spin's sound is the server's. + Species::CopperGolem if !m.no_ai => { + copper_golem::animate(m); + } + Species::Armadillo => armadillo::tick(m), + Species::Frog => frog::tick(m), + Species::Goat => goat::tick(m), + _ => {} + } +} + +/// `handleEntityEvent` of the mob types that start animations by an event +/// (`ClientboundEntityEventPacket` for a mob of a client). +pub fn entity_event(m: &mut Mob, event: u8) { + if m.species() == Species::Armadillo { + armadillo::entity_event(m, event); + } + if m.species() == Species::Goat { + goat::entity_event(m, event); + } + let age = m.age as f32; + match m.species() { + Species::Warden => match event { + // Attack: the roar ends, the swing starts. + 4 => { + m.anim.states[warden::ROAR].stop(); + m.anim.states[warden::ATTACK].start(age); + } + // The tendrils twitch. + 61 => m.anim.v[warden::TENDRIL] = 10.0, + // The sonic boom. + 62 => m.anim.states[warden::SONIC_BOOM].start(age), + _ => {} + }, + Species::Ravager => ravager::entity_event(m, event), + Species::Hoglin | Species::Zoglin => piglin::client_event(m, event), + Species::IronGolem => golem::client_event(m, event), + Species::Creaking => creaking::entity_event(m, event), + _ => {} + } +} diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 0b2075c96..f38296d4b 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -2,7 +2,7 @@ //! sitting, following and defending the owner, begging, anger and shaking //! off water (`Wolf`, `WolfModel`). use super::{ - Damage, Mob, MobEvent, MobWorld, Species, Who, + Damage, Mob, MobEvent, MobWorld, PlayerView, Species, Who, anim::{Poses, State}, goals::{ Breed, Cx, Float, Goal, HurtByTarget, JUMP, LOOK, LeapAtTarget, LookAtPlayer, MOVE, @@ -124,17 +124,23 @@ pub fn set_tame(m: &mut Mob, tame: bool) { m.attrs.max_health = 8.0; } } -/// The owner (the local player) when tame. -fn owner(m: &Mob, w: &MobWorld) -> Option<(Vec3, f64, bool)> { +/// `TamableAnimal.getOwner`: the player the saved owner UUID names, when it +/// is the one this mob sees; anyone else nearby is not its owner. +fn owner_view<'a>(m: &Mob, w: &'a MobWorld) -> Option<&'a PlayerView> { if !m.extra.tame { return None; } let p = w.player.as_ref()?; + (m.extra.owner == Some(p.uuid)).then_some(p) +} +/// The owner's position, eye height and spectator flag when tame. +fn owner(m: &Mob, w: &MobWorld) -> Option<(Vec3, f64, bool)> { + let p = owner_view(m, w)?; Some((p.position, p.eye[1], p.spectator)) } /// `TamableAnimal.unableToMoveToOwner`. fn unable_to_move_to_owner(m: &Mob, w: &MobWorld) -> bool { - m.extra.sitting || w.player.as_ref().is_some_and(|p| p.spectator) + m.extra.sitting || owner_view(m, w).is_some_and(|p| p.spectator) } /// `TamableAnimal.tryToTeleportToOwner`: ten tries around the owner. fn teleport_to_owner(m: &mut Mob, w: &MobWorld) { @@ -240,7 +246,7 @@ impl Goal for SitWhenOrdered { match owner_distance_sqr(m, cx.w) { None => true, Some(d) => { - let attacked = cx.w.player.as_ref().is_some_and(|p| p.hurt_by.is_some()); + let attacked = owner_view(m, cx.w).is_some_and(|p| p.hurt_by.is_some()); !(d < 144.0 && attacked) && m.extra.sitting } } @@ -388,7 +394,7 @@ impl Goal for OwnerHurtBy { if !m.extra.tame || m.extra.sitting { return false; } - let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.hurt_by) else { + let Some((who, at)) = owner_view(m, cx.w).and_then(|p| p.hurt_by) else { return false; }; at != self.timestamp && wants_to_attack(m, cx.w, who) @@ -399,7 +405,7 @@ impl Goal for OwnerHurtBy { .is_some_and(|t| t.alive) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.hurt_by) { + if let Some((who, at)) = owner_view(m, cx.w).and_then(|p| p.hurt_by) { m.ai.target = Some(who); self.timestamp = at; } @@ -422,7 +428,7 @@ impl Goal for OwnerHurt { if !m.extra.tame || m.extra.sitting { return false; } - let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.last_hurt) else { + let Some((who, at)) = owner_view(m, cx.w).and_then(|p| p.last_hurt) else { return false; }; at != self.timestamp && wants_to_attack(m, cx.w, who) @@ -433,7 +439,7 @@ impl Goal for OwnerHurt { .is_some_and(|t| t.alive) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.last_hurt) { + if let Some((who, at)) = owner_view(m, cx.w).and_then(|p| p.last_hurt) { m.ai.target = Some(who); self.timestamp = at; } @@ -822,7 +828,7 @@ impl Goal for CatLieOnBlock { m.extra.flag = self.0.reached; } } -/// `CatSitOnBlockGoal`: chests, lit furnaces and beds. +/// `CatSitOnBlockGoal`: unopened chests, lit furnaces and the foot of beds. #[derive(Clone, Debug)] struct CatSitOnBlock(super::goals::MoveToBlock); fn can_sit_on(w: &MobWorld, p: [i32; 3]) -> bool { @@ -833,7 +839,15 @@ fn can_sit_on(w: &MobWorld, p: [i32; 3]) -> bool { match f.name.as_ref() { // The lit state is the only light source a furnace has. "minecraft:furnace" => f.emission > 0, - _ => true, + // `ChestBlockEntity.getOpenCount(level, pos) < 1`: players' openers + // and the copper golems' own count. + "minecraft:chest" => { + let key = (p[0], p[1], p[2]); + !w.lid_openers.contains_key(&key) + && w.world.chest_openers.get(&key).is_none_or(|o| o.0 < 1) + } + // A bed's foot only (`BedBlock.PART != HEAD`). + _ => w.prop(p[0], p[1], p[2], "part") != Some("head"), } } impl Goal for CatSitOnBlock { diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index 3707f4bbe..25c610f69 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -498,15 +498,77 @@ fn zombified_piglin_step(m: &mut Mob, cx: &mut Cx) { } } } +/// `Entity.isInPowderSnow`: the mob's box, shrunk by `1.0E-5` as in +/// `checkInsideBlocks`, touches powder snow. +fn in_powder_snow(m: &Mob, w: &super::MobWorld) -> bool { + let b = m.bounds().deflate(Vec3::new(1e-5, 1e-5, 1e-5)); + let (min, max) = (b.min_position(), b.max_position()); + for x in min.x.floor() as i32..=max.x.floor() as i32 { + for y in min.y.floor() as i32..=max.y.floor() as i32 { + for z in min.z.floor() as i32..=max.z.floor() as i32 { + if &*w.facts.get(w.world.block(x, y, z)).name == "minecraft:powder_snow" { + return true; + } + } + } + } + false +} +/// `Skeleton.freezingTracker` (`ConversionTracker.tick`): 140 ticks in +/// powder snow start a conversion into a stray that takes 300 more; leaving +/// the snow stops it. `counter` is the affliction time (-1 outside the snow) +/// and `counter2` the conversion time plus one while converting, so that +/// reaching 0 is vanilla's `conversionTime < 0`. +fn skeleton_freezing(m: &mut Mob, cx: &mut Cx) { + if !in_powder_snow(m, cx.w) { + m.extra.counter = -1; + m.extra.counter2 = 0; + } else if m.extra.counter2 > 0 { + m.extra.counter2 -= 1; + if m.extra.counter2 == 0 { + // levelEvent 1048: the conversion sound at the stray. + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + cx.events.push(MobEvent::Sound( + "entity.skeleton.converted_to_stray", + m.center(), + 2.0, + pitch, + )); + cx.events.push(MobEvent::SpawnKind { + kind: "minecraft:stray".into(), + at: [m.position.x, m.position.y, m.position.z], + setup: super::SpawnSetup { + yaw: m.yaw, + persistent: m.persistent, + ..Default::default() + }, + }); + m.removed = true; + } + } else { + m.extra.counter += 1; + if m.extra.counter >= 140 { + m.extra.counter2 = 301; + } + } +} pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { if m.species() == Species::ZombieVillager { super::zombie_villager::step(m, cx); } + if m.species() == Species::Skeleton && m.alive() && !m.no_ai { + skeleton_freezing(m, cx); + } if m.species() == Species::ZombifiedPiglin { return zombified_piglin_step(m, cx); } if matches!(m.species(), Species::Zombie | Species::Husk) && m.alive() { - if m.extra.counter2 > 0 { + if m.extra.counter2 > 0 && !m.fluids.eye_in_water { + // ConversionTracker.tick: leaving the water ends a started + // conversion too. + m.extra.counter = -1; + m.extra.counter2 = 0; + } else if m.extra.counter2 > 0 { m.extra.counter2 -= 1; if m.extra.counter2 == 0 { let (kind, sound) = if m.species() == Species::Husk { diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 20280b190..632ba8c81 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -353,18 +353,14 @@ pub fn food_points(item: &str) -> i32 { _ => 0, } } -/// The farmer's `requestedItems`. +/// The farmer's `requestedItems` (`VillagerProfession.FARMER`). Food is picked +/// up and traded separately, through its villager food value. pub fn farmer_items() -> &'static [&'static str] { &[ - "minecraft:bread", - "minecraft:potato", - "minecraft:carrot", "minecraft:wheat", "minecraft:wheat_seeds", - "minecraft:beetroot", "minecraft:beetroot_seeds", - "minecraft:torchflower_seeds", - "minecraft:pitcher_pod", + "minecraft:bone_meal", ] } /// A villager's `requestedItems` by profession. diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 2052eef4c..676d9b713 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -789,14 +789,7 @@ pub fn golem_detected(m: &mut Mob, now: i64) { // ---- Behaviours --------------------------------------------------------- -/// The POI types villagers use. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Poi { - /// A job site, by profession index. - Job(u8), - Home, - Meeting, -} +pub use crate::poi_sections::Poi; impl Poi { fn max_tickets(self) -> usize { match self { @@ -2918,11 +2911,18 @@ impl B { let mut bodies = Vec::new(); if let Some(t) = cx.w.target_info(target) { let (min, max) = (t.bounds.min_position(), t.bounds.max_position()); - bodies.push((t.position, max.x - min.x, max.y - min.y)); + bodies.push((partner, t.position, max.x - min.x, max.y - min.y)); } - bodies.push((m.position, f64::from(m.width()), f64::from(m.height()))); - for (feet, width, height) in bodies { + bodies.push(( + m.id, + m.position, + f64::from(m.width()), + f64::from(m.height()), + )); + for (mob, feet, width, height) in bodies { cx.events.push(MobEvent::AroundSelf { + mob, + event: 12, kind: "heart", feet: [feet.x, feet.y, feet.z], width, @@ -3605,6 +3605,8 @@ fn pois_scan_order(_m: &Mob, found: &[(Poi, [i32; 3])]) -> Vec { /// `AbstractVillager.addParticlesAroundSelf(HAPPY_VILLAGER)` on the client. fn happy_particles(m: &Mob, cx: &mut Bx) { cx.events.push(MobEvent::AroundSelf { + mob: m.id, + event: 14, kind: "happy_villager", feet: [m.position.x, m.position.y, m.position.z], width: f64::from(m.width()), diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 11161ef7c..747443577 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -67,6 +67,29 @@ impl Pose { } } } +/// `Pose.id` of the poses a warden takes (`sync::pose_id`). +pub fn pose_id(m: &Mob) -> u8 { + match pose(m) { + Pose::Standing => 0, + Pose::Roaring => 11, + Pose::Sniffing => 12, + Pose::Emerging => 13, + Pose::Digging => 14, + } +} +/// `Entity.onSyncedDataUpdated(DATA_POSE)` on a client. +pub(super) fn set_pose_id(m: &mut Mob, id: u8) { + set_pose( + m, + match id { + 11 => Pose::Roaring, + 12 => Pose::Sniffing, + 13 => Pose::Emerging, + 14 => Pose::Digging, + _ => Pose::Standing, + }, + ); +} /// The warden's pose (kept in `Extra.counter` so it can be read while the /// brain is being ticked). pub fn pose(m: &Mob) -> Pose { @@ -434,6 +457,11 @@ pub fn do_push(m: &mut Mob, w: &MobWorld, who: Who, events: &mut Vec) pub(super) fn do_hurt_target(m: &mut Mob, target: Who, w: &MobWorld, events: &mut Vec) { m.anim.states[ROAR].stop(); m.anim.states[ATTACK].start(m.age as f32); + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 4, + at: at(m), + }); let pitch = voice_pitch(m); sound(m, "entity.warden.attack_impact", 10.0, pitch, events); warden_brain::mem(m).sonic_boom_cooldown.set_ttl((), 40); @@ -546,6 +574,11 @@ fn receive_vibration(m: &mut Mob, w: &MobWorld, info: Info, events: &mut Vec) { - let Some(st) = m.extra.warden.as_ref() else { - return; - }; - let client_anger = st.client_anger; - let delay = heart_beat_delay(client_anger); - if i64::from(m.age) % i64::from(delay) == 0 { - m.anim.v[HEART] = 10.0; + if heartbeat(m) { events.push(MobEvent::LevelEventSound { sound: "entity.warden.heartbeat", at: at(m), @@ -745,6 +772,30 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { spread: 0.2, }); } + animate(m, events); +} +/// The heart's beat on its clock, from the client's anger level: whether +/// this tick has one (its sound is the caller's). +fn heartbeat(m: &mut Mob) -> bool { + let Some(st) = m.extra.warden.as_ref() else { + return false; + }; + let delay = heart_beat_delay(st.client_anger); + let beat = i64::from(m.age) % i64::from(delay) == 0; + if beat { + m.anim.v[HEART] = 10.0; + } + beat +} +/// `Warden.tick` on a client that is not the server: the heart and tendril +/// animations and the keyframes that ended. Its sounds and particles come +/// from the server. +pub fn client_tick(m: &mut Mob) { + m.anim.vo = m.anim.v; + heartbeat(m); + animate(m, &mut Vec::new()); +} +fn animate(m: &mut Mob, events: &mut Vec) { // The animation values count down after the sync of the last tick. for slot in [TENDRIL, HEART] { if m.anim.v[slot] > 0.0 { diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 8caafefc9..667bbedf0 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -937,6 +937,11 @@ impl B { mm.sonic_boom_sound_delay.set_ttl((), SONIC_SOUND_DELAY); // Entity event 62: the sonic boom keyframes start. m.anim.states[warden::SONIC_BOOM].start(m.age as f32); + cx.events.push(MobEvent::EntityEvent { + mob: m.id, + event: 62, + at: [m.position.x, m.position.y, m.position.z], + }); sound(m, "entity.warden.sonic_charge", 3.0, 1.0, cx.events); true } diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index 6c3316ac7..2fdd16372 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -221,6 +221,7 @@ pub fn custom_server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec { /// The biome's base temperature at a position. @@ -249,6 +251,7 @@ impl MobWorld<'_> { can_be_seen_as_enemy: true, is_player: true, creative: p.creative, + passenger: p.passenger, }), Who::Mob(id) => self.seen(id).map(|s| TargetInfo { position: s.position, @@ -258,6 +261,7 @@ impl MobWorld<'_> { can_be_seen_as_enemy: !s.playing_dead, is_player: false, creative: false, + passenger: s.passenger, }), } } diff --git a/crates/horizon-client/src/model_library.rs b/crates/horizon-client/src/model_library.rs index 018bc6af2..5edf0f5a4 100644 --- a/crates/horizon-client/src/model_library.rs +++ b/crates/horizon-client/src/model_library.rs @@ -232,18 +232,7 @@ mod tests { .block_library(&fixture.0, vec!["horizon:nested/child".into()]) .is_ok() ); - let library = parsed.into_item_library(); - assert!(library.is_err()); - fs::write(fixture.0.join("items.json"), "{")?; - let load = || { - crate::item_render::ItemRenderer::load_with_library(&fixture.0, library.clone()) - .err() - .unwrap() - .to_string() - }; - assert!(!load().starts_with("item models:")); - fs::write(fixture.0.join("items.json"), "{}")?; - assert!(load().starts_with("item models:")); + assert!(parsed.into_item_library().is_err()); Ok(()) } } diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index a0a06a83a..d357a196f 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -44,7 +44,7 @@ use std::{ pub(crate) mod environment; mod fluids; -pub use fluids::{FluidResources, FluidTags, LAVA, PlayerFluids, WATER}; +pub use fluids::{FluidResources, FluidTags, LAVA, PlayerFluids, WATER, bubble_column_push}; pub struct MotionResources { pub attributes: Arc, @@ -55,6 +55,10 @@ pub struct MotionResources { /// `BlockTags.SOUL_SPEED_BLOCKS`: what Soul Speed's effects look for. pub soul_speed_blocks: BTreeSet, pub fall_reset: BTreeSet, + /// `BlockTags.INSIDE_STEP_SOUND_BLOCKS`. + pub inside_step_sound: BTreeSet, + /// `BlockTags.COMBINATION_STEP_SOUND_BLOCKS`. + pub combination_step_sound: BTreeSet, /// `BlockTags.CRYSTAL_SOUND_BLOCKS`: blocks that chime under footsteps. pub crystal_sound: BTreeSet, pub landing: BlockLandingRegistry, @@ -117,6 +121,8 @@ impl MotionResources { glide_through: tag("minecraft:can_glide_through")?, soul_speed_blocks: tag("minecraft:soul_speed_blocks")?, fall_reset: tag("minecraft:fall_damage_resetting")?, + inside_step_sound: tag("minecraft:inside_step_sound_blocks")?, + combination_step_sound: tag("minecraft:combination_step_sound_blocks")?, crystal_sound: tag("minecraft:crystal_sound_blocks")?, }) } @@ -162,11 +168,12 @@ pub enum MotionEvent { position: BlockPos, }, /// `Entity.walkingStepSound` on this block: `Player.playStepSound` - /// muffles it under a swim sound when `in_water`. + /// mutes it (`playMuffledStepSound`) under a swim sound in water or + /// under a combination block's own step. Emission { position: BlockPos, state: BlockStateId, - in_water: bool, + muffled: bool, }, /// `Entity.playAmethystStepSound`: `block.amethyst_block.chime`. Chime { @@ -259,6 +266,9 @@ pub struct PlayerMotion { pub history: MovementHistory, pub fall_distance: f64, pub stuck_multiplier: Vec3, + /// `Entity.pistonDeltas` and `pistonDeltasGameTime`: how far a moving + /// block has pushed this entity this tick (0.51 at most on any axis). + pub piston: horizon_world::piston_movement::PistonMovement, pub yaw: f32, pub head_yaw: f32, pub jumping: bool, @@ -472,6 +482,7 @@ impl PlayerMotion { history: MovementHistory::default(), fall_distance: 0.0, stuck_multiplier: Vec3::ZERO, + piston: Default::default(), yaw: 0.0, head_yaw: 0.0, jumping: false, @@ -1907,8 +1918,14 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { fn set_collision_flags(&mut self, value: CollisionFlags) { self.player.collision = value; } - fn limit_piston_movement(&mut self, _: Vec3) -> Result { - Err("piston movement requires a ticking entity runtime".into()) + /// `Entity.limitPistonMovement`: the per-tick 0.51-block budget shared by + /// every move on an axis. A failed game-time read leaves the accumulator + /// as it was, as native does. + fn limit_piston_movement(&mut self, movement: Vec3) -> Result { + let time = self.scene.game_time; + self.player + .piston + .limit(movement, || Ok::>(time)) } fn stuck_multiplier(&self) -> Vec3 { self.player.stuck_multiplier @@ -1927,7 +1944,8 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { let input = EdgeBackoffInput { movement, bounds: self.player.bounds(), - flying: false, + // Player.maybeBackOffFromEdge: not while flying. + flying: self.player.flying, self_or_player: matches!(mover, MoverType::SelfMovement | MoverType::Player), fall_distance: self.player.fall_distance, query_budget: 1_000_000, @@ -2170,18 +2188,54 @@ impl MovementEmissionWorld for MotionWorld<'_, '_, '_> { fn in_water(&mut self) -> Result { Ok(self.player.fluids.was_touching_water) } - /// `Player.playStepSound`: in water a swim sound, then the step muffled. + /// `Player.playStepSound`: in water a swim sound, then the step muffled; + /// on land the step of an inside-sound block above the floor, or of a + /// combination block above it with the floor's step muffled. fn walking_step_sound(&mut self, position: BlockPos, state: BlockStateId) -> Result<()> { - let in_water = self.player.fluids.was_touching_water; - if in_water { + let muffled = self.player.fluids.was_touching_water; + let mut stepped = false; + if muffled { self.water_swim_sound()?; + } else { + // Entity.getPrimaryStepSoundBlockPos. + let above = BlockPos { + y: position.y + 1, + ..position + }; + let above_state = self.block(above); + let name = &self + .assets + .registry + .state(above_state) + .ok_or("missing scene state")? + .name; + let combination = self.resources.combination_step_sound.contains(name); + if combination || self.resources.inside_step_sound.contains(name) { + self.player.events.push(MotionEvent::Emission { + position: above, + state: above_state, + muffled: false, + }); + if combination { + // Entity.playCombinationStepSounds. + self.player.events.push(MotionEvent::Emission { + position, + state, + muffled: true, + }); + } + stepped = true; + } } - self.player.events.push(MotionEvent::Emission { - position, - state, - in_water, - }); - // Entity.walkingStepSound: the amethyst chime after the step. + if !stepped { + self.player.events.push(MotionEvent::Emission { + position, + state, + muffled, + }); + } + // Entity.walkingStepSound: the amethyst chime after the step, by the + // floor's state even when the step sound was the block above's. let name = &self .assets .registry diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index 894e6d907..e3751f0c6 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -119,6 +119,67 @@ impl PlayerMotion { !self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&FluidTags, LAVA) } } +/// `BubbleColumnBlock.entityInside` for an entity that is not the player (a mob, +/// a dropped item, an ender pearl): the bubble columns its box touches push it +/// up or drag it down, harder at the surface (`Entity.handleOnAboveBubbleColumn` +/// and `handleOnInsideBubbleColumn`). Returns whether it was inside a column +/// below the surface, which resets its fall distance. +pub fn bubble_column_push( + world: &World, + registry: &horizon_world::registry::BlockRegistry, + facts: &crate::blocks::BlockFacts, + collision: &horizon_world::block_collision::BlockCollisionRegistry<'_>, + bounds: Aabb, + velocity: &mut Vec3, +) -> bool { + let b = bounds.deflate(Vec3::new( + f64::from(1.0e-5f32), + f64::from(1.0e-5f32), + f64::from(1.0e-5f32), + )); + let (lo, hi) = (b.min_position(), b.max_position()); + let mut reset_fall = false; + for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) { + for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { + for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) { + let state = world.block(x, y, z); + if &*facts.get(state).name != "minecraft:bubble_column" { + continue; + } + let drag = registry + .state(state) + .and_then(|s| s.properties.get("drag")) + .is_some_and(|d| d == "true"); + let above = world.block(x, y + 1, z); + // stateAbove.getCollisionShape(level, pos): the shape is asked + // at the column's own position. + let mut scene = SceneCollisions { + world, + binding: collision, + subject: None, + }; + let context = horizon_world::collision_context::CollisionContext::empty(false); + let nothing_above = collision + .collision_shape_with_context( + &mut scene, + above, + BlockPos::new(x, y, z), + &context, + ) + .is_ok_and(|shape| shape.is_empty()) + && facts.get(above).fluid == crate::blocks::Fluid::None; + velocity.y = match (nothing_above, drag) { + (true, true) => (-0.9_f64).max(velocity.y - 0.03), + (true, false) => 1.8_f64.min(velocity.y + 0.1), + (false, true) => (-0.3_f64).max(velocity.y - 0.03), + (false, false) => 0.7_f64.min(velocity.y + 0.06), + }; + reset_fall |= !nothing_above; + } + } + } + reset_fall +} /// Which fluids `FluidTags.WATER` and `FluidTags.LAVA` hold. pub struct FluidTags; impl FluidMembership for FluidTags { diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 85882009f..fbcf8ba98 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -4,6 +4,8 @@ //! OptionsList screens and drawn with the shared widgets. use std::time::Instant; +pub use crate::settings::Opt; + use crate::{ gamepad::{self, GlyphStyle}, hud::{HudAtlas, HudBatch, rgba}, @@ -14,95 +16,6 @@ use crate::{ ui, }; -/// One option instance. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Opt { - Fov, - RenderDistance, - SimulationDistance, - Sensitivity, - WheelSensitivity, - InvertY, - DiscreteScroll, - Volume(usize), - GuiScale, - ViewBobbing, - Gamma, - MaxFps, - Vsync, - Fullscreen, - SmoothLighting, - Clouds, - CloudRange, - Particles, - EntityDistance, - EntityShadows, - BiomeBlend, - Preset, - Mipmaps, - WeatherRadius, - ChunkFade, - Vignette, - Autosave, - CutoutLeaves, - ImprovedTransparency, - AttackIndicator, - InactivityFps, - ChunkBuilder, - MenuBlur, - ToggleCrouch, - ToggleSprint, - AutoJump, - ChatVisibility, - ChatColors, - ChatLinks, - ChatLinksPrompt, - ChatOpacity, - TextBackgroundOpacity, - ChatScale, - ChatWidth, - ChatHeightFocused, - ChatHeightUnfocused, - ChatLineSpacing, - AutoSuggestions, - ReducedDebugInfo, - HighContrast, - ShowSubtitles, - MusicFrequency, - NotificationDisplayTime, - Narrator, - TextBackground, - ChatDelay, - DistortionEffects, - FovEffects, - DarknessPulsing, - DamageTilt, - GlintSpeed, - GlintStrength, - HideLightningFlashes, - MonochromeLogo, - PanoramaSpeed, - HideSplashTexts, - NarratorHotkey, - RotateWithMinecarts, - HighContrastBlockOutlines, - ForceUnicode, - JapaneseGlyphs, - /// Horizon's controller settings (`horizon-controller.txt`). - PadEnabled, - PadVibration, - PadAdaptiveTriggers, - PadLightbar, - PadLookSensitivity, - PadInvertX, - PadInvertY, - PadToggleSneak, - PadMoveDeadzone, - PadLookDeadzone, - PadGlyphs, - PadMenuNav, - PadKeyboard, -} fn tr(key: &str) -> Text { Text::translate(key, &[]) } @@ -168,9 +81,12 @@ impl Opt { Opt::Narrator | Opt::NarratorHotkey | Opt::ChatDelay + // Stored, but there are no blocked players, signed chat or + // chat drafts yet. + | Opt::HideMatchedNames + | Opt::OnlySecureChat + | Opt::SaveChatDrafts | Opt::DistortionEffects - | Opt::GlintSpeed - | Opt::GlintStrength | Opt::MonochromeLogo | Opt::RotateWithMinecarts | Opt::HighContrastBlockOutlines @@ -185,6 +101,9 @@ impl Opt { Opt::Narrator => "narrator", Opt::TextBackground => "backgroundForChatOnly", Opt::ChatDelay => "chatDelay", + Opt::HideMatchedNames => "hideMatchedNames", + Opt::OnlySecureChat => "onlyShowSecureChat", + Opt::SaveChatDrafts => "saveChatDrafts", Opt::DistortionEffects => "screenEffectScale", Opt::FovEffects => "fovEffectScale", Opt::DarknessPulsing => "darknessEffectScale", @@ -253,6 +172,9 @@ impl Opt { Opt::ChatHeightUnfocused => "options.chat.height.unfocused", Opt::ChatLineSpacing => "options.chat.line_spacing", Opt::AutoSuggestions => "options.autoSuggestCommands", + Opt::HideMatchedNames => "options.hideMatchedNames", + Opt::OnlySecureChat => "options.onlyShowSecureChat", + Opt::SaveChatDrafts => "options.chat.drafts", Opt::ReducedDebugInfo => "options.reducedDebugInfo", Opt::HighContrast => "options.accessibility.high_contrast", Opt::ShowSubtitles => "options.showSubtitles", @@ -526,6 +448,9 @@ impl Opt { Opt::HideLightningFlashes => on_off(s.file.bool("hideLightningFlashes")), Opt::MonochromeLogo => on_off(s.file.bool("darkMojangStudiosBackground")), Opt::HideSplashTexts => on_off(s.file.bool("hideSplashTexts")), + Opt::HideMatchedNames | Opt::OnlySecureChat | Opt::SaveChatDrafts => { + on_off(s.file.bool(self.file_key().unwrap())) + } Opt::NarratorHotkey => on_off(s.file.bool("narratorHotkey")), Opt::RotateWithMinecarts => on_off(s.file.bool("rotateWithMinecart")), Opt::HighContrastBlockOutlines => on_off(s.file.bool("highContrastBlockOutline")), @@ -640,10 +565,12 @@ impl Opt { self.file_key().unwrap(), crate::options_file::V::Double(f64::from(v).powi(2)), ), - Opt::DamageTilt | Opt::PanoramaSpeed => s.file.set( - self.file_key().unwrap(), - crate::options_file::V::Double(f64::from(v)), - ), + Opt::DamageTilt | Opt::PanoramaSpeed | Opt::GlintSpeed | Opt::GlintStrength => { + s.file.set( + self.file_key().unwrap(), + crate::options_file::V::Double(f64::from(v)), + ) + } Opt::Fov => s.fov = step(30.0, 110.0), Opt::RenderDistance => s.render_distance = step(2.0, 64.0) as i32, Opt::SimulationDistance => s.simulation_distance = step(5.0, 32.0) as i32, @@ -722,7 +649,12 @@ impl Opt { value + 1 }; } - Opt::TextBackground | Opt::HideLightningFlashes | Opt::HideSplashTexts => { + Opt::TextBackground + | Opt::HideLightningFlashes + | Opt::HideSplashTexts + | Opt::HideMatchedNames + | Opt::OnlySecureChat + | Opt::SaveChatDrafts => { let key = self.file_key().unwrap(); s.file .set(key, crate::options_file::V::Bool(!s.file.bool(key))); @@ -1521,7 +1453,10 @@ impl OptionsUi { Opt::ChatHeightFocused, Opt::ChatHeightUnfocused, Opt::AutoSuggestions, + Opt::HideMatchedNames, Opt::ReducedDebugInfo, + Opt::OnlySecureChat, + Opt::SaveChatDrafts, ]), Page::Accessibility => { let mut rows = vec![Row::Buttons( diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 1e012fd90..28952ba2c 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -4,9 +4,9 @@ //! and an overlay resource root that layers the enabled packs over the //! vanilla resources (later packs win), so every loader sees one tree. mod cache; -pub mod pattern; use crate::text::Style; use crate::{text::Text, zip::Zip}; +pub use horizon_client_core::pattern; use pattern::Pattern; use std::{ collections::{BTreeMap, BTreeSet}, diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 5efc83621..a9bed143a 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -546,6 +546,17 @@ fn next_double_between(random: &mut impl RandomSource, min: f64, max: f64) -> f6 pub fn on_block_faces( random: &mut impl RandomSource, pos: [i32; 3], + emit: impl FnMut([f64; 3], [f64; 3]), +) { + on_block_faces_between(random, pos, 3, 5, emit); +} +/// `ParticleUtils.spawnParticlesOnBlockFaces` with `UniformInt.of(min, max)` +/// particles per face (3009 sniffer egg cracks use 3 to 6). +pub fn on_block_faces_between( + random: &mut impl RandomSource, + pos: [i32; 3], + min: i32, + max: i32, mut emit: impl FnMut([f64; 3], [f64; 3]), ) { const FACES: [[i32; 3]; 6] = [ @@ -557,7 +568,7 @@ pub fn on_block_faces( [1, 0, 0], ]; for face in FACES { - let count = random.next_int_bound(5 - 3 + 1).unwrap_or(0) + 3; + let count = random.next_int_bound(max - min + 1).unwrap_or(0) + min; for _ in 0..count { // getRandomSpeedRanges, then spawnParticleOnFace with step factor 0.55. let speed: [f64; 3] = std::array::from_fn(|_| next_double_between(random, -0.5, 0.5)); @@ -577,15 +588,17 @@ pub fn on_block_faces( } } /// `ParticleUtils.spawnParticlesAlongAxis(axis, level, pos, 0.125, particle, -/// UniformInt.of(10, 19))` (level event 3002 on a lightning rod): sparks along -/// the rod, moving along it. `axis` is 0, 1, 2 for X, Y, Z. +/// UniformInt.of(min, max))` (`count` is the range; level event 3002 on a +/// lightning rod uses 10 to 19): sparks along the rod, moving along it. +/// `axis` is 0, 1, 2 for X, Y, Z. pub fn along_axis( random: &mut impl RandomSource, axis: usize, pos: [i32; 3], + (min, max): (i32, i32), mut emit: impl FnMut([f64; 3], [f64; 3]), ) { - let count = random.next_int_bound(19 - 10 + 1).unwrap_or(0) + 10; + let count = random.next_int_bound(max - min + 1).unwrap_or(0) + min; for _ in 0..count { let p: [f64; 3] = std::array::from_fn(|i| { f64::from(pos[i]) @@ -983,6 +996,8 @@ pub struct ParticleEngine { emitters: Vec<(ParticleOptions, [f64; 3], f64, f64, u32)>, /// Camera position for the 32-block spawn limiter. pub camera: [f64; 3], + /// The Particles option (`ParticleStatus`): 0 all, 1 decreased, 2 minimal. + pub particle_level: u8, /// FireworkParticles.Starter instances. starters: Vec, /// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch). @@ -1013,6 +1028,7 @@ impl ParticleEngine { emitters: Vec::new(), starters: Vec::new(), camera: [0.0; 3], + particle_level: 0, sounds: Vec::new(), made: Default::default(), item_sprites: HashMap::new(), @@ -1123,30 +1139,48 @@ impl ParticleEngine { &mut self.level_random } /// `ClientLevel.addParticle`: dropped beyond 32 blocks of the camera unless - /// the type overrides the limiter. + /// the type overrides the limiter, and thinned by the Particles option. pub fn add(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { + self.add_with(options, p, v, false, false); + } + /// `ClientLevel.addParticle(particle, overrideLimiter, alwaysShow, ...)` + /// (`doAddParticle`). `always_show` is `addAlwaysVisibleParticle`'s flag. + pub fn add_with( + &mut self, + options: &ParticleOptions, + p: [f64; 3], + v: [f64; 3], + override_limiter: bool, + always_show: bool, + ) { let c = self.camera; let d2 = (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2); if let Some(requested) = &mut self.requested { requested.push((options.clone(), p, v)); return; } - if !options.ty.override_limiter() && d2 > 1024.0 { - return; + let minimal = self.calculate_particle_level(always_show) == 2; + if override_limiter || options.ty.override_limiter() || (d2 <= 1024.0 && !minimal) { + self.create(options, p, v); } - self.create(options, p, v); + } + /// `ClientLevel.calculateParticleLevel`: minimal still shows one in ten + /// always-visible particles as decreased, and decreased drops a third. + fn calculate_particle_level(&mut self, always_show: bool) -> u8 { + let mut level = self.particle_level.min(2); + if always_show && level == 2 && self.level_random.next_int_bound(10).unwrap_or(0) == 0 { + level = 1; + } + if level == 1 && self.level_random.next_int_bound(3).unwrap_or(0) == 0 { + level = 2; + } + level } /// `LevelEventHandler.singleBlockTeleportationParticles` towards /// `BlockUtil.unpackDifferenceInPosition(from, data, radius)`: the dragon /// egg's event 2015 packs offsets within (16, 8, 16), a consumable's /// teleport (2017) within (127, 127, 127). - pub fn block_teleportation( - &mut self, - from: [i32; 3], - data: i32, - radius: [i32; 3], - particle_level: u8, - ) { + pub fn block_teleportation(&mut self, from: [i32; 3], data: i32, radius: [i32; 3]) { let to = [ from[0].wrapping_add(((data >> 16) & 255) - radius[0]), from[1].wrapping_add(((data >> 8) & 255) - radius[1]), @@ -1164,6 +1198,35 @@ impl ParticleEngine { to[1] + t * (from[1] - to[1]) + r.next_double() - 0.5, to[2] + t * (from[2] - to[2]) + (r.next_double() - 0.5) + 0.5, ]; + self.add(&options, position, velocity); + } + } + /// `LevelEventHandler.levelEvent` 2018: an enderman's portal trail from + /// where it was (`from`) to where it went, which `data` packs within + /// (127, 127, 127). 128 portal particles along the way, spread about the + /// width and height of an enderman. + pub fn enderman_teleportation(&mut self, from: [i32; 3], data: i32, particle_level: u8) { + // EntityTypes.ENDERMAN's dimensions. + const WIDTH: f64 = 0.6_f32 as f64; + const HEIGHT: f64 = 2.9_f32 as f64; + let to = [ + from[0].wrapping_add(((data >> 16) & 255) - 127), + from[1].wrapping_add(((data >> 8) & 255) - 127), + from[2].wrapping_add((data & 255) - 127), + ] + .map(f64::from); + let from = from.map(f64::from); + let options = ParticleOptions::simple(ParticleType::Portal); + for _ in 0..128 { + let r = &mut self.level_random; + let t = r.next_double(); + let velocity = std::array::from_fn(|_| f64::from((r.next_float() - 0.5) * 0.2)); + // Mth.lerp(t, to, from). + let position = [ + to[0] + t * (from[0] - to[0]) + (r.next_double() - 0.5) * WIDTH * 2.0, + to[1] + t * (from[1] - to[1]) + r.next_double() * HEIGHT, + to[2] + t * (from[2] - to[2]) + (r.next_double() - 0.5) * WIDTH * 2.0, + ]; // The option roll shares the level random and precedes the distance check. let limited = match particle_level { 1 => r.next_int_bound(3).unwrap_or(0) == 0, @@ -1214,6 +1277,10 @@ impl ParticleEngine { block_count: usize, is_air: &dyn Fn([i32; 3]) -> bool, ) { + // ClientExplosionTracker.tick: only the All option throws the debris. + if self.particle_level != 0 { + return; + } for _ in 0..block_count.min(512) { let r = &mut self.random; let d = Vec3::new( @@ -3754,6 +3821,8 @@ impl ParticleEngine { }, color, light, + + glint_uv: [0.0, 0.0], }); } } @@ -3778,7 +3847,7 @@ mod tests { let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new()); engine.seed_randoms(0, 0, 0); // Destination offset (-15, 7, 15); the unused top byte is ignored. - engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16], 0); + engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16]); assert_eq!(engine.pending.len(), 128); assert!(engine.pending.iter().all(|p| p.ty == ParticleType::Portal)); let first = &engine.pending[0]; @@ -3805,7 +3874,7 @@ mod tests { // TeleportRandomlyConsumeEffect: BlockUtil.clampedPackDifferenceInPosition // of the move (-7, -3, 9) with radii 127, from (4, 12, -5) to (-3, 9, 4). let data = (-7 + 127) << 16 | (-3 + 127) << 8 | (9 + 127); - engine.block_teleportation([4, 12, -5], data, [127, 127, 127], 0); + engine.block_teleportation([4, 12, -5], data, [127, 127, 127]); assert_eq!(engine.pending.len(), 128); for p in &engine.pending { let [x, y, z] = p.position; @@ -3831,7 +3900,8 @@ mod tests { if distant { engine.camera = [1000.0; 3]; } - engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16], option); + engine.particle_level = option; + engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16]); assert_eq!(engine.pending.len(), if distant { 0 } else { count }); assert_eq!(engine.level_random.state(), state); } diff --git a/crates/horizon-client/src/poi_sections.rs b/crates/horizon-client/src/poi_sections.rs index 79ff0441d..a806706a1 100644 --- a/crates/horizon-client/src/poi_sections.rs +++ b/crates/horizon-client/src/poi_sections.rs @@ -79,6 +79,15 @@ impl PoiSections { } } +/// The POI types villagers use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Poi { + /// A job site, by profession index. + Job(u8), + Home, + Meeting, +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index aae9b296b..b3e9938c9 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -109,6 +109,9 @@ pub struct Projectile { pub arrow: Option>, /// `AbstractHurtingProjectile.accelerationPower`. pub acceleration: f64, + /// `Entity.needsSync`: a server tells its clients about the change this + /// tick instead of at the next update interval. + pub needs_sync: bool, } /// What a projectile struck this tick. #[derive(Clone, Copy, Debug, PartialEq)] @@ -173,6 +176,7 @@ impl Projectile { left_owner: false, bonus: Default::default(), acceleration: 0.1, + needs_sync: false, arrow: kind_is_arrow.then(|| { // Entity.random: seeded unpredictably, the position stands in. Box::new(crate::arrows::ArrowState::new( diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index b6f4c1322..885d10771 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -339,59 +339,7 @@ impl SaveTables { } } -/// A container's loot table and what Horizon rolled from it. Vanilla keeps -/// `LootTable` and `LootTableSeed` until the container is first opened; -/// Horizon rolls when it generates or loads the chunk, and saves the table -/// again while the container still holds exactly the rolled items. -#[derive(Clone, Debug, PartialEq)] -pub struct RolledLoot { - pub pos: (i32, i32, i32), - pub table: String, - /// The saved `LootTableSeed`, written back unless 0 (trySaveLootTable). - pub seed: Option, - /// The rolled `Items`. - pub items: Tag, -} -impl RolledLoot { - /// Puts the loot table back in place of `Items` while they are still the - /// roll; false once the container holds anything else. - pub fn restore(&self, map: &mut Compound) -> bool { - if map.get(&"Items".into()) != Some(&self.items) { - return false; - } - map.remove(&"Items".into()); - map.insert("LootTable".into(), string(&self.table)); - if let Some(seed) = self.seed.filter(|s| *s != 0) { - map.insert("LootTableSeed".into(), Tag::Long(seed)); - } - true - } -} - -/// Save data loaded with a chunk that Horizon keeps but does not simulate. -#[derive(Clone, Debug, Default)] -pub struct ChunkExtras { - /// Chunk root keys written back as loaded (structures, PostProcessing, - /// InhabitedTime, blending data, ...). - pub root: Compound, - /// Block entities Horizon does not model. - pub block_entities: Vec, - /// The NBT of the modelled block entities as loaded, to restore the fields and - /// detail Horizon does not model when it saves them (`block_entity_nbt::overlay`). - pub block_entity_sources: Vec<((i32, i32, i32), Tag)>, - /// Every saved block entity's position in the order of the save's list, - /// the order `SerializableChunkData` puts them in the chunk's maps. - pub block_entity_order: Vec<(i32, i32, i32)>, - /// Scheduled ticks (`block_ticks`/`fluid_ticks`): delays relative to the - /// save time. Registered with the level's tick scheduler on arrival and - /// replaced with the scheduler's pending ticks when saving. - pub block_ticks: Vec, - pub fluid_ticks: Vec, - /// Game time written as `LastUpdate`. - pub last_update: i64, - /// Containers still holding their loot table's roll. - pub rolled_loot: Vec, -} +pub use crate::chunk::{ChunkExtras, RolledLoot, SavedProto}; fn tick_list(ticks: &[SavedTick], name: impl Fn(u32) -> Option) -> Tag { Tag::List( @@ -599,6 +547,11 @@ pub fn encode_block_entity( } } BlockEntity::Sculk(s) => entries.extend(s.to_nbt()), + // ChiseledBookShelfBlockEntity.saveAdditional. + BlockEntity::ChiseledBookshelf(b) => { + entries.push(("Items", encode_items(&b.items))); + entries.push(("last_interacted_slot", Tag::Int(b.last_slot))); + } // CampfireBlockEntity.saveAdditional. BlockEntity::Campfire(c) => { entries.push(("Items", encode_items(&c.items))); @@ -643,6 +596,16 @@ pub fn encode_block_entity( entries.push(("custom_name", name.clone())); } } + // TheEndGatewayBlockEntity.saveAdditional. + BlockEntity::EndGateway(g) => { + entries.push(("Age", Tag::Long(g.age))); + if let Some(exit) = g.exit_portal { + entries.push(("exit_portal", Tag::IntArray(exit.to_vec()))); + } + if g.exact_teleport { + entries.push(("ExactTeleport", Tag::Byte(1))); + } + } BlockEntity::Spawner(s) => entries.extend(s.save()), BlockEntity::TrialSpawner(s) => entries.extend(s.save()), BlockEntity::Vault(v) => entries.extend(v.save()), @@ -702,11 +665,24 @@ fn roll_loaded_loot( biome, )) } +/// `TheEndGatewayBlockEntity.loadAdditional`. +pub fn decode_end_gateway(tag: &Tag) -> crate::containers::EndGateway { + crate::containers::EndGateway { + age: number(tag.get("Age")).unwrap_or(0), + exit_portal: tag + .get("exit_portal") + .and_then(crate::block_entity_nbt::gateway_exit), + exact_teleport: number(tag.get("ExactTeleport")).unwrap_or(0) != 0, + } +} pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> { use crate::containers::BlockEntity; let int = |k: &str| number(tag.get(k)).map(|v| v as i32); let id = text(tag.get("id"))?; let pos = (int("x")?, int("y")?, int("z")?); + if id == "minecraft:end_gateway" { + return Some((pos, BlockEntity::EndGateway(decode_end_gateway(tag)))); + } if id == "minecraft:jukebox" { let record = tag.get("RecordItem").and_then(item_from_nbt); let ticks = number(tag.get("ticks_since_song_started")).unwrap_or(0); @@ -814,6 +790,13 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain } BlockEntity::Sign(sign) => sign.decode(tag), BlockEntity::Sculk(s) => s.load(tag), + // ChiseledBookShelfBlockEntity.loadAdditional. + BlockEntity::ChiseledBookshelf(b) => { + for (slot, item) in decode_items(tag.get("Items"), 6).into_iter().enumerate() { + b.items[slot] = item; + } + b.last_slot = int("last_interacted_slot").unwrap_or(-1); + } // CampfireBlockEntity.loadAdditional: missing time arrays stay zeros. BlockEntity::Campfire(c) => { for (slot, item) in decode_items(tag.get("Items"), 4).into_iter().enumerate() { @@ -846,6 +829,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Lectern(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector => {} BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), @@ -1528,21 +1512,6 @@ fn decode_column( Some(chunk) } -/// A proto chunk saved before it became final. Decoration writes into a -/// chunk's neighbours, and decorated chunks wait for theirs, so the chunks -/// past the finished ones hold writes that generating them again would lose -/// (whole structure pieces, trees, ores). Vanilla saves its proto chunks too. -pub struct SavedProto { - /// Blocks, scheduled ticks (in `saved`) and post-processing marks. - pub column: Chunk, - /// Decorated itself (`features`), not only written to by its neighbours - /// (`terrain`). - pub decorated: bool, - /// Block entity data in placement order, with `x`, `y` and `z`. - pub block_entities: Vec, - /// Entities placed by structures, with absolute `Pos`. - pub entities: Vec, -} pub fn encode_proto( proto: &SavedProto, registry: &BlockRegistry, @@ -4642,6 +4611,79 @@ mod tests { } use super::*; + #[test] + fn end_gateway_block_entity_round_trips() { + use crate::containers::{BlockEntity, EndGateway}; + let plain = BlockEntity::for_block("minecraft:end_gateway").expect("gateway"); + assert!(matches!(&plain, BlockEntity::EndGateway(g) if *g == EndGateway::default())); + for exit in [None, Some([8, 100, 0])] { + for exact in [false, true] { + let gateway = EndGateway { + age: 201, + exit_portal: exit, + exact_teleport: exact, + }; + let tag = encode_block_entity( + (702, 100, 0), + &BlockEntity::EndGateway(gateway.clone()), + "minecraft:end_gateway", + ); + assert_eq!( + text(tag.get("id")).as_deref(), + Some("minecraft:end_gateway") + ); + assert_eq!(tag.get("Age"), Some(&Tag::Long(201))); + assert_eq!( + tag.get("exit_portal"), + exit.map(|p| Tag::IntArray(p.to_vec())).as_ref() + ); + assert_eq!( + tag.get("ExactTeleport"), + exact.then_some(Tag::Byte(1)).as_ref() + ); + let (pos, back) = decode_block_entity(&tag).expect("gateway"); + assert_eq!(pos, (702, 100, 0)); + assert!(matches!(back, BlockEntity::EndGateway(g) if g == gateway)); + } + } + } + + #[test] + fn end_gateway_exit_requires_spawnable_bounds() { + for (exit, valid) in [ + (vec![-30_000_000, -20_000_000, -30_000_000], true), + (vec![29_999_999, 19_999_999, 29_999_999], true), + (vec![30_000_000, 0, 0], false), + (vec![0, 0, 30_000_000], false), + (vec![-30_000_001, 0, 0], false), + (vec![0, 0, -30_000_001], false), + (vec![0, 20_000_000, 0], false), + (vec![0, -20_000_001, 0], false), + (vec![i32::MIN, 0, 0], false), + (vec![0, 100], false), + ] { + let tag = Tag::compound([ + ("id", string("minecraft:end_gateway")), + ("x", Tag::Int(702)), + ("y", Tag::Int(100)), + ("z", Tag::Int(0)), + ("exit_portal", Tag::IntArray(exit)), + ]); + let (_, crate::containers::BlockEntity::EndGateway(g)) = + decode_block_entity(&tag).unwrap() + else { + panic!("gateway"); + }; + assert_eq!(g.exit_portal.is_some(), valid); + let canonical = crate::block_entity_nbt::canonical(&tag).expect("gateway NBT"); + assert_eq!(canonical.get("exit_portal").is_some(), valid); + } + assert_eq!( + decode_end_gateway(&Tag::Compound(Compound::new())), + crate::containers::EndGateway::default() + ); + } + #[test] fn skull_block_entity_keeps_its_profile() { // A placed `player_head` as vanilla saves it: the owning player's diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 09d7ae3ff..aeb366947 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -608,6 +608,99 @@ impl Settings { } } +/// One option instance. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Opt { + Fov, + RenderDistance, + SimulationDistance, + Sensitivity, + WheelSensitivity, + InvertY, + DiscreteScroll, + Volume(usize), + GuiScale, + ViewBobbing, + Gamma, + MaxFps, + Vsync, + Fullscreen, + SmoothLighting, + Clouds, + CloudRange, + Particles, + EntityDistance, + EntityShadows, + BiomeBlend, + Preset, + Mipmaps, + WeatherRadius, + ChunkFade, + Vignette, + Autosave, + CutoutLeaves, + ImprovedTransparency, + AttackIndicator, + InactivityFps, + ChunkBuilder, + MenuBlur, + ToggleCrouch, + ToggleSprint, + AutoJump, + ChatVisibility, + ChatColors, + ChatLinks, + ChatLinksPrompt, + ChatOpacity, + TextBackgroundOpacity, + ChatScale, + ChatWidth, + ChatHeightFocused, + ChatHeightUnfocused, + ChatLineSpacing, + AutoSuggestions, + HideMatchedNames, + ReducedDebugInfo, + OnlySecureChat, + SaveChatDrafts, + HighContrast, + ShowSubtitles, + MusicFrequency, + NotificationDisplayTime, + Narrator, + TextBackground, + ChatDelay, + DistortionEffects, + FovEffects, + DarknessPulsing, + DamageTilt, + GlintSpeed, + GlintStrength, + HideLightningFlashes, + MonochromeLogo, + PanoramaSpeed, + HideSplashTexts, + NarratorHotkey, + RotateWithMinecarts, + HighContrastBlockOutlines, + ForceUnicode, + JapaneseGlyphs, + /// Horizon's controller settings (`horizon-controller.txt`). + PadEnabled, + PadVibration, + PadAdaptiveTriggers, + PadLightbar, + PadLookSensitivity, + PadInvertX, + PadInvertY, + PadToggleSneak, + PadMoveDeadzone, + PadLookDeadzone, + PadGlyphs, + PadMenuNav, + PadKeyboard, +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/shadows.rs b/crates/horizon-client/src/shadows.rs index dece7f726..613eb0bb1 100644 --- a/crates/horizon-client/src/shadows.rs +++ b/crates/horizon-client/src/shadows.rs @@ -119,6 +119,8 @@ pub fn shadow( layer: crate::gfx::SHADOW_OVERLAY, color, light: 240 | 240 << 8, + + glint_uv: [0.0, 0.0], }); } } diff --git a/crates/horizon-client/src/signs.rs b/crates/horizon-client/src/signs.rs index 07217ed79..799210797 100644 --- a/crates/horizon-client/src/signs.rs +++ b/crates/horizon-client/src/signs.rs @@ -147,10 +147,10 @@ fn component_text(tag: &Tag) -> String { _ => s, } } - Tag::Compound(_) => match tag.get("text") { - Some(Tag::String(t)) => t.to_string_lossy(), - _ => String::new(), - }, + // Component.getString: translations and key binds resolved. + Tag::Compound(_) => { + crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(tag)).plain() + } _ => String::new(), } } diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index ee6851e00..740208973 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -116,20 +116,9 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture /// heads and mannequins read their profile this way, and `SkinManager` lets /// those textures be unsigned (`getInsecureSkinInformation`). pub fn profile_skin_url(profile: &serde_json::Value) -> Option { - let value = profile - .get("properties")? - .as_array()? - .iter() - .find_map(|p| { - if p.get("name")?.as_str()? == "textures" { - p.get("value")?.as_str() - } else { - None - } - })?; - unpack(value, Signature::Unsigned, &TEXTURE_URIS).skin + let (value, signature) = parse_profile(profile).textures?; + unpack(&value, signature, &TEXTURE_URIS).skin } - /// `profile_skin_url` on a block entity's `profile` NBT (`SkullBlockEntity`): /// the same `properties` list, held as a compound. A name-only profile (a /// string tag) has no properties and no skin URL. @@ -164,13 +153,329 @@ pub fn profile_uuid_nbt(profile: &horizon_world::nbt::Tag) -> Option { } } -fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option { +pub(crate) fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option { match tag { Some(horizon_world::nbt::Tag::String(s)) => Some(s.to_string_lossy()), _ => None, } } +/// `Either`: the key a `Dynamic` `ResolvableProfile` resolves +/// by (`ResolvableProfile.nameOrId`). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum NameOrId { + Name(String), + Id(u128), +} + +/// `GameProfile` as `fetchProfile` returns it: the account's id, name and +/// property map (its `textures` property is the skin). +#[derive(Clone, Debug)] +pub struct ResolvedProfile { + pub id: u128, + pub name: String, + /// `(name, value, signature)` properties. + pub properties: Vec<(String, String, Option)>, +} +impl ResolvedProfile { + /// `SessionService.getPackedTextures`: the `textures` property. + pub fn textures(&self) -> Option<(String, Signature)> { + self.properties + .iter() + .find(|(n, _, _)| n == "textures") + .map(|(_, v, s)| { + ( + v.clone(), + if s.is_some() { + Signature::Signed + } else { + Signature::Unsigned + }, + ) + }) + } +} + +/// Where a `Dynamic` profile's resolution stands (`resolveProfile`'s future). +#[derive(Clone, Debug)] +pub enum Resolve { + Pending, + /// The services' answer: `None` for no profile or no answer, which the + /// cache holds like any result (`Optional.empty`). + Done(Option), +} + +/// `ProfileResolver.Cached`: resolves a `Dynamic` profile through the +/// services — `profileCacheByName` asks `profiles`/`getByName` for the id, +/// `profileCacheById` asks `session`/`getProfileById` for the profile — +/// at most 256 entries kept 10 minutes after their last use, fetched on +/// background threads. +pub struct Resolver { + entries: std::collections::HashMap, + done: std::sync::mpsc::Receiver<(NameOrId, Option)>, + send: std::sync::mpsc::Sender<(NameOrId, Option)>, + last_sweep: std::time::Instant, +} +struct Entry { + touched: std::time::Instant, + /// `None` while the fetch is in flight. + resolved: Option>, +} +/// `ProfileResolver.Cached`'s cache bounds. +const MAX_PROFILES: usize = 256; +const PROFILE_TTL: std::time::Duration = std::time::Duration::from_secs(10 * 60); + +/// `StringUtil.isValidPlayerName` (the check `fetchByName` makes first). +fn valid_player_name(name: &str) -> bool { + name.encode_utf16().count() <= 16 && name.encode_utf16().all(|c| c > 32 && c < 127) +} + +/// `fetchByNameOrId`: `getByName` answers `{id, name}`; `getProfileById` +/// (`fetchProfile(id, requireSecure)`) answers `{id, name, properties}` — +/// asked `unsigned=false` so the `textures` property is signed. +fn resolve_profile(key: &NameOrId, doc: &serde_json::Value) -> Option { + let id = match key { + NameOrId::Id(id) => *id, + NameOrId::Name(name) => { + let url = crate::auth::endpoint(doc, "profiles", "getByName")? + .replace("{name}", &name.to_lowercase()); + let body = http_get(&url)?; + let v: serde_json::Value = serde_json::from_slice(&body).ok()?; + crate::auth::parse_uuid(v.get("id")?.as_str()?)? + } + }; + let url = crate::auth::endpoint(doc, "session", "getProfileById")? + .replace("{profileId}", &format!("{id:032x}")); + let separator = if url.contains('?') { '&' } else { '?' }; + let body = http_get(&format!("{url}{separator}unsigned=false"))?; + let v: serde_json::Value = serde_json::from_slice(&body).ok()?; + Some(ResolvedProfile { + id: crate::auth::parse_uuid(v.get("id")?.as_str()?)?, + name: v.get("name")?.as_str()?.to_owned(), + properties: v + .get("properties")? + .as_array()? + .iter() + .map(|p| { + Some(( + p.get("name")?.as_str()?.to_owned(), + p.get("value")?.as_str()?.to_owned(), + p.get("signature") + .and_then(|s| s.as_str()) + .map(str::to_owned), + )) + }) + .collect::>>()?, + }) +} + +impl Default for Resolver { + fn default() -> Self { + Self::new() + } +} +impl Resolver { + pub fn new() -> Self { + let (send, done) = std::sync::mpsc::channel(); + Self { + entries: Default::default(), + done, + send, + last_sweep: std::time::Instant::now(), + } + } + /// `CacheBuilder.expireAfterAccess` with `maximumSize`. + fn sweep(&mut self) { + if self.last_sweep.elapsed() < std::time::Duration::from_secs(30) { + return; + } + self.last_sweep = std::time::Instant::now(); + self.entries + .retain(|_, e| e.touched.elapsed() < PROFILE_TTL); + while self.entries.len() > MAX_PROFILES + && let Some(oldest) = self + .entries + .iter() + .min_by_key(|(_, e)| e.touched) + .map(|(k, _)| k.clone()) + { + self.entries.remove(&oldest); + } + } + /// How the resolution of `key` stands, starting it the first time. + pub fn state(&mut self, key: &NameOrId) -> Resolve { + while let Ok((key, resolved)) = self.done.try_recv() { + self.entries.insert( + key, + Entry { + touched: std::time::Instant::now(), + resolved: Some(resolved), + }, + ); + } + self.sweep(); + if let Some(entry) = self.entries.get_mut(key) { + entry.touched = std::time::Instant::now(); + return match &entry.resolved { + Some(resolved) => Resolve::Done(resolved.clone()), + None => Resolve::Pending, + }; + } + // `fetchByName` refuses an invalid name without a fetch; like every + // other empty answer that is the cached result. + let resolved = matches!(key, NameOrId::Name(name) if !valid_player_name(name)); + self.entries.insert( + key.clone(), + Entry { + touched: std::time::Instant::now(), + resolved: resolved.then_some(None), + }, + ); + if resolved { + return Resolve::Done(None); + } + let (key, send) = (key.clone(), self.send.clone()); + std::thread::spawn(move || { + let resolved = crate::auth::discovery() + .ok() + .and_then(|doc| resolve_profile(&key, &doc)); + let _ = send.send((key, resolved)); + }); + Resolve::Pending + } +} + +/// `ResolvableProfile` (an item's `minecraft:profile` component, a skull's +/// `profile` tag): the `textures` property it carries, the key a `Dynamic` +/// profile resolves by, and `partialProfile.id` — the fallback skin's key. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ProfileInfo { + /// `GameProfile.id` (`DefaultPlayerSkin.get`). + pub id: u128, + /// The `textures` property's value and signature state, when present. + pub textures: Option<(String, Signature)>, + /// `Dynamic` profiles resolve by name or id. + pub dynamic: Option, +} + +/// A profile's `id`: `UUIDUtil.CODEC` (an int array of four, or a UUID +/// string). +fn profile_id(v: &serde_json::Value) -> Option { + match v { + serde_json::Value::Array(a) => { + let ints: Option> = a.iter().map(|x| x.as_i64()).collect(); + let i = ints?; + (i.len() == 4).then(|| { + ((i[0] as u32 as u128) << 96) + | ((i[1] as u32 as u128) << 64) + | ((i[2] as u32 as u128) << 32) + | i[3] as u32 as u128 + }) + } + serde_json::Value::String(s) => crate::auth::parse_uuid(s), + _ => None, + } +} + +/// `ResolvableProfile`'s read of a `profile` value: a bare name is +/// `createUnresolved` (the `PLAYER_NAME` codec's alternative), a compound +/// `name` + `id` + `properties` (`Partial.MAP_CODEC` or a `GameProfile`). +pub fn parse_profile(v: &serde_json::Value) -> ProfileInfo { + if let serde_json::Value::String(name) = v { + return ProfileInfo { + id: horizon_protocol::crypto::offline_uuid(name), + textures: None, + dynamic: valid_player_name(name).then(|| NameOrId::Name(name.clone())), + }; + } + let name = v.get("name").and_then(|n| n.as_str()).map(str::to_owned); + let id = v.get("id").and_then(profile_id); + let properties = v.get("properties").and_then(|p| p.as_array()); + let textures = properties + .into_iter() + .flatten() + .find(|p| p.get("name").and_then(|n| n.as_str()) == Some("textures")) + .and_then(|p| { + Some(( + p.get("value")?.as_str()?.to_owned(), + if p.get("signature").is_some() { + Signature::Signed + } else { + Signature::Unsigned + }, + )) + }); + // `ResolvableProfile.create`: a Partial is Dynamic with no properties + // and exactly one of a name or an id. + let dynamic = + (properties.is_none_or(|p| p.is_empty()) && name.is_some() != id.is_some()).then(|| { + name.as_deref().map_or_else( + || NameOrId::Id(id.unwrap()), + |n| NameOrId::Name(n.to_owned()), + ) + }); + ProfileInfo { + // `createPartialProfile`: the id, else the name's offline UUID, else nil. + id: id + .or_else(|| name.as_deref().map(horizon_protocol::crypto::offline_uuid)) + .unwrap_or(0), + textures, + dynamic, + } +} + +/// `ResolvableProfile.create`'s `Dynamic` key from a skull's `profile` tag: +/// a bare name string is `createUnresolved`, and a compound without +/// properties and with exactly one of a name or an id is `Dynamic`. +pub fn dynamic_nbt(profile: &horizon_world::nbt::Tag) -> Option { + if let horizon_world::nbt::Tag::String(s) = profile { + let name = s.to_string_lossy(); + return valid_player_name(&name).then_some(NameOrId::Name(name)); + } + if matches!(profile.get("properties"), Some(horizon_world::nbt::Tag::List(l)) if !l.is_empty()) + { + return None; + } + match (nbt_text(profile.get("name")), profile_uuid_nbt(profile)) { + (Some(name), None) => Some(NameOrId::Name(name)), + (None, Some(id)) => Some(NameOrId::Id(id)), + _ => None, + } +} + +/// `PlayerSkinRenderCache.getOrDefault` for a head: the resolved skin once +/// its texture is in the atlas (`atlas`), else `partialProfile`'s default. +pub fn head_skin( + profile: &serde_json::Value, + resolver: &mut Resolver, + downloads: &mut Downloader, + atlas: impl Fn(&str) -> bool, +) -> String { + let p = parse_profile(profile); + let property = p.textures.or_else(|| { + let key = p.dynamic.as_ref()?; + match resolver.state(key) { + Resolve::Done(Some(profile)) => profile.textures(), + _ => None, + } + }); + if let Some((value, signature)) = property + && let Some(url) = unpack(&value, signature, &TEXTURE_URIS).skin + && let Some(hash) = texture_hash(&url) + { + let location = skin_location(&hash); + match downloads.state(Kind::Skin, &url) { + Download::Ready if atlas(&location) => return location, + // Its slot was evicted: offer the image again. + Download::Ready => { + downloads.again(&location); + } + _ => {} + } + } + crate::tab_list::default_skin(p.id).to_owned() +} + /// `MinecraftProfileTexture.getHash`: the base name of the URL's path. pub fn texture_hash(url: &str) -> Option { let rest = url.split_once("://")?.1; @@ -313,7 +618,16 @@ pub struct Downloader { done: std::sync::mpsc::Receiver<((Kind, String), Option>)>, send: std::sync::mpsc::Sender<((Kind, String), Option>)>, ready: Vec<(String, Vec)>, + /// Locations already in `ready`, so `again` does not double-queue. + queued: std::collections::HashSet, + /// Decoded skin images by location, kept so a skin evicted from the + /// atlas uploads again (`again`); the disk cache backs anything dropped. + images: std::collections::HashMap>, + image_order: std::collections::VecDeque, } +/// `images` is bounded only so a long session on a busy server does not grow +/// without end; the disk cache holds everything it drops. +const MAX_SKIN_IMAGES: usize = 1024; impl Downloader { pub fn new(root: std::path::PathBuf) -> Self { let (send, done) = std::sync::mpsc::channel(); @@ -323,6 +637,9 @@ impl Downloader { done, send, ready: Vec::new(), + queued: Default::default(), + images: Default::default(), + image_order: Default::default(), } } /// How the download of `url` stands, starting it the first time. @@ -331,7 +648,8 @@ impl Downloader { let state = match image { Some(rgba) => { if key.0 == Kind::Skin { - self.ready.push((skin_location(&key.1), rgba)); + let location = skin_location(&key.1); + self.queue(location, rgba); } Download::Ready } @@ -370,8 +688,53 @@ impl Downloader { }); Download::Pending } + /// Keeps a decoded skin for `again`, dropping the oldest past the bound. + fn remember(&mut self, location: String, rgba: Vec) { + if !self.images.contains_key(&location) { + self.image_order.push_back(location.clone()); + while self.image_order.len() > MAX_SKIN_IMAGES + && let Some(old) = self.image_order.pop_front() + { + self.images.remove(&old); + } + } + self.images.insert(location, rgba); + } + /// An image off to the atlas: remembered for `again` and marked queued + /// so nothing uploads the same location twice. + fn queue(&mut self, location: String, rgba: Vec) { + self.remember(location.clone(), rgba.clone()); + self.queued.insert(location.clone()); + self.ready.push((location, rgba)); + } + /// A ready skin whose atlas slot was evicted (`show_skin` answered no): + /// its image for upload again, from memory or the disk cache. + pub fn again(&mut self, location: &str) -> bool { + if self.queued.contains(location) { + return true; + } + let Some(digest) = location.strip_prefix("skins/") else { + return false; + }; + let image = self.images.get(location).cloned().or_else(|| { + let file = self + .root + .join(if digest.len() > 2 { &digest[..2] } else { "xx" }) + .join(digest); + let (w, h, rgba) = crate::hud::decode_bytes(&std::fs::read(&file).ok()?).ok()?; + process_legacy_skin(w, h, &rgba) + }); + let Some(image) = image else { + return false; + }; + self.queue(location.to_owned(), image); + true + } /// Skins that finished since the last call: texture id and 64x64 RGBA. pub fn take_ready(&mut self) -> Vec<(String, Vec)> { + for (location, _) in &self.ready { + self.queued.remove(location); + } std::mem::take(&mut self.ready) } } @@ -452,6 +815,134 @@ pub fn sha1(data: &[u8]) -> [u8; 20] { #[cfg(test)] mod tests { + #[test] + fn profiles_parse_like_resolvable_profiles() { + use super::{NameOrId, Signature, parse_profile}; + // A bare name is `createUnresolved`: dynamic by name, and its partial + // id is the name's offline UUID. + let p = parse_profile(&serde_json::json!("Notch")); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + assert_eq!(p.id, horizon_protocol::crypto::offline_uuid("Notch")); + assert!(p.textures.is_none()); + // A name-only compound resolves the same way. + let p = parse_profile(&serde_json::json!({"name": "Notch"})); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + // An id-only compound resolves by id (int array or UUID string). + let id = 0x0123_4567_89ab_cdef_0123_4567_89ab_cdef_u128; + let ints: Vec = [ + (id >> 96) as i32 as i64, + (id >> 64) as i32 as i64, + (id >> 32) as i32 as i64, + id as i32 as i64, + ] + .into(); + let p = parse_profile(&serde_json::json!({"id": ints})); + assert_eq!(p.dynamic, Some(NameOrId::Id(id))); + let p = parse_profile(&serde_json::json!({"id": "01234567-89ab-cdef-0123-4567abcdef00"})); + assert_eq!( + p.dynamic, + Some(NameOrId::Id(0x0123_4567_89ab_cdef_0123_4567_abcd_ef00)) + ); + // Name and id but no properties is Static: it never resolves, and its + // default skin keys off the id. + let p = parse_profile(&serde_json::json!({"name": "Notch", "id": ints})); + assert!(p.dynamic.is_none()); + assert_eq!(p.id, id); + // A `textures` property makes it Static (unsigned and signed). + let p = parse_profile(&serde_json::json!({ + "properties": [{"name": "textures", "value": "v"}] + })); + assert!(p.dynamic.is_none()); + assert_eq!(p.textures, Some(("v".into(), Signature::Unsigned))); + let p = parse_profile(&serde_json::json!({ + "properties": [{"name": "textures", "value": "v", "signature": "s"}] + })); + assert_eq!(p.textures, Some(("v".into(), Signature::Signed))); + // Empty properties leave it dynamic. + let p = parse_profile(&serde_json::json!({"name": "Notch", "properties": []})); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + } + + /// `getByName` and `getProfileById` answer from the services the + /// discovery document names; a profile resolves through both. + #[test] + fn profiles_resolve_through_the_services() { + use std::io::{BufRead, BufReader, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + let reply = |status: &str, body: &str| { + format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + }; + for stream in listener.incoming().take(3) { + let mut stream = stream.unwrap(); + let mut line = String::new(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + reader.read_line(&mut line).unwrap(); + while reader.read_line(&mut String::new()).unwrap() > 2 {} + let body = if line.contains("/users/profiles/minecraft/") { + r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch"}"# + } else if line.contains("/session/minecraft/profile/") + && line.contains("unsigned=false") + { + r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch","properties":[{"name":"textures","value":"dmFsdWU=","signature":"c2ln"}]}"# + } else { + "{}" + }; + stream.write_all(reply("200 OK", body).as_bytes()).unwrap(); + } + }); + let doc = serde_json::json!({"discovery": { + "profiles": {"endpoints": {"getByName": {"uri": format!("{base}/users/profiles/minecraft/{{name}}")}}}, + "session": {"endpoints": {"getProfileById": {"uri": format!("{base}/session/minecraft/profile/{{profileId}}")}}}, + }}); + let resolved = + super::resolve_profile(&super::NameOrId::Name("Notch".into()), &doc).unwrap(); + assert_eq!(resolved.id, 0x069a_79f4_44e9_4726_a5be_fca9_0e38_aaf5); + assert_eq!(resolved.name, "Notch"); + assert_eq!( + resolved.properties, + vec![( + "textures".to_owned(), + "dmFsdWU=".to_owned(), + Some("c2ln".to_owned()) + )] + ); + let by_id = super::resolve_profile(&super::NameOrId::Id(resolved.id), &doc).unwrap(); + assert_eq!(by_id.name, "Notch"); + // A discovery without `profiles`/`getByName` resolves no name. + let doc = serde_json::json!({"discovery": { + "session": {"endpoints": {"getProfileById": {"uri": format!("{base}/session/minecraft/profile/{{profileId}}")}}}, + }}); + assert!(super::resolve_profile(&super::NameOrId::Name("Notch".into()), &doc).is_none()); + } + + /// A skin evicted from the atlas re-uploads (`again`), once per ask. + #[test] + fn evicted_skins_upload_again() { + let mut d = super::Downloader::new(std::env::temp_dir().join("horizon-test-skins")); + d.remember("skins/abc".into(), vec![1, 2, 3]); + assert!(d.again("skins/abc")); + assert!(!d.again("skins/missing")); + // Once queued, more asks do not pile up uploads. + assert!(d.again("skins/abc")); + assert_eq!( + d.take_ready(), + vec![("skins/abc".to_owned(), vec![1, 2, 3])] + ); + assert!(d.take_ready().is_empty()); + assert!(d.again("skins/abc")); + assert_eq!(d.take_ready().len(), 1); + // The first upload marks the location queued too: an `again` before + // `take_ready` does not put the same skin in the atlas twice. + d.queue("skins/def".into(), vec![4]); + assert!(d.again("skins/def")); + assert_eq!(d.take_ready(), vec![("skins/def".to_owned(), vec![4])]); + } + #[test] fn profile_components_supply_unsigned_head_skins() { let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0="; diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index c5ed5d881..14dfedb49 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -151,8 +151,12 @@ pub struct AnvilResult { pub repair_item_count_cost: u32, pub only_renaming: bool, } +/// `ItemStack.isDamageableItem`: durability, and not `minecraft:unbreakable`. pub fn is_damageable(items: &Items, stack: &ItemStack) -> bool { items.get(&stack.item).is_some_and(|i| i.max_damage > 0) + && stack + .data() + .is_none_or(|d| d.other("minecraft:unbreakable").is_none()) } fn max_damage(items: &Items, stack: &ItemStack) -> i32 { items.get(&stack.item).map_or(0, |i| i.max_damage as i32) diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 619a0202c..6588ac32d 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -75,11 +75,11 @@ pub trait ChunkGenerator: Send + Sync + 'static { fn light_view(&self, _proto: &Proto) -> Option { None } - fn saved_proto(&self, _proto: &Proto) -> Option { + fn saved_proto(&self, _proto: &Proto) -> Option { None } /// Put a saved proto chunk's state back onto `proto`, generated again. - fn restore_proto(&self, _proto: &mut Proto, _saved: crate::save::SavedProto) {} + fn restore_proto(&self, _proto: &mut Proto, _saved: crate::chunk::SavedProto) {} /// Save proto chunks decoration wrote to, so that they come back as they /// were: generating them again would lose those writes. fn save_protos(&self, _protos: &[&Proto]) {} diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 0a4c9a88e..d05649f3a 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -69,6 +69,9 @@ pub fn loot_item_with_components(s: &horizon_world::loot::LootStack) -> ItemStac .stew_effects .push((Arc::from(effect.as_str()), *duration)); } + for (id, text) in &s.names { + item.data_mut().set_loot_name(id, text); + } item } @@ -257,6 +260,23 @@ mod tests { use super::*; use horizon_world::loot::{ExplorationMap, LootStack}; + #[test] + fn generated_end_gateway_keeps_its_exit() { + let Tag::Compound(nbt) = Tag::compound([ + ("exit_portal", Tag::IntArray(vec![100, 50, 0])), + ("ExactTeleport", Tag::Byte(1)), + ]) else { + unreachable!() + }; + let Some(BlockEntity::EndGateway(g)) = + generated_block_entity("minecraft:end_gateway", &nbt) + else { + panic!("gateway"); + }; + assert_eq!(g.exit_portal, Some([100, 50, 0])); + assert!(g.exact_teleport); + } + #[test] fn placed_chest_loot_keeps_its_enchantments_and_potions() { let stack = @@ -270,6 +290,7 @@ mod tests { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), }; // An End city chest's enchant_with_levels roll. let boots = loot_item_with_components(&stack( @@ -332,6 +353,7 @@ mod tests { })))), ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), }; let mut item = loot_item(&stack); assert!(has_pending_map(&item)); diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 9984cdcdf..d08917303 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -14,10 +14,12 @@ use std::{ }; mod create_world; +mod flat; #[cfg(test)] mod tests; pub mod world_management; pub use create_world::{DIFFICULTIES, WorldOptions}; +pub use flat::{FlatLayer, FlatSettings, State as FlatEditor}; /// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`. const LIST_TOP: f32 = 49.0; @@ -102,6 +104,16 @@ pub enum Mode { return_to: Box, }, Multiplayer(crate::multiplayer::Screen), + /// CreateFlatWorldScreen over Create New World: the fields that screen + /// keeps and the superflat editor on top of them. + CreateFlat { + name: String, + seed: String, + creative: bool, + focus: u8, + options: WorldOptions, + flat: flat::State, + }, } #[derive(Clone, Debug, PartialEq)] pub enum Action { @@ -129,6 +141,8 @@ pub struct Title { /// Direct Connection's address, synchronized with `options.txt`'s `lastServer`. pub last_server: String, pub saves: PathBuf, + /// The prepared resource root: the flat preset list and block registry. + resources: PathBuf, pub started: std::time::Instant, search: String, search_focused: bool, @@ -234,6 +248,7 @@ impl Title { mode, last_server: String::new(), saves, + resources: resources.to_owned(), started: now, search: String::new(), search_focused: false, @@ -320,6 +335,64 @@ impl Title { self.return_to_list(None); } } + /// A press on the superflat screens: their list, share box or buttons. + fn flat_click(&mut self, x: f32, y: f32, size: (f32, f32), hit: Option) { + match hit { + Some(70) => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.remove_selected(); + } + } + Some(71) => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.open_presets(); + } + } + Some(72) => self.close_flat(true), + Some(73) => self.close_flat(false), + Some(74) => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.apply_share(); + } + } + Some(75) => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.back_to_layers(); + } + } + None => { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat::click(flat, (x, y), size); + } + } + _ => {} + } + } + /// Return to Create New World, keeping (`apply`) or dropping the layers. + fn close_flat(&mut self, apply: bool) { + let mode = std::mem::replace(&mut self.mode, Mode::Main); + if let Mode::CreateFlat { + name, + seed, + creative, + focus, + mut options, + flat, + } = mode + { + if apply { + options.flat = true; + options.flat_settings = Some(flat.settings); + } + self.mode = Mode::Create { + name, + seed, + creative, + focus, + options, + }; + } + } fn matches_search(&self, world: &WorldEntry) -> bool { let filter = self.search.to_lowercase(); world.name.to_lowercase().contains(&filter) || world.folder.to_lowercase().contains(&filter) @@ -370,6 +443,10 @@ impl Title { if let Mode::Multiplayer(screen) = &mut self.mode { return screen.drag(cursor.1, size); } + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat::drag(flat, cursor, size); + return; + } if let Mode::Select { worlds, .. } = &self.mode { let (top, bottom, _, content) = self.world_list(worlds, size); let mut scroll = self.scroll.get(); @@ -385,6 +462,9 @@ impl Title { if let Mode::Multiplayer(screen) = &mut self.mode { screen.release(); } + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat::release(flat); + } self.scroll.get_mut().release(); } /// Mouse wheel over the classic world and server lists. @@ -396,6 +476,10 @@ impl Title { screen.wheel(delta, cursor, size); return; } + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat::wheel(flat, delta, cursor, size); + return; + } let Mode::Select { worlds, .. } = &self.mode else { return; }; @@ -720,6 +804,7 @@ impl Title { Mode::Create { creative, options, .. } => create_world::buttons(w, h, *creative, options), + Mode::CreateFlat { flat, .. } => flat::buttons(w, h, flat), Mode::Edit { world, name, .. } => { let x = (w / 2.0).floor() - 100.0; let top = edit_top(h); @@ -881,6 +966,11 @@ impl Title { } let version = format!("Horizon {} (Rust)", horizon_core::VANILLA_VERSION); batch.text(atlas, &version, 2.0, h - 10.0, u32::MAX, true); + // A nightly names its build in the top-left corner, the one spot no button reaches at any GUI + // scale, so screenshots and reports say which build they come from. + if let Some(nightly) = horizon_core::release::nightly_label() { + batch.text(atlas, &nightly, 2.0, 2.0, u32::MAX, true); + } let notice = "Not affiliated with Mojang or Microsoft"; let tw = HudBatch::text_width(atlas, notice); batch.text(atlas, notice, w - tw - 2.0, h - 10.0, u32::MAX, true); @@ -1042,6 +1132,7 @@ impl Title { options, .. } => self.draw_create(atlas, batch, cursor, name, seed, *focus, options), + Mode::CreateFlat { flat, .. } => flat::draw(self, atlas, batch, cursor, flat), Mode::Edit { name, focused, .. } => { crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); centered( @@ -1248,6 +1339,10 @@ impl Title { .into_iter() .find(|b| b.enabled && x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + 20.0) .map(|b| b.id); + if matches!(self.mode, Mode::CreateFlat { .. }) { + self.flat_click(x, y, (w, h), hit); + return (Action::None, hit.is_some()); + } let action = self.click_action(x, y, (w, h), hit); // World list selection is silent; launching its selected entry sounds. let sound = hit.is_some() || matches!(action, Action::Play { .. }); @@ -1416,6 +1511,27 @@ impl Title { *self.rules.get_mut() = Some(RulesScreen::for_creation(&options.rules)); Action::None } + ( + Mode::Create { + name, + seed, + creative, + focus, + options, + }, + Some(26), + ) => { + let flat = flat::State::new(&self.resources, options.flat_settings.clone()); + self.mode = Mode::CreateFlat { + name: name.clone(), + seed: seed.clone(), + creative: *creative, + focus: *focus, + options: options.clone(), + flat, + }; + Action::None + } ( Mode::Create { creative, options, .. @@ -1669,6 +1785,16 @@ impl Title { self.return_to_list(Some(&folder)); } Mode::Error { return_to, .. } => self.mode = *return_to.clone(), + Mode::CreateFlat { .. } => { + if matches!(&self.mode, Mode::CreateFlat { flat, .. } if flat.page == flat::Page::Presets) + { + if let Mode::CreateFlat { flat, .. } = &mut self.mode { + flat.back_to_layers(); + } + } else { + self.close_flat(false); + } + } Mode::Create { .. } => self.cancel_create(), _ => self.mode = Mode::Main, } @@ -1697,6 +1823,7 @@ const SEARCH: crate::clipboard::FieldId = ("world.search", 0); const EDIT_NAME: crate::clipboard::FieldId = ("world.edit-name", 0); const WORLD_NAME: crate::clipboard::FieldId = ("world.name", 0); const WORLD_SEED: crate::clipboard::FieldId = ("world.seed", 0); +const FLAT_SHARE: crate::clipboard::FieldId = ("world.flat-share", 0); /// The focused field of the world screens and the server screens: the list's /// search, a world name or seed, or Add Server, Direct Connection and Join a /// Friend. @@ -1720,6 +1847,9 @@ fn caret_field<'a>( _ => None, }, Mode::Multiplayer(screen) => screen.focused_text(), + Mode::CreateFlat { flat, .. } if flat.page == flat::Page::Presets && flat.share_focused => { + Some((FLAT_SHARE, &mut flat.share, 1230)) + } _ => None, } } diff --git a/crates/horizon-client/src/title/create_world.rs b/crates/horizon-client/src/title/create_world.rs index 65d4f60ac..c0611f0d5 100644 --- a/crates/horizon-client/src/title/create_world.rs +++ b/crates/horizon-client/src/title/create_world.rs @@ -32,6 +32,8 @@ pub struct WorldOptions { pub commands: Option, /// The Superflat world preset instead of Default. pub flat: bool, + /// CreateFlatWorldScreen's layers and biome, kept with the world type. + pub flat_settings: Option, pub structures: bool, pub bonus_chest: bool, /// `getGameRules`: the Game Rules screen's values, saved with the world. @@ -45,6 +47,7 @@ impl Default for WorldOptions { difficulty: 2, commands: None, flat: false, + flat_settings: None, structures: true, bonus_chest: false, rules: crate::gamerules::GameRules::default(), @@ -67,6 +70,10 @@ impl WorldOptions { .unwrap_or(2), commands: Some(commands), flat: generation.flat, + flat_settings: generation + .flat + .then(|| super::flat::FlatSettings::from_world(dir)) + .flatten(), structures: generation.structures, bonus_chest: generation.bonus_chest, rules: crate::gamerules::GameRules::load(dir), @@ -92,6 +99,12 @@ impl WorldOptions { bonus_chest: self.bonus_chest(), } } + /// The custom layers, as `write_world_gen_settings_with` takes them. + pub fn flat_settings(&self) -> Option { + self.flat_settings + .as_ref() + .map(super::flat::FlatSettings::to_tag) + } /// A press on one of the open tab's cycle buttons or switches. pub(super) fn press(&mut self, id: u8, creative: &mut bool) { match id { @@ -105,7 +118,13 @@ impl WorldOptions { } 23 => self.difficulty = (self.difficulty + 1) % DIFFICULTIES.len(), 24 => self.commands = Some(!self.commands(*creative)), - 25 => self.flat = !self.flat, + 25 => { + self.flat = !self.flat; + if self.flat { + // setWorldType starts the generator from the flat preset. + self.flat_settings = Some(super::flat::FlatSettings::default()); + } + } 27 => self.structures = !self.structures, 28 => self.bonus_chest = !self.bonus_chest, _ => {} @@ -247,13 +266,13 @@ pub(super) fn buttons(w: f32, h: f32, creative: bool, o: &WorldOptions) -> Vec, + pub structure_overrides: Vec, +} +impl Default for FlatSettings { + fn default() -> Self { + // worldgen/world_preset/flat.json's overworld. + Self { + biome: "minecraft:plains".into(), + features: false, + lakes: false, + layers: vec![ + FlatLayer { + block: "minecraft:bedrock".into(), + height: 1, + }, + FlatLayer { + block: "minecraft:dirt".into(), + height: 2, + }, + FlatLayer { + block: "minecraft:grass_block".into(), + height: 1, + }, + ], + structure_overrides: vec!["minecraft:strongholds".into(), "minecraft:villages".into()], + } + } +} +impl FlatSettings { + /// A saved world's flat generator settings, for Re-Create. + pub fn from_world(dir: &Path) -> Option { + let settings = crate::save::world_gen_settings(dir)?; + let generator = settings + .get("dimensions")? + .get("minecraft:overworld")? + .get("generator")?; + if crate::save::text(generator.get("type"))?.trim_start_matches("minecraft:") != "flat" { + return None; + } + Self::from_tag(generator.get("settings")?) + } + pub fn from_tag(tag: &Tag) -> Option { + let Some(Tag::List(list)) = tag.get("layers") else { + return None; + }; + let layers: Vec = list + .iter() + .filter_map(|layer| { + Some(FlatLayer { + block: crate::save::text(layer.get("block"))?, + height: crate::save::number(layer.get("height"))?.clamp(0, Y_SIZE as i64) + as i32, + }) + }) + .collect(); + // `layers: []` is a valid void flat world; a list whose entries all + // fail to parse is not. + if layers.is_empty() && !list.is_empty() { + return None; + } + let flag = |key: &str, default: bool| { + crate::save::number(tag.get(key)).map_or(default, |value| value != 0) + }; + let structure_overrides = match tag.get("structure_overrides") { + Some(Tag::String(text)) => vec![text.to_string_lossy()], + Some(Tag::List(list)) => list + .iter() + .filter_map(|value| crate::save::text(Some(value))) + .collect(), + _ => Vec::new(), + }; + Some(Self { + biome: crate::save::text(tag.get("biome")).unwrap_or_else(|| "minecraft:plains".into()), + features: flag("features", false), + lakes: flag("lakes", false), + layers, + structure_overrides, + }) + } + /// FlatLevelGeneratorSettings.CODEC, as world_gen_settings stores it. + pub fn to_tag(&self) -> Tag { + let string = |text: &str| Tag::String(text.into()); + Tag::compound([ + ("biome", string(&self.biome)), + ("features", Tag::Byte(i8::from(self.features))), + ("lakes", Tag::Byte(i8::from(self.lakes))), + ( + "layers", + Tag::List( + self.layers + .iter() + .map(|layer| { + Tag::compound([ + ("block", string(&layer.block)), + ("height", Tag::Int(layer.height)), + ]) + }) + .collect(), + ), + ), + ( + "structure_overrides", + Tag::List( + self.structure_overrides + .iter() + .map(|id| string(id)) + .collect(), + ), + ), + ]) + } + /// `CreateFlatWorldScreen.save`: the text the preset screen shows. + pub fn to_share(&self) -> String { + let layers = self + .layers + .iter() + .map(|layer| { + if layer.height == 1 { + layer.block.clone() + } else { + format!("{}*{}", layer.height, layer.block) + } + }) + .collect::>() + .join(","); + format!("{layers};{}", self.biome) + } + /// `PresetFlatWorldScreen.fromString`: `layers;biome`, keeping the + /// decorations the screen was opened with. `None` for a malformed list, + /// as vanilla falls back to the preset's own settings. + pub fn parse( + text: &str, + blocks: &BTreeSet, + biomes: &BTreeSet, + base: &Self, + ) -> Option { + let (layer_text, biome_text) = text.split_once(';').unwrap_or((text, "")); + let mut layers = Vec::new(); + let mut total = 0; + for part in layer_text.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + let (height, block) = match part.split_once('*') { + Some((height, block)) => (height.trim().parse::().ok()?, block.trim()), + None => (1, part), + }; + let block = namespaced(block); + if !blocks.is_empty() && !blocks.contains(&block) { + return None; + } + let height = height.max(0).min(Y_SIZE - total); + if height == 0 { + continue; + } + total += height; + layers.push(FlatLayer { block, height }); + } + if layers.is_empty() { + return None; + } + let mut biome = namespaced(biome_text.trim()); + if biome == "minecraft:" || biome.is_empty() { + biome = "minecraft:plains".into(); + } + if !biomes.is_empty() && !biomes.contains(&biome) { + biome = "minecraft:plains".into(); + } + Some(Self { + biome, + layers, + ..base.clone() + }) + } +} +/// `Identifier.parse`: bare names get the default namespace. +fn namespaced(id: &str) -> String { + if id.is_empty() || id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum Page { + Layers, + Presets, +} + +#[derive(Clone, Debug)] +pub struct State { + pub(super) page: Page, + pub(super) settings: FlatSettings, + /// The preset screen's share box (`createWorld.customize.presets.share`). + pub(super) share: String, + pub(super) share_focused: bool, + /// The selected layer, in the list's top-first order. + pub(super) selected: Option, + pub(super) scroll: ui::Scroll, + preset_selected: Option, + preset_scroll: ui::Scroll, + presets: Vec, + blocks: BTreeSet, + biomes: BTreeSet, +} +#[derive(Clone, Debug)] +struct Preset { + id: String, + display: String, + settings: FlatSettings, +} +impl State { + /// The layers the editor holds, for the control socket's state. + pub fn settings(&self) -> &FlatSettings { + &self.settings + } + pub(super) fn new(root: &Path, current: Option) -> Self { + let settings = current.unwrap_or_default(); + let (presets, blocks, biomes) = load(root); + Self { + page: Page::Layers, + share: settings.to_share(), + settings, + share_focused: false, + selected: None, + scroll: ui::Scroll::default(), + preset_selected: None, + preset_scroll: ui::Scroll::default(), + presets, + blocks, + biomes, + } + } + pub(super) fn open_presets(&mut self) { + self.page = Page::Presets; + self.preset_selected = None; + self.preset_scroll = ui::Scroll::default(); + self.share = self.settings.to_share(); + self.share_focused = false; + } + pub(super) fn back_to_layers(&mut self) { + self.page = Page::Layers; + self.share_focused = false; + } + pub(super) fn remove_selected(&mut self) { + let Some(row) = self.selected else { + return; + }; + let index = self.settings.layers.len().wrapping_sub(1 + row); + if index < self.settings.layers.len() { + self.settings.layers.remove(index); + } + self.selected = None; + } + /// PresetFlatWorldScreen's Select: parse the share text into the settings + /// the Create New World screen keeps. + pub(super) fn apply_share(&mut self) { + // PresetFlatWorldScreen keeps the selected preset's decorations while + // the share text supplies its layers and biome. + let base = self + .preset_selected + .and_then(|index| self.presets.get(index)) + .map(|preset| preset.settings.clone()) + .unwrap_or_else(|| self.settings.clone()); + // A malformed list falls back to FlatLevelGeneratorSettings.getDefault. + let settings = + FlatSettings::parse(&self.share, &self.blocks, &self.biomes, &base).unwrap_or_default(); + self.settings = settings; + self.share = self.settings.to_share(); + self.page = Page::Layers; + self.share_focused = false; + self.selected = None; + } + fn select_preset(&mut self, index: usize) { + let Some(preset) = self.presets.get(index) else { + return; + }; + self.preset_selected = Some(index); + self.share = preset.settings.to_share(); + self.share_focused = false; + } + fn selecting(&self) -> Option { + self.preset_selected + } +} + +/// `/data//worldgen/flat_level_generator_preset/.json`, +/// in the order of the `visible` tag, plus the block and biome ids the share +/// text is checked against. +fn load(root: &Path) -> (Vec, BTreeSet, BTreeSet) { + let mut presets = Vec::new(); + let tag_path = + root.join("data/minecraft/tags/worldgen/flat_level_generator_preset/visible.json"); + if let Ok(text) = std::fs::read_to_string(tag_path) + && let Ok(Value::Object(tag)) = serde_json::from_str(&text) + && let Some(Value::Array(ids)) = tag.get("values") + { + for id in ids.iter().filter_map(Value::as_str) { + let Some((namespace, path)) = id.split_once(':') else { + continue; + }; + let path = root.join(format!( + "data/{namespace}/worldgen/flat_level_generator_preset/{path}.json" + )); + let Ok(text) = std::fs::read_to_string(path) else { + continue; + }; + let Ok(value) = serde_json::from_str::(&text) else { + continue; + }; + let Some(settings) = preset_settings(&value) else { + continue; + }; + presets.push(Preset { + id: id.to_owned(), + display: value["display"] + .as_str() + .unwrap_or("minecraft:grass_block") + .to_owned(), + settings, + }); + } + } + let blocks = registry_ids(root, "minecraft:block"); + let biomes = json_keys(&root.join("worldgen/biomes.json")); + (presets, blocks, biomes) +} +fn preset_settings(value: &Value) -> Option { + let settings = value.get("settings")?; + let layers = settings + .get("layers")? + .as_array()? + .iter() + .filter_map(|layer| { + Some(FlatLayer { + block: layer.get("block")?.as_str()?.to_owned(), + height: layer.get("height")?.as_i64()? as i32, + }) + }) + .collect::>(); + if layers.is_empty() { + return None; + } + let structure_overrides = match settings.get("structure_overrides") { + Some(Value::String(id)) => vec![id.clone()], + Some(Value::Array(ids)) => ids + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + _ => Vec::new(), + }; + Some(FlatSettings { + biome: settings + .get("biome") + .and_then(Value::as_str) + .unwrap_or("minecraft:plains") + .to_owned(), + features: settings + .get("features") + .and_then(Value::as_bool) + .unwrap_or(false), + lakes: settings + .get("lakes") + .and_then(Value::as_bool) + .unwrap_or(false), + layers, + structure_overrides, + }) +} +/// The ids of a registry in the prepared `registries.json`. +fn registry_ids(root: &Path, registry: &str) -> BTreeSet { + let Ok(text) = std::fs::read_to_string(root.join("registries.json")) else { + return BTreeSet::new(); + }; + let Ok(value) = serde_json::from_str::(&text) else { + return BTreeSet::new(); + }; + value + .get(registry) + .and_then(|registry| registry.get("entries")) + .and_then(Value::as_object) + .map(|entries| entries.keys().cloned().collect()) + .unwrap_or_default() +} +fn json_keys(path: &Path) -> BTreeSet { + let Ok(text) = std::fs::read_to_string(path) else { + return BTreeSet::new(); + }; + let Ok(value) = serde_json::from_str::(&text) else { + return BTreeSet::new(); + }; + value + .as_object() + .map(|entries| entries.keys().cloned().collect()) + .unwrap_or_default() +} + +/// CreateFlatWorldScreen's list and the preset screen's list. +fn list_area(state: &State, size: (f32, f32)) -> (f32, f32, f32, f32) { + let (w, h) = (size.0.ceil(), size.1.ceil()); + let (top, bottom) = match state.page { + Page::Layers => (43.0, h - 60.0), + Page::Presets => (80.0, h - 37.0), + }; + let left = ((w - ROW_WIDTH) * 0.5).floor(); + let rows = match state.page { + Page::Layers => HEADER + state.settings.layers.len() as f32 * LAYER_ROW + 4.0, + Page::Presets => state.presets.len() as f32 * PRESET_ROW + 4.0, + }; + (top, bottom, left, rows) +} + +pub(super) fn buttons(w: f32, h: f32, state: &State) -> Vec