diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 000000000..af951fe12 --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,3 @@ +self-hosted-runner: + # The Mac mini's runner (ludovics-mac-mini), which holds the maintainer's own Minecraft files. + labels: [horizon-game, ludovics-mac-mini] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b1a63710..dd9cde557 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,14 +1,25 @@ name: checks +# verify: every pull request and every push to main, on GitHub's runners (the repository is public). +# parity: the vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the +# maintainer's own Minecraft files (Horizon never downloads the game). A fork's pull request runs it only when +# a maintainer adds the run-parity label, once per label. See docs/release-flow.md. on: push: branches: [main] pull_request: + types: [opened, synchronize, reopened, labeled] workflow_dispatch: permissions: contents: read +concurrency: + # A new push to a pull request replaces its running checks; main's runs all finish (releases follow them). + group: checks-${{ github.event.pull_request.number || github.sha }}-${{ github.event.action == 'labeled' && 'label' || 'run' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: verify: + if: github.event.action != 'labeled' runs-on: ubuntu-latest + timeout-minutes: 30 steps: - uses: actions/checkout@v4 with: @@ -26,12 +37,49 @@ jobs: run: | sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev rustup toolchain install stable --profile minimal --component rustfmt --component clippy + # Dependencies and the workspace's own build, saved from main's runs (pull requests read main's cache). + - uses: Swatinem/rust-cache@v2 + with: + shared-key: verify + save-if: ${{ github.ref == 'refs/heads/main' }} - name: Check formatting and lint run: | cargo +stable fmt --all -- --check cargo +stable clippy --workspace --all-targets -- -D warnings - name: Test Rust core and voxel kernel correctness run: cargo +stable test --workspace + parity: + if: >- + github.event_name == 'pull_request' && ( + (github.event.pull_request.head.repo.full_name == github.repository && github.event.action != 'labeled') || + (github.event.action == 'labeled' && github.event.label.name == 'run-parity')) + runs-on: [self-hosted, horizon-game] + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + # The commit the event names: a fork's later pushes need another run-parity label. + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + # Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs. + clean: false + - uses: dtolnay/rust-toolchain@stable + - name: Tools from the runner + run: bash tools/ci/runner-env.sh + - name: Vanilla data, and resources prepared by this preparer + run: bash tools/ci/vanilla-data.sh + - name: The harnesses this change can affect + env: + PARITY_HOSTS: '' + run: python3 tools/parity.py --changed ${{ github.event.pull_request.base.sha }} --timeout 1500 + - name: Logs of the failed harnesses + if: failure() + uses: actions/upload-artifact@v4 + with: + name: parity-logs + path: .local/parity-runner/logs/ + if-no-files-found: ignore # Horizon never downloads the game. These jobs need a self-hosted Linux runner # (label horizon-game) holding the maintainer's own copy: the official launcher's # game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index 50a9ca9ca..d41b38092 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -1,64 +1,156 @@ name: launcher -# Builds the launcher on Linux, macOS and Windows. A pushed `launcher-vX.Y.Z` tag also puts the -# three archives on a draft GitHub release of that tag, to publish by hand. Horizon's own -# releases are tagged `vYYYY.MM.DD`; the launcher reads only `launcher-v*` releases for itself. +# Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a +# push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme), +# every hour (a release the cooldown held goes out) and by hand, tools/release_train.py decides as for the game. +# A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull +# request is labelled feature. The version is given to the build (HORIZON_LAUNCHER_VERSION): no bump commits. +# Never marked latest. Pushes to launcher branches only build. RELEASES_PAUSED=1 stops releases. +# gh workflow run launcher --ref # dry run: builds everything, publishes nothing +# gh workflow run launcher --ref main -f dry_run=false -f force=true on: - workflow_dispatch: push: - branches: [launcher, 'launcher-*'] - tags: ['launcher-v*'] + branches: [main, launcher, 'launcher-*'] + paths: + - 'launcher/**' + - 'crates/horizon-prepare/**' + - 'crates/horizon-theme/**' + - '.github/workflows/launcher.yml' + schedule: + - cron: '47 * * * *' + workflow_dispatch: + inputs: + dry_run: + description: Build everything and write the notes, but publish nothing + type: boolean + default: true + force: + description: Release even without launcher changes, within the cooldown or while paused + type: boolean + default: false permissions: contents: read +concurrency: + group: launcher-${{ github.ref == 'refs/heads/main' && 'release' || github.ref }} + cancel-in-progress: false + jobs: + decide: + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + release: ${{ steps.decide.outputs.release }} + tag: ${{ steps.decide.outputs.tag }} + head: ${{ steps.decide.outputs.head }} + version: ${{ steps.decide.outputs.version }} + dry_run: ${{ steps.mode.outputs.dry_run }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - id: mode + # Off main every run is a dry run (a launcher branch's push only builds). + run: echo "dry_run=${{ github.ref != 'refs/heads/main' || (github.event_name == 'workflow_dispatch' && inputs.dry_run) }}" >> "$GITHUB_OUTPUT" + - id: decide + env: + GH_TOKEN: ${{ github.token }} + RELEASES_PAUSED: ${{ vars.RELEASES_PAUSED }} + # A push or a run off main builds its own commit; otherwise main's newest commit with green checks. + HEAD_SHA: ${{ (github.event_name == 'push' || steps.mode.outputs.dry_run == 'true') && github.sha || '' }} + FORCE: ${{ inputs.force && 'yes' || '' }} + run: | + python3 tools/release_train.py decide --kind launcher ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json + echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY" + tag=$(jq -r '.tag' decision.json) + echo "version=${tag#launcher-v}" >> "$GITHUB_OUTPUT" + # A dry run (and a launcher branch's push) builds whatever the decision. + if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then + echo "release=true" >> "$GITHUB_OUTPUT" + echo "head=$GITHUB_SHA" >> "$GITHUB_OUTPUT" + fi + build: + needs: decide + if: needs.decide.outputs.release == 'true' + name: build ${{ matrix.name }} strategy: fail-fast: false matrix: include: - - os: ubuntu-latest + - name: linux + os: ubuntu-22.04 asset: horizon-launcher-linux-x86_64.tar.gz binary: horizon-launcher - - os: macos-latest + - name: macos + mac: true asset: horizon-launcher-macos-arm64.zip binary: horizon-launcher - - os: windows-latest + - name: windows + os: windows-latest asset: horizon-launcher-windows-x64.zip binary: horizon-launcher.exe # The C runtime linked in: without it the launcher asks for VCRUNTIME140.dll, # which only the Visual C++ redistributable installs. rustflags: -C target-feature=+crt-static - runs-on: ${{ matrix.os }} + runs-on: ${{ matrix.mac && (vars.MAC_RUNNER || 'ludovics-mac-mini') || matrix.os }} + timeout-minutes: 40 env: RUSTFLAGS: ${{ matrix.rustflags }} # Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository # variable, not a secret. Unset, the launcher says sign-in is not configured. HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }} + # The release's version, built in (launcher/src/backend.rs VERSION); a launcher branch's build keeps + # Cargo.toml's. + HORIZON_LAUNCHER_VERSION: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.version || '' }} defaults: run: working-directory: launcher shell: bash steps: - uses: actions/checkout@v4 + with: + ref: ${{ needs.decide.outputs.head }} + persist-credentials: false + # The Mac mini's runner keeps its target/ between runs. + clean: ${{ runner.environment == 'github-hosted' }} - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 + if: runner.environment == 'github-hosted' with: workspaces: launcher + shared-key: launcher-${{ matrix.name }} - name: Linux libraries GPUI links to if: runner.os == 'Linux' run: | sudo apt-get update sudo apt-get install -y libxkbcommon-x11-dev libwayland-dev libx11-xcb-dev libfontconfig-dev libvulkan-dev libasound2-dev - - name: The tag matches Cargo.toml - if: startsWith(github.ref, 'refs/tags/launcher-v') - run: grep -qx "version = \"${GITHUB_REF_NAME#launcher-v}\"" Cargo.toml - - run: cargo test --release --locked --lib - - run: cargo build --release --locked + - name: Metal shaders compiled now, or at run time without the Metal toolchain + # GPUI compiles its Metal shaders when it builds; the Mac mini has Xcode without the Metal toolchain + # (xcodebuild -downloadComponent MetalToolchain), so there they are compiled when the launcher starts. + if: runner.os == 'macOS' + run: | + if ! xcrun metal --version > /dev/null 2>&1; then + echo "::notice::No Metal toolchain on this runner: GPUI compiles its shaders at run time" + echo "LAUNCHER_FEATURES=gpui/runtime_shaders" >> "$GITHUB_ENV" + fi + - run: cargo test --release --locked --lib ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} + - run: cargo build --release --locked ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} + - name: The version is the release's + run: | + out=$(target/release/${{ matrix.binary }} --version) + echo "$out" + expected="${HORIZON_LAUNCHER_VERSION:-$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)}" + [[ "$out" == "horizon-launcher $expected" ]] || { echo "::error::expected horizon-launcher $expected"; exit 1; } - name: Only system libraries - if: runner.os == 'Windows' - run: python ../tools/check_imports.py target/release/${{ matrix.binary }} + run: | + file=target/release/${{ matrix.binary }} + case "$RUNNER_OS" in + Windows) python ../tools/check_imports.py "$file" ;; + macOS) others=$(otool -L "$file" | tail -n +2 | awk '{print $1}' | grep -v -E '^(/usr/lib/|/System/Library/)' || true) + [[ -z "$others" ]] || { echo "::error::links $others"; exit 1; } ;; + esac - name: Smoke test env: HORIZON_LAUNCHER_NO_SELF_UPDATE: '1' @@ -67,10 +159,10 @@ jobs: set -euo pipefail export HORIZON_LAUNCHER_HOME="${RUNNER_TEMP//\\//}/horizon-launcher-smoke" export HORIZON_HOME="$HORIZON_LAUNCHER_HOME/game" + rm -rf "$HORIZON_LAUNCHER_HOME" launcher="$PWD/target/release/${{ matrix.binary }}" # GitHub's API rate-limits shared runner addresses now and then: try a few times. retry() { for i in 1 2 3 4; do "$@" && return 0; sleep $((i * 15)); done; return 1; } - "$launcher" --version retry "$launcher" versions retry "$launcher" install latest "$launcher" versions --installed @@ -86,46 +178,74 @@ jobs: soft() { if [[ "$RUNNER_OS" == "Linux" ]]; then "$@" || echo "::warning::$* failed"; else "$@"; fi; } if [[ "$RUNNER_OS" == "Windows" ]]; then python ../tools/check_imports.py "$client" - python ../tools/check_imports.py "$launcher" elif [[ "$RUNNER_OS" == "Linux" ]]; then soft python3 ../tools/check_imports.py "$client" fi # The client starts: --help prints before any window or GPU is needed. help() { "$client" --help > "$RUNNER_TEMP/help.txt" 2>&1 && head -3 "$RUNNER_TEMP/help.txt" && grep -q -- '--resources' "$RUNNER_TEMP/help.txt"; } soft help + rm -rf "$HORIZON_LAUNCHER_HOME" - name: Package run: | - mkdir -p dist - cp target/release/${{ matrix.binary }} dist/ - cd dist - if [[ "${{ matrix.asset }}" == *.tar.gz ]]; then - tar czf ../${{ matrix.asset }} ${{ matrix.binary }} - elif [[ "$RUNNER_OS" == "Windows" ]]; then - 7z a ../${{ matrix.asset }} ${{ matrix.binary }} + rm -rf dist out && mkdir -p out + if [[ "$RUNNER_OS" == "macOS" ]]; then + # Horizon.app, zipped (self-update) and in a .dmg (installer): packaging/macos. + python3 -m venv "$RUNNER_TEMP/dmg" && "$RUNNER_TEMP/dmg/bin/pip" install --quiet dmgbuild==1.6.5 + version=${HORIZON_LAUNCHER_VERSION:-$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)} + DMGBUILD="$RUNNER_TEMP/dmg/bin/dmgbuild" ../packaging/macos/package.sh target/release/${{ matrix.binary }} "$version" out + rm -rf out/Horizon.app else - zip ../${{ matrix.asset }} ${{ matrix.binary }} + mkdir -p dist + cp target/release/${{ matrix.binary }} dist/ + if [[ "${{ matrix.asset }}" == *.tar.gz ]]; then + (cd dist && tar czf ../out/${{ matrix.asset }} ${{ matrix.binary }}) + else + (cd dist && 7z a ../out/${{ matrix.asset }} ${{ matrix.binary }}) + fi fi + ls -l out - uses: actions/upload-artifact@v4 with: name: ${{ matrix.asset }} - path: launcher/${{ matrix.asset }} + path: launcher/out/* + retention-days: 7 release: - if: startsWith(github.ref, 'refs/tags/launcher-v') - needs: build + needs: [decide, build] runs-on: ubuntu-latest + timeout-minutes: 10 permissions: contents: write steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Notes + env: + GH_TOKEN: ${{ github.token }} + run: | + python3 tools/release_train.py notes --kind launcher --tag "${{ needs.decide.outputs.tag }}" \ + --head "${{ needs.decide.outputs.head }}" --out notes > /dev/null + { echo "## $(cat notes/title.txt)"; echo; cat notes/body.md; } >> "$GITHUB_STEP_SUMMARY" - uses: actions/download-artifact@v4 with: path: dist merge-multiple: true - # A draft, and never marked latest: Horizon's own releases stay the repository's latest. - - uses: softprops/action-gh-release@v2 + # Never marked latest: Horizon's own releases stay the repository's latest. + - name: Publish ${{ needs.decide.outputs.tag }} + if: needs.decide.outputs.dry_run != 'true' + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.decide.outputs.tag }} + run: | + gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ + --notes-file notes/body.md --latest=false dist/horizon-launcher-* + - name: Dry run, the release that would be published + if: needs.decide.outputs.dry_run == 'true' + run: | + echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)" + ls -l dist + - uses: actions/upload-artifact@v4 with: - tag_name: ${{ github.ref_name }} - name: Horizon launcher ${{ github.ref_name }} - draft: true - make_latest: false - files: dist/* + name: launcher-release-notes + path: notes/ diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 000000000..59560e262 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,79 @@ +name: nightly audit +# Every vanilla harness, from scratch, on main, at 03:00 Paris time on the Mac mini's runner (it holds the +# maintainer's own Minecraft files). The resources are prepared again first when the preparer or its exporters +# changed (tools/ci/vanilla-data.sh). A harness that passed in the previous audit and fails now gets an issue +# labelled parity-regression (one per harness); its issue closes when it passes again +# (tools/ci/parity_issues.py). The bugs session picks those up. See docs/release-flow.md. +# gh workflow run "nightly audit" # now +# gh workflow run "nightly audit" -f dry_run=true # the audit, without touching issues +on: + schedule: + # GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:00 in Paris. + - cron: '7 1 * * *' + - cron: '7 2 * * *' + workflow_dispatch: + inputs: + dry_run: + description: Run the audit, but only print what it would do with issues + type: boolean + default: false +permissions: + contents: read + issues: write +concurrency: + group: nightly-audit + cancel-in-progress: false +jobs: + audit: + runs-on: [self-hosted, horizon-game] + timeout-minutes: 150 + steps: + - name: 03:00 in Paris + id: when + run: | + hour=$(TZ=Europe/Paris date +%H) + if [[ "${{ github.event_name }}" == schedule && "$hour" != 03 ]]; then + echo "It is ${hour}:00 in Paris: the other schedule runs the audit." + echo "run=false" >> "$GITHUB_OUTPUT" + else + echo "run=true" >> "$GITHUB_OUTPUT" + fi + - uses: actions/checkout@v4 + if: steps.when.outputs.run == 'true' + with: + fetch-depth: 0 + persist-credentials: false + # Keeps .local/ (parity state, probe builds, the previous audit) and target/. + clean: false + - uses: dtolnay/rust-toolchain@stable + if: steps.when.outputs.run == 'true' + - name: Tools from the runner + if: steps.when.outputs.run == 'true' + run: bash tools/ci/runner-env.sh + - name: Vanilla data, prepared again if the preparer changed + if: steps.when.outputs.run == 'true' + run: bash tools/ci/vanilla-data.sh + - name: Every harness + id: audit + if: steps.when.outputs.run == 'true' + env: + PARITY_HOSTS: '' + run: | + echo "since=$(date +%Y-%m-%dT%H:%M:%S)" >> "$GITHUB_OUTPUT" + set +e + python3 tools/parity.py --all --timeout 1800 2>&1 | tee "$RUNNER_TEMP/audit.log" + echo "exit=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT" + { echo '```'; tail -40 "$RUNNER_TEMP/audit.log"; echo '```'; } >> "$GITHUB_STEP_SUMMARY" + - name: Issues for the harnesses that regressed + if: steps.when.outputs.run == 'true' && always() && steps.audit.outputs.since + env: + GH_TOKEN: ${{ github.token }} + run: python3 tools/ci/parity_issues.py --since "${{ steps.audit.outputs.since }}" ${{ inputs.dry_run && '--dry-run' || '' }} | tee -a "$GITHUB_STEP_SUMMARY" + - name: Logs of the failed harnesses + if: steps.when.outputs.run == 'true' && steps.audit.outputs.exit != '0' + uses: actions/upload-artifact@v4 + with: + name: nightly-parity-logs + path: .local/parity-runner/logs/ + if-no-files-found: ignore + retention-days: 14 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 88a91ee97..4b8444176 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,57 +1,223 @@ -name: release builds -# Started by hand: gh workflow run release.yml --ref -# Builds the Windows x64 and Linux x86_64 clients (with horizon-ctl and horizon-prepare) and uploads the playable folders -# as artifacts. -# macOS builds are made on the development machines. Linux is built here, on an older Ubuntu, -# so the binary uses the standard loader and runs on any recent distribution (and on NixOS -# through nix-ld): a build made on NixOS asks for a /nix/store loader no other system has. +name: release +# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every hour (a release +# held by the cooldown goes out without another merge) and by hand, tools/release_train.py decides: a release +# when a pull request merged since the last one changed what players run and that release is 3 hours old, or at +# once for a pull request labelled release-now. RELEASES_PAUSED=1 (repository variable) stops them. +# Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and +# Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then +# publishes vYYYY.MM.DD[.N] with notes from the merged pull requests. +# gh workflow run release --ref # dry run: builds and notes, publishes nothing +# gh workflow run release -f dry_run=false -f force=true # on main: release now, whatever the rules say on: + workflow_run: + workflows: [checks] + types: [completed] + branches: [main] + schedule: + - cron: '17 * * * *' workflow_dispatch: + inputs: + dry_run: + description: Build everything and write the notes, but publish nothing + type: boolean + default: true + force: + description: Release even without player-facing changes, within the cooldown or while paused + type: boolean + default: false permissions: contents: read +concurrency: + group: game-release + cancel-in-progress: false jobs: - windows: - runs-on: windows-latest + decide: + if: >- + github.event_name != 'workflow_run' || + (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push') + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + release: ${{ steps.decide.outputs.release }} + tag: ${{ steps.decide.outputs.tag }} + head: ${{ steps.decide.outputs.head }} + dry_run: ${{ steps.mode.outputs.dry_run }} steps: - uses: actions/checkout@v4 - - name: Install Rust toolchain - run: rustup toolchain install stable --profile minimal - - name: Build the client - # The C runtime linked in, so the game runs without the Visual C++ redistributable. + with: + fetch-depth: 0 + - 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: decide env: - RUSTFLAGS: -C target-feature=+crt-static - run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare - - name: Only system DLLs - # Vulkan and the rest are loaded at run time; a linked non-system DLL is a - # "DLL not found" dialog on some players' machines. + GH_TOKEN: ${{ github.token }} + RELEASES_PAUSED: ${{ vars.RELEASES_PAUSED }} + # The commit whose checks just passed; a dry run builds the branch it was started on; otherwise + # main's newest commit with green checks. + HEAD_SHA: ${{ github.event.workflow_run.head_sha || (steps.mode.outputs.dry_run == 'true' && github.sha) || '' }} + FORCE: ${{ inputs.force && 'yes' || '' }} run: | - python tools/check_imports.py target/release/horizon-client.exe - python tools/check_imports.py target/release/horizon-ctl.exe - python tools/check_imports.py target/release/horizon-prepare.exe - - name: Package - run: cargo +stable run --locked -p xtask -- package target/release/horizon-client.exe dist/horizon-windows-x64 - - uses: actions/upload-artifact@v4 - with: - name: horizon-windows-x64 - path: dist/horizon-windows-x64 - linux: - runs-on: ubuntu-22.04 + python3 tools/release_train.py decide --kind game ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json + echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY" + # 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 + + build: + needs: decide + 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 + - 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 }} + timeout-minutes: 40 + env: + RUSTFLAGS: ${{ matrix.rustflags }} + defaults: + run: + shell: bash steps: - uses: actions/checkout@v4 - - name: Install Rust toolchain - run: rustup toolchain install stable --profile minimal + with: + ref: ${{ needs.decide.outputs.head }} + persist-credentials: false + # On the Mac mini's runner, keep target/ (incremental) and .local/ (the prepared resources). + clean: ${{ runner.environment == 'github-hosted' }} + - 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 - run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare - - name: Standard loader and libraries only + - name: Build the client, horizon-ctl and horizon-prepare + run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare + - name: Every program the release folder takes was built run: | - python3 tools/check_imports.py target/release/horizon-client - python3 tools/check_imports.py target/release/horizon-ctl - python3 tools/check_imports.py target/release/horizon-prepare + for binary in horizon-client horizon-ctl horizon-prepare; do + test -f "target/release/$binary${{ matrix.exe }}" || { echo "::error::target/release/$binary${{ matrix.exe }} is missing"; exit 1; } + 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; 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 }}" --version + "$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir' + - 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 --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 - name: Package - run: cargo +stable run --locked -p xtask -- package target/release/horizon-client dist/horizon-linux-x86_64 + 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 ditto -c -k --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}"; fi ;; + esac + ls -l "${{ matrix.asset }}" - uses: actions/upload-artifact@v4 with: - name: horizon-linux-x86_64 - path: dist/horizon-linux-x86_64 + name: ${{ matrix.asset }} + path: dist/${{ matrix.asset }} + if-no-files-found: error + retention-days: 7 + + publish: + needs: [decide, build] + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Notes + env: + GH_TOKEN: ${{ github.token }} + run: | + python3 tools/release_train.py notes --kind game --tag "${{ needs.decide.outputs.tag }}" \ + --head "${{ needs.decide.outputs.head }}" --out notes > /dev/null + { echo "## $(cat notes/title.txt)"; echo; cat notes/body.md; } >> "$GITHUB_STEP_SUMMARY" + - uses: actions/download-artifact@v4 + with: + path: dist + merge-multiple: true + - name: Publish ${{ needs.decide.outputs.tag }} + if: needs.decide.outputs.dry_run != 'true' + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.decide.outputs.tag }} + run: | + gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ + --notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \ + dist/horizon-macos-arm64.zip + - name: Dry run, the release that would be published + if: needs.decide.outputs.dry_run == 'true' + run: | + echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)" + ls -l dist + - uses: actions/upload-artifact@v4 + with: + name: release-notes + path: notes/ diff --git a/.gitignore b/.gitignore index 22e289788..ad41a3230 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ /dist/ /mods/horizon/build/ /saves/ +/backups/ /tools/logs/ .DS_Store # What the client writes to its working directory when run from the repo root. diff --git a/Cargo.lock b/Cargo.lock index 4694fb718..0753fc7d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -923,6 +923,8 @@ dependencies = [ "ureq", "wgpu", "winit", + "winresource", + "zip", ] [[package]] @@ -2346,6 +2348,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + [[package]] name = "sha1" version = "0.10.7" @@ -2663,6 +2674,21 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "toml" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + [[package]] name = "toml_datetime" version = "1.1.1+spec-1.1.0" @@ -2693,6 +2719,12 @@ dependencies = [ "winnow", ] +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + [[package]] name = "tracing" version = "0.1.44" @@ -3558,6 +3590,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winresource" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" +dependencies = [ + "toml", + "version_check", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -3648,6 +3690,9 @@ checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" [[package]] name = "xtask" version = "0.1.0" +dependencies = [ + "horizon-theme", +] [[package]] name = "xxhash-rust" diff --git a/README.md b/README.md index 2ed714b7f..c766eba04 100644 --- a/README.md +++ b/README.md @@ -47,8 +47,8 @@ Horizon is downloaded only through **the Horizon launcher**: get it from [playho - - + +
The launcher's Play page: v2026.10.13.1 ready to play, its summary, Client and Server, the Play button and prepared resourcesThe launcher's Patch notes page, showing the notes of Horizon 2026.10.13.1The launcher's Play page: v2026.10.14.1 ready to play, its summary, Client and Server, the version picker and Play, the resources and the Minecraft folder as a numbered listThe launcher's Patch notes page, showing the notes of Horizon 2026.10.14.1
@@ -62,7 +62,7 @@ Captured in the Rust client itself, with vanilla assets and no mods or shaders. - + diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 42841eecb..12aeaae4a 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -28,11 +28,16 @@ chrono = { version = "0.4.42", default-features = false, features = ["clock", "s flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } horizon-theme = { path = "../horizon-theme" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } +zip = { version = "2", default-features = false, features = ["deflate"] } # Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). gilrs = "0.11" # HTTPS to the Minecraft services (online-mode session join). ureq = { version = "2", default-features = false, features = ["tls"] } +[target.'cfg(windows)'.build-dependencies] +# The icon resource in the .exe (build.rs). +winresource = "0.1" + [features] # Records the call sites of mob random draws (`mob_ai_probe` traces). rng-trace = ["horizon-core/rng-trace"] diff --git a/crates/horizon-client/build.rs b/crates/horizon-client/build.rs new file mode 100644 index 000000000..d99b304f3 --- /dev/null +++ b/crates/horizon-client/build.rs @@ -0,0 +1,15 @@ +//! Embeds Horizon's icon (`packaging/icons/horizon.ico`) in the Windows executables, as icon +//! resource 1: Explorer and the task bar show it, and the window takes it as its icon. +fn main() { + let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default(); + let ico = format!("{dir}/../../packaging/icons/horizon.ico"); + println!("cargo:rerun-if-changed={ico}"); + #[cfg(windows)] + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + let mut resource = winresource::WindowsResource::new(); + resource.set_icon(&ico); + if let Err(e) = resource.compile() { + panic!("embedding {ico}: {e}"); + } + } +} diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/arrow_probe.rs new file mode 100644 index 000000000..c8aed6a46 --- /dev/null +++ b/crates/horizon-client/examples/arrow_probe.rs @@ -0,0 +1,312 @@ +//! Arrows over the client's resident scene (`arrows::tick`), for +//! tools/test_arrow_parity.py: one line of state and one of events per operation. +#![forbid(unsafe_code)] +use horizon_client::{ + Result, + arrows::{ + self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, Pickup, Touch, + }, + assets::Assets, + blocks::BlockFacts, + collisions, + items::ItemStack, + mobs::Who, + motion::{LAVA, MotionResources, WATER}, + projectiles::{Projectile, ProjectileKind}, + world::World, +}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; +use serde_json::Value; +use std::{ + fs, + io::{BufRead, Write}, + path::PathBuf, +}; +fn number(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn vector(v: &Value) -> Vec3 { + Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) +} +fn bits(v: Vec3) -> String { + format!( + "{:016x},{:016x},{:016x}", + v.x.to_bits(), + v.y.to_bits(), + v.z.to_bits() + ) +} +fn seed(v: &Value) -> i64 { + v.as_str().unwrap().parse().unwrap() +} +fn particle(k: ArrowParticle) -> &'static str { + match k { + ArrowParticle::Bubble => "bubble", + ArrowParticle::Crit => "crit", + ArrowParticle::Splash => "splash", + } +} +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + if args.len() != 3 { + return Err("usage: arrow_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into()); + } + let root = PathBuf::from(&args[0]); + let dir = PathBuf::from(&args[1]); + let assets = Assets::load(&root)?; + let mut scene = World::test_scene(&assets, 1)?; + fs::write( + dir.join("scene.json"), + serde_json::to_vec( + &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":assets.model_gallery}), + )?, + )?; + if args[2] == "--describe" { + return Ok(()); + } + let binding = collisions::load(&root, assets.registry)?; + let motion = MotionResources::load(&root, &assets)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let side = &args[2]; + let mut out = std::io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); + let mut level_random = LegacyRandom::new(0); + for line in std::io::BufReader::new(fs::File::open(dir.join("inputs.txt"))?).lines() { + let f: Value = serde_json::from_str(&line?)?; + let kind = ProjectileKind::Arrow { + base_damage: 2.0, + critical: f["crit"].as_bool().unwrap(), + effect: None, + }; + let mut arrow = Projectile::new(kind, vector(&f["position"]), None) + .with_arrow_random(LegacyRandom::new(seed(&f["seed"]))); + arrow.velocity = vector(&f["velocity"]); + arrow.arrow.as_mut().unwrap().no_physics = f["no_physics"].as_bool().unwrap(); + // ProjectileWeaponItem.useAmmo's stack, intangible when no ammo was used. + arrow.arrow.as_mut().unwrap().set_item(&arrows::drawn_ammo( + &ItemStack::new("minecraft:arrow", 1), + f["intangible"].as_bool().unwrap(), + )); + for op in f["ops"].as_array().unwrap() { + let mut events = Vec::new(); + let mut touched = "-".to_string(); + match op["mode"].as_str().unwrap() { + "tick" => { + if !arrow.arrow.as_ref().unwrap().removed { + let no_rain = |_| false; + let view = ArrowScene { + world: &scene, + registry: assets.registry, + facts: &facts, + collision: &binding, + fluids: &motion.fluids, + raining: &no_rain, + mob_griefing: true, + tnt_explodes: true, + }; + arrows::tick(&mut arrow, &view, &[]); + } + for event in arrow.arrow.as_mut().unwrap().events.drain(..) { + match event { + ArrowEvent::Particle { + kind, + position, + velocity, + } => events.push(format!( + "particle {} {} {}", + particle(kind), + bits(position), + bits(velocity) + )), + ArrowEvent::Sound { + sound, + volume, + pitch, + } => events.push(format!( + "sound {} {:08x} {:08x}", + match sound { + ArrowSound::HitGround => "hit", + ArrowSound::Splash => "splash", + ArrowSound::Extinguish => "extinguish", + }, + volume.to_bits(), + pitch.to_bits() + )), + ArrowEvent::BubbleColumnParticles { pos } => { + for _ in 0..2 { + let x = f64::from(pos.x) + level_random.next_double(); + let z = f64::from(pos.z) + level_random.next_double(); + let at = Vec3::new(x, f64::from(pos.y + 1), z); + events.push(format!( + "sent splash {} {} {:016x}", + bits(at), + bits(Vec3::ZERO), + 1.0f64.to_bits() + )); + let x = f64::from(pos.x) + level_random.next_double(); + let z = f64::from(pos.z) + level_random.next_double(); + let at = Vec3::new(x, f64::from(pos.y + 1), z); + events.push(format!( + "sent bubble {} {} {:016x}", + bits(at), + bits(Vec3::new(0.0, 0.01, 0.0)), + 0.2f64.to_bits() + )); + } + } + ArrowEvent::Block { pos, reaction } => match reaction { + BlockReaction::PrimeTnt => { + // TntBlock.prime: PrimedTnt draws its push from the + // level random, then removeBlock(pos, false). + let _ = level_random.next_double(); + let at = Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ); + events.push(format!("spawn tnt {} 80", bits(at))); + events.push(format!( + "sound tnt_primed {:08x} {:08x}", + 1.0f32.to_bits(), + 1.0f32.to_bits() + )); + events.push("prime-event".into()); + let air = + assets.registry.default_state("minecraft:air").unwrap(); + scene.set(pos.x, pos.y, pos.z, air)?; + events.push(format!( + "write {},{},{} {} 3", + pos.x, pos.y, pos.z, air.0 + )); + } + BlockReaction::Light(lit) => { + scene.set(pos.x, pos.y, pos.z, lit)?; + events.push(format!( + "write {},{},{} {} 11", + pos.x, pos.y, pos.z, lit.0 + )); + } + }, + ArrowEvent::SplashEvent => events.push("splash-event".into()), + ArrowEvent::ShootEvent => events.push("shoot-event".into()), + } + } + } + "block" => { + let p = &op["position"]; + let mut state = assets + .registry + .default_state(op["name"].as_str().unwrap()) + .ok_or("missing fixture block")?; + if let Some(properties) = op["properties"].as_object() { + let mut definition = assets.registry.state(state).unwrap().clone(); + for (name, value) in properties { + definition + .properties + .insert(name.clone(), value.as_str().unwrap().into()); + } + state = assets + .registry + .id(&definition) + .ok_or("missing fixture state")?; + } + scene.set( + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + state, + )?; + } + "velocity" => arrow.velocity = vector(&op["value"]), + "ignite" => arrow + .arrow + .as_mut() + .unwrap() + .ignite_for_seconds(f32::from_bits( + u32::from_str_radix(op["value"].as_str().unwrap(), 16).unwrap(), + )), + "level_seed" => level_random.set_seed(seed(&op["value"])), + "owner" => arrow + .arrow + .as_mut() + .unwrap() + .set_owner(match op["value"].as_str() { + Some("player") => Some(Who::Player), + Some("mob") => Some(Who::Mob(1)), + _ => None, + }), + "pickup" => { + arrow.arrow.as_mut().unwrap().pickup = + Pickup::from_byte(op["value"].as_i64().unwrap()) + } + // The game's touch: the inventory takes the arrow unless full, + // and a creative player takes it anyway. + "touch" => { + let creative = op["creative"].as_bool().unwrap(); + let full = op["inventory"] == "full"; + let a = arrow.arrow.as_mut().unwrap(); + let (taken, arrows) = match a.player_touch(creative) { + Touch::Ignore => (false, 0), + Touch::Take => (true, 0), + Touch::Give(_) => (!full || creative, u32::from(!full)), + }; + if taken { + a.removed = true; + } + touched = format!("{taken} {arrows}"); + } + other => return Err(format!("unknown operation {other}").into()), + } + let a = arrow.arrow.as_ref().unwrap(); + writeln!( + out, + "arrow {} {} {:08x} {:08x} {} {} {} {} {} {} {} {} {} {:016x} {:016x} {} {} {:016x}", + bits(arrow.position), + bits(arrow.velocity), + arrow.pitch.to_bits(), + arrow.yaw.to_bits(), + a.in_ground, + a.in_ground_time, + a.life, + a.shake, + a.last_state.map_or("none".into(), |s| s.0.to_string()), + a.fire_ticks, + a.was_touching_water, + a.was_eye_in_water, + a.first_tick, + a.fluids.fluid_height(&Tags, WATER).to_bits(), + a.fluids.fluid_height(&Tags, LAVA).to_bits(), + a.removed, + arrow.critical(), + a.fall_distance.to_bits() + )?; + writeln!(out, "events {}", events.join(" | "))?; + let a = arrow.arrow.as_ref().unwrap(); + let intangible = a + .pickup_item + .data() + .and_then(|d| d.other(arrows::INTANGIBLE)) + .is_some(); + writeln!(out, "pickup {} {intangible} {touched}", a.pickup.byte())?; + } + writeln!(out, "end")?; + } + Ok(()) +} +struct Tags; +impl horizon_world::entity_fluid::FluidMembership for Tags { + fn fluid_in_tag( + &self, + kind: horizon_world::fluid::FluidKind, + tag: horizon_world::entity_fluid::FluidTagId, + ) -> bool { + use horizon_world::fluid::FluidKind; + if tag == WATER { + matches!(kind, FluidKind::Water | FluidKind::FlowingWater) + } else { + matches!(kind, FluidKind::Lava | FluidKind::FlowingLava) + } + } +} diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/entity_anim_fixture.rs index 663bc288a..e5a146ef9 100644 --- a/crates/horizon-client/examples/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/entity_anim_fixture.rs @@ -294,12 +294,26 @@ fn main() -> horizon_client::Result<()> { let types = MobTypes::load(&root)?; let animations = MobData::load_animations(&root); let mut out = String::new(); + let crystal = horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"); for line in fs::read_to_string(&args[1])?.lines() { let v: Value = serde_json::from_str(line)?; let layer = v["layer"] .as_str() .unwrap_or_default() .trim_start_matches("minecraft:"); + // EndCrystalModel is not a mob's: horizon_client::end_crystal poses it. + if layer == "end_crystal#main" + && let Some(model) = &crystal + { + let case = &v["case"]; + let mut poses = horizon_client::end_crystal::poses( + model, + case["ageInTicks"].as_f64().unwrap_or(0.0) as f32, + case["showsBottom"].as_bool().unwrap_or(false), + ); + out.push_str(&format!("{}\n", emit(model, &mut poses, case, layer))); + continue; + } let baby = layer.contains("_baby#"); let adult = layer.replace("_baby#", "#"); // Variant layers (sizes, hatless villagers, climate cows...) animate @@ -576,35 +590,38 @@ fn main() -> horizon_client::Result<()> { } _ => anim::setup(&mob, s, p, &animations), } - // The harness's part-scale override, set after setupAnim as the oracle does. - if let Some(scale) = case["@partScale"].as_array() { - let pose = poses.get(scale[0].as_str().unwrap_or_default()); - for i in 0..3 { - pose[6 + i] = scale[1 + i].as_f64().unwrap_or(1.0) as f32; - } - } - let mut parts = BTreeMap::new(); - walk(&model, "", &poses, &mut parts); - let mut emitted = Vec::new(); - render::draw( - &model, - root_transform(case), - &poses, - [0.0, 0.0, 1.0, 1.0], - 0xFFFF_FFFF, - 240 | 240 << 8, - 0, - &mut emitted, - ); - let mut vertices = BTreeMap::new(); - let mut cursor = 0; - drawn(&model, "", &poses, &emitted, &mut cursor, &mut vertices); - assert_eq!(cursor, emitted.len(), "{layer}: draw's walk changed"); - out.push_str(&format!( - "{}\n", - json!({"parts": parts, "vertices": vertices}) - )); + out.push_str(&format!("{}\n", emit(&model, &mut poses, case, layer))); } fs::write(&args[2], out)?; Ok(()) } + +/// Every part's pose, and the vertices drawn under the harness's root transform. +fn emit(model: &Part, poses: &mut Poses, case: &Value, layer: &str) -> Value { + // The harness's part-scale override, set after setupAnim as the oracle does. + if let Some(scale) = case["@partScale"].as_array() { + let pose = poses.get(scale[0].as_str().unwrap_or_default()); + for i in 0..3 { + pose[6 + i] = scale[1 + i].as_f64().unwrap_or(1.0) as f32; + } + } + let poses = &*poses; + let mut parts = BTreeMap::new(); + walk(model, "", poses, &mut parts); + let mut emitted = Vec::new(); + render::draw( + model, + root_transform(case), + poses, + [0.0, 0.0, 1.0, 1.0], + 0xFFFF_FFFF, + 240 | 240 << 8, + 0, + &mut emitted, + ); + let mut vertices = BTreeMap::new(); + let mut cursor = 0; + drawn(model, "", poses, &emitted, &mut cursor, &mut vertices); + assert_eq!(cursor, emitted.len(), "{layer}: draw's walk changed"); + json!({"parts": parts, "vertices": vertices}) +} diff --git a/crates/horizon-client/examples/hud_fixture.rs b/crates/horizon-client/examples/hud_fixture.rs index dcb594088..4a4c78869 100644 --- a/crates/horizon-client/examples/hud_fixture.rs +++ b/crates/horizon-client/examples/hud_fixture.rs @@ -93,8 +93,9 @@ fn encode(draws: &[GuiDraw]) -> Vec { h, region, color, + blend, } => { - json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32}) + json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32, "pipeline": blend.pipeline()}) } GuiDraw::AtlasSprite { sprite, @@ -190,7 +191,12 @@ fn decorations(c: &Value, atlas: &HudAtlas) -> Vec { // Spectators only see it over a spectatable target (none here). if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" { let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0)); - draws.extend(hud_layout::crosshair(w, h, attack, false)); + // crosshairPickEntity: absent, or a living entity alive or not. + let target = c["target"].as_bool(); + let full = attack.is_some_and(|a| { + hud_layout::full_attack_indicator(a, float("attackDelay", 5.0), target) + }); + draws.extend(hud_layout::crosshair(w, h, attack, full)); } if mode != "spectator" { let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial); diff --git a/crates/horizon-client/examples/mipmap_probe.rs b/crates/horizon-client/examples/mipmap_probe.rs new file mode 100644 index 000000000..0cdb9655f --- /dev/null +++ b/crates/horizon-client/examples/mipmap_probe.rs @@ -0,0 +1,54 @@ +//! Horizon's sprite mip levels for tools/test_mipmap_parity.py: each sprite +//! loads through `sprites::Sprites` (its .mcmeta settings and transparency) +//! and `mipmap::generate` makes its levels down to 1x1, printed as RGBA hex +//! rows like VanillaMipmapOracle. +use std::{fmt::Write as _, fs, path::Path}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let input = fs::read_to_string(&args[0])?; + let mut lines = input.lines(); + let root = Path::new(lines.next().ok_or("no resources root")?); + let names: Vec<&str> = lines.collect(); + let mut sprites = horizon_client::sprites::Sprites::default(); + let layers = names + .iter() + .map(|name| sprites.insert(root, name)) + .collect::>>()?; + sprites.finish(); + let size = sprites.size; + let bytes = (size * size * 4) as usize; + let mut out = String::new(); + for (name, layer) in names.iter().zip(layers) { + let start = layer as usize * bytes; + let base = horizon_client::mipmap::Image { + width: size, + height: size, + pixels: sprites.pixels[start..start + bytes] + .as_chunks::<4>() + .0 + .to_vec(), + }; + let s = sprites.mips[layer as usize]; + writeln!(out, "== {name}")?; + for mip in horizon_client::mipmap::generate( + base, + size.trailing_zeros(), + s.strategy, + s.alpha_cutoff_bias, + s.has_transparent, + s.item, + ) { + write!(out, "{}x{}", mip.width, mip.height)?; + for row in mip.pixels.chunks(mip.width as usize) { + out.push(' '); + for p in row { + write!(out, "{:02x}{:02x}{:02x}{:02x}", p[0], p[1], p[2], p[3])?; + } + } + out.push('\n'); + } + } + fs::write(&args[1], out)?; + Ok(()) +} diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index f90fbfc3e..1645bc01c 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -684,6 +684,7 @@ fn main() -> horizon_client::Result<()> { let assets = Assets::load(root)?; let registry = assets.registry; let facts = BlockFacts::load(root, registry)?; + let motion = horizon_client::motion::MotionResources::load(root, &assets)?; let data = MobData::load(root, &facts); let types = MobTypes::load(root)?; let biomes = Biomes::load(root)?; @@ -911,6 +912,7 @@ fn main() -> horizon_client::Result<()> { world: &world, registry, facts: &facts, + movement: &motion.blocks, collision: &collision, data: &data, player: player.clone(), diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs new file mode 100644 index 000000000..1520ee7ca --- /dev/null +++ b/crates/horizon-client/src/arrows.rs @@ -0,0 +1,1099 @@ +//! `AbstractArrow.tick` for arrows, tipped and spectral arrows: the flight with +//! its water inertia and bubbles, the base tick's fluids (currents, splash), +//! bubble columns and water along the path, sticking in blocks, falling out +//! when the block goes, and despawning. Entity hits and their effects stay +//! with the game (`projectile_hit`). +use crate::{ + blocks::BlockFacts, + collisions::SceneCollisions, + mobs::Who, + motion::{FluidResources, LAVA, WATER}, + projectiles::{Hit, Projectile}, + world::World, +}; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3, sweep_intersected_blocks}, + position::BlockPos, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::{ + block_collision::BlockCollisionRegistry, + entity_fluid::{ + CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership, + FluidSections, FluidTagId, + }, + entity_fluid_tick::{self, EntityFluidTickWorld}, + fluid::{FluidHeightWorld, FluidKind, FluidState}, + fluid_flow::{FluidFlowWorld, flow_at}, + registry::BlockStateId, + water_splash::{self, SplashParticle, WaterSplashWorld}, +}; +use std::{collections::HashSet, fmt}; + +/// `EntityType.ARROW` (and tipped/spectral arrows): 0.5 x 0.5, eyes at 0.13. +const WIDTH: f32 = 0.5; +const HEIGHT: f32 = 0.5; +const EYE_HEIGHT: f32 = 0.13; + +/// `AbstractArrow.Pickup`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Pickup { + #[default] + Disallowed, + Allowed, + CreativeOnly, +} +impl Pickup { + /// The saved `pickup` byte (`LEGACY_CODEC`: the ordinal, out of range is + /// DISALLOWED). + pub fn from_byte(b: i64) -> Self { + match b { + 1 => Self::Allowed, + 2 => Self::CreativeOnly, + _ => Self::Disallowed, + } + } + pub fn byte(self) -> i8 { + self as i8 + } +} +/// `DataComponents.INTANGIBLE_PROJECTILE`. +pub const INTANGIBLE: &str = "minecraft:intangible_projectile"; +/// `ProjectileWeaponItem.useAmmo`'s drawn stack: one of the ammo, marked +/// intangible when no ammo was used (creative, Infinity, multishot extras). +pub fn drawn_ammo(ammo: &crate::items::ItemStack, intangible: bool) -> crate::items::ItemStack { + let mut drawn = crate::items::ItemStack { + count: 1, + ..ammo.clone() + }; + if intangible { + drawn.data_mut().set_other( + INTANGIBLE, + Some(horizon_world::nbt::Tag::Compound(Default::default())), + ); + } + drawn +} +/// What `AbstractArrow.playerTouch` does for a player touching the arrow. +#[derive(Clone, Debug, PartialEq)] +pub enum Touch { + /// Not stuck yet, still shaking, or not the player's to take. + Ignore, + /// ALLOWED: taken if the inventory takes this stack whole. + Give(crate::items::ItemStack), + /// CREATIVE_ONLY in creative: taken without an item. + Take, +} +/// What an arrow's tick asks the game to play or show. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ArrowEvent { + /// `level().addParticle` (the client's copy of the arrow adds them). + Particle { + kind: ArrowParticle, + position: Vec3, + velocity: Vec3, + }, + Sound { + sound: ArrowSound, + volume: f32, + pitch: f32, + }, + /// `Entity.sendBubbleColumnParticles` at this block: two SPLASH (speed 1) + /// and two BUBBLE (spread 0, 0.01, 0, speed 0.2) particles at the top, + /// placed by the level random (drawn by the consumer, nothing else draws + /// it during an arrow's tick). + BubbleColumnParticles { + pos: BlockPos, + }, + /// The block hit reacts (before the arrow sticks). + Block { + pos: BlockPos, + reaction: BlockReaction, + }, + /// The SPLASH and PROJECTILE_SHOOT game events. + SplashEvent, + ShootEvent, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ArrowParticle { + Bubble, + Crit, + Splash, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ArrowSound { + /// `entity.generic.splash` (an arrow's splash and high-speed splash). + Splash, + /// The arrow's hit-ground sound (`entity.arrow.hit`). + HitGround, + /// `entity.generic.extinguish_fire`. + Extinguish, +} +/// What a burning arrow does to the block it hits (`onProjectileHit`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BlockReaction { + /// `TntBlock.prime` (primed TNT, its sound and PRIME_FUSE), then + /// `removeBlock(pos, false)`. + PrimeTnt, + /// `setBlock(pos, lit=true, 11)`: campfires and candles. + Light(BlockStateId), +} +/// The arrow part of `AbstractArrow` and its `Entity` state. +#[derive(Clone)] +pub struct ArrowState { + pub in_ground: bool, + pub in_ground_time: i32, + /// Ticks stuck (`life`): gone at 1200. + pub life: i32, + pub shake: i32, + /// The block it stuck in (`lastState`). + pub last_state: Option, + pub pickup: Pickup, + /// `pickupItemStack`: what picking the arrow up gives. + pub pickup_item: crate::items::ItemStack, + pub no_physics: bool, + pub pierce: u8, + /// `Entity.remainingFireTicks`. + pub fire_ticks: i32, + pub fall_distance: f64, + pub fluids: EntityFluidInteraction, + pub was_touching_water: bool, + pub was_eye_in_water: bool, + pub first_tick: bool, + pub has_been_shot: bool, + pub removed: bool, + /// The arrow's own random (`Entity.random`). + pub random: LegacyRandom, + pub events: Vec, +} +impl fmt::Debug for ArrowState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ArrowState") + .field("in_ground", &self.in_ground) + .field("life", &self.life) + .field("fire_ticks", &self.fire_ticks) + .finish_non_exhaustive() + } +} +impl PartialEq for ArrowState { + fn eq(&self, other: &Self) -> bool { + self.in_ground == other.in_ground + && self.life == other.life + && self.last_state == other.last_state + && self.fire_ticks == other.fire_ticks + } +} +impl ArrowState { + pub fn new(random: LegacyRandom) -> Self { + Self { + in_ground: false, + in_ground_time: 0, + life: 0, + shake: 0, + last_state: None, + pickup: Pickup::Disallowed, + pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1), + no_physics: false, + pierce: 0, + fire_ticks: 0, + fall_distance: 0.0, + fluids: EntityFluidInteraction::new([WATER, LAVA]), + was_touching_water: false, + was_eye_in_water: false, + first_tick: true, + has_been_shot: false, + removed: false, + random, + events: Vec::new(), + } + } + /// The `AbstractArrow` constructor's `pickupItemStack`: the drawn ammo + /// (one item). Ammo drawn without being used up (`INTANGIBLE_PROJECTILE`) + /// makes the arrow CREATIVE_ONLY; vanilla takes the component off the + /// stack it was given, not its copy, so the item keeps it. + pub fn set_item(&mut self, item: &crate::items::ItemStack) { + self.pickup_item = item.clone(); + if item.data().and_then(|d| d.other(INTANGIBLE)).is_some() { + self.pickup = Pickup::CreativeOnly; + } + } + /// `AbstractArrow.setOwner`: a player's arrows may be picked up. + pub fn set_owner(&mut self, owner: Option) { + if owner == Some(Who::Player) && self.pickup == Pickup::Disallowed { + self.pickup = Pickup::Allowed; + } + } + /// `AbstractArrow.playerTouch` and `tryPickup` (`creative`: + /// `Player.hasInfiniteMaterials`). Like vanilla it does not look at + /// removal: players only touch arrows still in the world. + pub fn player_touch(&self, creative: bool) -> Touch { + if !(self.in_ground || self.no_physics) || self.shake > 0 { + return Touch::Ignore; + } + match self.pickup { + Pickup::Disallowed => Touch::Ignore, + Pickup::Allowed => Touch::Give(self.pickup_item.clone()), + Pickup::CreativeOnly if creative => Touch::Take, + Pickup::CreativeOnly => Touch::Ignore, + } + } + /// `Entity.isOnFire` (arrows are not fire immune). + pub fn on_fire(&self) -> bool { + self.fire_ticks > 0 + } + /// `Entity.clearFire`. + pub fn clear_fire(&mut self) { + self.fire_ticks = self.fire_ticks.min(0); + } + /// `Entity.igniteForTicks` (an arrow never freezes). + pub fn ignite_for_ticks(&mut self, ticks: i32) { + if self.fire_ticks < ticks { + self.fire_ticks = ticks; + } + } + /// `Entity.igniteForSeconds`: Flame's `projectile_spawned` ignite. + pub fn ignite_for_seconds(&mut self, seconds: f32) { + self.ignite_for_ticks((seconds * 20.0).floor() as i32); + } + /// `BaseFireBlock.fireIgnite` for an entity that is not a player. + fn fire_ignite(&mut self) { + if self.fire_ticks < 0 { + self.fire_ticks += 1; + } + if self.fire_ticks >= 0 { + self.ignite_for_ticks(160); + } + } +} +/// The blocks, fluids and weather an arrow flies through. +pub struct ArrowScene<'a, 'r> { + pub world: &'a World, + pub registry: &'a horizon_world::registry::BlockRegistry, + pub facts: &'a BlockFacts, + pub collision: &'a BlockCollisionRegistry<'r>, + pub fluids: &'a FluidResources, + /// `Level.isRainingAt`. + pub raining: &'a dyn Fn(BlockPos) -> bool, + /// The `mob_griefing` and `tnt_explodes` game rules. + pub mob_griefing: bool, + pub tnt_explodes: bool, +} +impl ArrowScene<'_, '_> { + fn block(&self, p: BlockPos) -> BlockStateId { + self.world.block(p.x, p.y, p.z) + } + fn is_air(&self, state: BlockStateId) -> bool { + self.facts.is_air(state) + } + /// `BlockState.getCollisionShape(level, pos)` (an empty collision context). + fn collision_boxes(&self, state: BlockStateId, p: BlockPos) -> Vec { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + subject: None, + }; + self.collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .map(|s| s.boxes().to_vec()) + .unwrap_or_default() + } + fn property(&self, state: BlockStateId, name: &str) -> Option<&str> { + self.registry + .state(state)? + .properties + .get(name) + .map(String::as_str) + } + /// `ClipContext.Block.COLLIDER` with `Fluid.NONE`: the first block hit. + fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, BlockPos, [i32; 3])> { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + subject: None, + }; + let hit = horizon_core::geometry::traverse_blocks(from, to, 1024, |p: BlockPos| { + let state = self.block(p); + if self.is_air(state) { + return None; + } + let shape = self + .collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .ok()?; + shape.clip(from, to, p) + }); + let hit = hit.ok().flatten()?; + Some((hit.location, hit.block, hit.direction.normal())) + } + /// `CollisionGetter.noCollision(null, box)` over blocks. + fn no_block_collision(&self, b: Aabb) -> bool { + let (lo, hi) = (b.min_position(), b.max_position()); + for x in (lo.x.floor() as i32 - 1)..=(hi.x.floor() as i32 + 1) { + for y in (lo.y.floor() as i32 - 1)..=(hi.y.floor() as i32 + 1) { + for z in (lo.z.floor() as i32 - 1)..=(hi.z.floor() as i32 + 1) { + let p = BlockPos::new(x, y, z); + let state = self.block(p); + if self.is_air(state) { + continue; + } + let origin = Vec3::new(f64::from(x), f64::from(y), f64::from(z)); + if self + .collision_boxes(state, p) + .iter() + .any(|c| c.move_by(origin).intersects(b)) + { + return false; + } + } + } + } + true + } +} +fn bounds(at: Vec3) -> Aabb { + // EntityDimensions.makeBoundingBox: half the float width. + let w = f64::from(WIDTH / 2.0); + Aabb::new( + Vec3::new(at.x - w, at.y, at.z - w), + Vec3::new(at.x + w, at.y + f64::from(HEIGHT), at.z + w), + ) +} +/// `Projectile.lerpRotation`. +fn lerp_rotation(mut old: f32, new: f32) -> f32 { + while new - old < -180.0 { + old -= 360.0; + } + while new - old >= 180.0 { + old += 360.0; + } + old + 0.2 * (new - old) +} +/// `(float)(Mth.atan2(y, x) * 180.0F / (float)Math.PI)`: compiled as one +/// multiplication by the folded float constant. +fn degrees(y: f64, x: f64) -> f32 { + horizon_core::geometry::trig::atan2_degrees(y, x) +} +fn signum(v: f64) -> f64 { + if v > 0.0 { + 1.0 + } else if v < 0.0 { + -1.0 + } else { + v + } +} +/// One arrow tick: whether to keep it and what it hit. +pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) -> (bool, Hit) { + let Some(mut st) = p.arrow.take() else { + return (false, Hit::None); + }; + let hit = Ticker { + p, + st: &mut st, + scene, + } + .tick(targets); + p.stuck = st.in_ground; + let keep = !st.removed; + p.arrow = Some(st); + (keep, hit) +} +struct Ticker<'p, 's, 'a, 'r> { + p: &'p mut Projectile, + st: &'s mut ArrowState, + scene: &'s ArrowScene<'a, 'r>, +} +impl Ticker<'_, '_, '_, '_> { + fn position(&self) -> Vec3 { + self.p.position + } + fn block_position(&self) -> BlockPos { + BlockPos::containing(self.p.position) + } + /// `Entity.isInRain`: at the block position or the top of the box. + fn in_rain(&self) -> bool { + let p = self.block_position(); + (self.scene.raining)(p) + || (self.scene.raining)(BlockPos::new( + p.x, + bounds(self.p.position).max_position().y.floor() as i32, + p.z, + )) + } + fn tick(&mut self, targets: &[(Who, Aabb)]) -> Hit { + let physics = !self.st.no_physics; + let movement = self.p.velocity; + let block_pos = self.block_position(); + let state = self.scene.block(block_pos); + if !self.scene.is_air(state) && physics { + let origin = Vec3::new( + f64::from(block_pos.x), + f64::from(block_pos.y), + f64::from(block_pos.z), + ); + let at = self.position(); + if self + .scene + .collision_boxes(state, block_pos) + .iter() + .any(|b| b.move_by(origin).contains(at)) + { + self.p.velocity = Vec3::ZERO; + self.st.in_ground = true; + } + } + if self.st.shake > 0 { + self.st.shake -= 1; + } + if self.st.was_touching_water || self.in_rain() { + self.st.clear_fire(); + } + if self.st.in_ground && physics { + if self.st.last_state != Some(state) && self.should_fall() { + self.start_falling(); + } else { + // AbstractArrow.tickDespawn. + self.st.life += 1; + if self.st.life >= 1200 { + self.st.removed = true; + } + } + self.st.in_ground_time += 1; + if !self.st.removed { + let at = self.position(); + self.apply_effects_from_blocks(at, at); + } + return Hit::None; + } + self.st.in_ground_time = 0; + let original = self.position(); + if self.st.was_touching_water { + // getWaterInertia, then the bubbles behind it. + self.p.velocity = self.p.velocity.scale(f64::from(0.6f32)); + let v = self.p.velocity; + for _ in 0..4 { + self.st.events.push(ArrowEvent::Particle { + kind: ArrowParticle::Bubble, + position: Vec3::new( + original.x - v.x * 0.25, + original.y - v.y * 0.25, + original.z - v.z * 0.25, + ), + velocity: v, + }); + } + } + if self.p.critical() { + for i in 0..4 { + let f = f64::from(i) / 4.0; + self.st.events.push(ArrowEvent::Particle { + kind: ArrowParticle::Crit, + position: Vec3::new( + original.x + movement.x * f, + original.y + movement.y * f, + original.z + movement.z * f, + ), + velocity: Vec3::new(-movement.x, -movement.y + 0.2, -movement.z), + }); + } + } + let y_rot = if physics { + degrees(movement.x, movement.z) + } else { + degrees(-movement.x, -movement.z) + }; + let x_rot = degrees(movement.y, movement.horizontal_distance()); + self.p.pitch = lerp_rotation(self.p.pitch, x_rot); + self.p.yaw = lerp_rotation(self.p.yaw, y_rot); + self.check_left_owner(targets); + let mut hit = Hit::None; + let end = Vec3::new( + original.x + movement.x, + original.y + movement.y, + original.z + movement.z, + ); + if physics { + hit = self.step_move_and_hit(original, end, targets); + } else { + self.p.position = end; + self.apply_effects_from_blocks(original, end); + } + if !self.st.was_touching_water { + self.p.velocity = self.p.velocity.scale(f64::from(0.99f32)); + } + if physics && !self.st.in_ground { + // Entity.applyGravity: AbstractArrow.getDefaultGravity. + self.add_velocity(-0.05); + } + // Projectile.tick, then Entity.baseTick's fluid and fire phases. + if !self.st.has_been_shot { + self.st.events.push(ArrowEvent::ShootEvent); + self.st.has_been_shot = true; + } + self.st.was_eye_in_water = self.st.fluids.is_eye_in_fluid(&Tags, WATER); + let mut fluids = std::mem::take(&mut self.st.fluids); + let _ = entity_fluid_tick::update(&mut fluids, self, WATER, LAVA, 1_000_000); + self.st.fluids = fluids; + if self.st.fire_ticks > 0 { + self.st.fire_ticks -= 1; + } + if !self.st.first_tick && self.st.fluids.is_in_fluid(&Tags, LAVA) { + self.st.fall_distance *= 0.5; + } + if self.position().y < f64::from(crate::chunk::MIN_Y - 64) { + self.st.removed = true; + } + self.st.first_tick = false; + hit + } + /// `getDeltaMovement().add(0, y, 0)`: the zeros added to x and z also + /// turn a negative zero positive. + fn add_velocity(&mut self, y: f64) { + let v = self.p.velocity; + self.p.velocity = Vec3::new(v.x + 0.0, v.y + y, v.z + 0.0); + } + /// `Projectile.checkLeftOwner`: out of the owner's box once the arrow's + /// box, swept by its motion and grown by 1, no longer touches it. + fn check_left_owner(&mut self, targets: &[(Who, Aabb)]) { + if self.p.left_owner { + return; + } + let owner = targets + .iter() + .find(|(who, _)| Some(*who) == self.p.owner) + .map(|(_, b)| *b); + let swept = bounds(self.p.position) + .expand_towards(self.p.velocity) + .inflate(Vec3::new(1.0, 1.0, 1.0)); + self.p.left_owner = owner.is_none_or(|b| !swept.intersects(b)); + } + /// `AbstractArrow.shouldFall`. + fn should_fall(&self) -> bool { + let at = self.position(); + self.st.in_ground + && self + .scene + .no_block_collision(Aabb::new(at, at).inflate(Vec3::new(0.06, 0.06, 0.06))) + } + /// `AbstractArrow.startFalling`. + fn start_falling(&mut self) { + self.st.in_ground = false; + let v = self.p.velocity; + let x = f64::from(self.st.random.next_float() * 0.2); + let y = f64::from(self.st.random.next_float() * 0.2); + let z = f64::from(self.st.random.next_float() * 0.2); + self.p.velocity = Vec3::new(v.x * x, v.y * y, v.z * z); + self.st.life = 0; + } + /// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the + /// block (not piercing: the game removes an arrow that hits an entity). + fn step_move_and_hit(&mut self, from: Vec3, to: Vec3, targets: &[(Who, Aabb)]) -> Hit { + let block = self.scene.clip(from, to); + let end = block.map_or(to, |b| b.0); + let mut best: Option<(Who, Vec3, f64)> = None; + for (who, b) in targets { + if Some(*who) == self.p.owner && !self.p.left_owner { + continue; + } + if let Some(at) = b.inflate(Vec3::new(0.3, 0.3, 0.3)).clip(from, end) { + let c = b.center(); + let d = from.distance_squared(Vec3::new(c.x, b.min_position().y, c.z)); + if best.is_none_or(|bb| d < bb.2) { + best = Some((*who, at, d)); + } + } + } + let next = best.map_or(end, |b| b.1); + self.p.position = next; + self.apply_effects_from_blocks(from, next); + if let Some((who, at, _)) = best { + // The game hurts it; the arrow is spent (piercing is not modelled). + self.st.removed = true; + return Hit::Entity { who, at }; + } + let Some((at, pos, face)) = block else { + return Hit::None; + }; + if self.st.removed { + return Hit::None; + } + let state = self.scene.block(pos); + if self.scene.is_air(state) { + return Hit::None; + } + self.on_hit_block(pos, state); + Hit::Block { + pos: [pos.x, pos.y, pos.z], + at, + face, + } + } + /// `AbstractArrow.onHitBlock`: back off the face by 0.05 along each axis + /// it moved on, stop, and stick. + fn on_hit_block(&mut self, pos: BlockPos, state: BlockStateId) { + self.st.last_state = Some(state); + // Projectile.onHitBlock: BlockState.onProjectileHit. + if self.st.on_fire() + && let Some(reaction) = self.block_reaction(state) + { + self.st.events.push(ArrowEvent::Block { pos, reaction }); + } + let v = self.p.velocity; + let offset = f64::from(0.05f32); + self.p.position = Vec3::new( + self.p.position.x - signum(v.x) * offset, + self.p.position.y - signum(v.y) * offset, + self.p.position.z - signum(v.z) * offset, + ); + self.p.velocity = Vec3::ZERO; + let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9); + self.st.events.push(ArrowEvent::Sound { + sound: ArrowSound::HitGround, + volume: 1.0, + pitch, + }); + self.st.in_ground = true; + self.st.shake = 7; + self.p.set_critical(false); + self.st.pierce = 0; + } + /// `Projectile.mayInteract`: a mob's arrows need `mob_griefing`. + fn may_interact(&self) -> bool { + !matches!(self.p.owner, Some(Who::Mob(_))) || self.scene.mob_griefing + } + /// `onProjectileHit` of the blocks a burning projectile lights. + fn block_reaction(&self, state: BlockStateId) -> Option { + let name = self.scene.registry.state(state)?.name.as_str(); + let flag = |key: &str| self.scene.property(state, key) == Some("true"); + let lit = || { + let mut definition = self.scene.registry.state(state)?.clone(); + definition.properties.insert("lit".into(), "true".into()); + self.scene.registry.id(&definition) + }; + match name { + "minecraft:tnt" if self.may_interact() && self.scene.tnt_explodes => { + Some(BlockReaction::PrimeTnt) + } + "minecraft:campfire" | "minecraft:soul_campfire" + if self.may_interact() && !flag("lit") && !flag("waterlogged") => + { + lit().map(BlockReaction::Light) + } + // AbstractCandleBlock: candles also must be dry (CandleBlock.canBeLit). + _ if name.ends_with("candle_cake") && !flag("lit") => lit().map(BlockReaction::Light), + _ if name.ends_with("candle") && !flag("lit") && !flag("waterlogged") => { + lit().map(BlockReaction::Light) + } + _ => None, + } + } + /// `Entity.applyEffectsFromBlocks(from, to)` for an arrow: the blocks and + /// fluids its box passes through (bubble columns push, water puts the fire + /// out), then rain. + fn apply_effects_from_blocks(&mut self, from: Vec3, to: Vec3) { + // Entity.isAffectedByBlocks. + if self.st.removed || self.st.no_physics { + return; + } + let was_on_fire = self.st.on_fire(); + let previous_fire = self.st.fire_ticks; + let mut visited = HashSet::new(); + let mut effects = Collector::default(); + let used = self.check_inside_blocks(from, to, &mut visited, &mut effects, 16); + if 16 - used <= 0 { + self.check_inside_blocks(to, to, &mut visited, &mut effects, 1); + } + // StepBasedCollector.applyAndClear. + for effect in effects.finish() { + if self.st.removed { + break; + } + match effect { + Effect::ClearFreeze => {} + Effect::FireIgnite => self.st.fire_ignite(), + Effect::LavaIgnite => self.st.ignite_for_ticks(300), + Effect::Extinguish => self.st.clear_fire(), + } + } + if self.in_rain() { + self.st.clear_fire(); + } + if was_on_fire && !self.st.on_fire() { + // Entity.playEntityOnFireExtinguishedSound. + let pitch = 1.6 + (self.st.random.next_float() - self.st.random.next_float()) * 0.4; + self.st.events.push(ArrowEvent::Sound { + sound: ArrowSound::Extinguish, + volume: 0.7, + pitch, + }); + } + let ignited = self.st.fire_ticks > previous_fire; + if !self.st.on_fire() && !ignited { + // -getFireImmuneTicks(): 0 for arrows. + self.st.fire_ticks = 0; + } + } + /// `Entity.checkInsideBlocks(from, to, ...)`: returns the iterations used. + fn check_inside_blocks( + &mut self, + from: Vec3, + to: Vec3, + visited: &mut HashSet, + effects: &mut Collector, + max_iterations: i32, + ) -> i32 { + let deflated = bounds(to).deflate(Vec3::new( + f64::from(1.0e-5f32), + f64::from(1.0e-5f32), + f64::from(1.0e-5f32), + )); + let far = from.distance_squared(to) > 0.999_990_000_000_252_6f64 * 0.999_990_000_000_252_6; + let mut hits = Vec::new(); + let mut iterations = 0; + let alive = !self.st.removed; + let _ = sweep_intersected_blocks(from, to, deflated, 1_000_000, |p, iteration| { + if !alive || iteration >= max_iterations { + return false; + } + iterations = iteration; + hits.push((p, iteration)); + true + }); + for (p, step) in hits { + let state = self.scene.block(p); + if self.scene.is_air(state) { + continue; + } + // getEntityInsideCollisionShape: the whole block for these. + let inside_block = true; + let fluid = self.scene.fluids.fluid(state); + let inside_fluid = self.collided_with_fluid(fluid, p, from, to); + if !(inside_block || inside_fluid) || !visited.insert(p) { + continue; + } + effects.advance(step); + let name = &*self.scene.facts.get(state).name; + if matches!(name, "minecraft:fire" | "minecraft:soul_fire") { + // BaseFireBlock.entityInside (its inFire hurt does nothing to arrows). + effects.apply(Effect::ClearFreeze); + effects.apply(Effect::FireIgnite); + } + if name == "minecraft:bubble_column" { + let precise = far + || deflated.intersects(Aabb::new( + Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)), + Vec3::new(f64::from(p.x + 1), f64::from(p.y + 1), f64::from(p.z + 1)), + )); + if precise { + self.bubble_column(state, p); + } + } + if inside_fluid { + effects.advance(step); + match fluid.kind() { + // WaterFluid.entityInside. + FluidKind::Water | FluidKind::FlowingWater => effects.apply(Effect::Extinguish), + // LavaFluid.entityInside (lavaHurt does nothing to arrows). + FluidKind::Lava | FluidKind::FlowingLava => { + effects.apply(Effect::ClearFreeze); + effects.apply(Effect::LavaIgnite); + } + FluidKind::Empty => {} + } + } + } + iterations + 1 + } + /// `Entity.collidedWithFluid`: the fluid's box swept from `from` to `to`. + fn collided_with_fluid( + &mut self, + fluid: FluidState, + p: BlockPos, + from: Vec3, + to: Vec3, + ) -> bool { + if fluid.kind() == FluidKind::Empty { + return false; + } + let Ok(height) = fluid.height_at(self, [p.x, p.y, p.z]) else { + return false; + }; + let b = Aabb::new( + Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)), + Vec3::new( + f64::from(p.x) + 1.0, + f64::from(p.y) + f64::from(height), + f64::from(p.z) + 1.0, + ), + ); + bounds(from).collided_along_vector(to.subtract(from), &[b]) + } + /// `BubbleColumnBlock.entityInside` with `Projectile`'s pushes. + fn bubble_column(&mut self, state: BlockStateId, p: BlockPos) { + let drag = self.scene.property(state, "drag") == Some("true"); + let above = self.scene.block(BlockPos::new(p.x, p.y + 1, p.z)); + // The state above's collision shape, queried at this position. + let nothing_above = self.scene.collision_boxes(above, p).is_empty() + && self.scene.fluids.fluid(above).kind() == FluidKind::Empty; + if self.st.in_ground { + return; + } + if nothing_above { + self.add_velocity(if drag { -0.03 } else { 0.1 }); + self.st + .events + .push(ArrowEvent::BubbleColumnParticles { pos: p }); + } else { + self.add_velocity(if drag { -0.03 } else { 0.06 }); + self.st.fall_distance = 0.0; + } + } +} +/// `InsideBlockEffectType`s an arrow meets, in their apply order (FREEZE +/// needs powder snow, which an arrow's collision context passes through). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Effect { + ClearFreeze, + FireIgnite, + LavaIgnite, + Extinguish, +} +const EFFECT_ORDER: [Effect; 4] = [ + Effect::ClearFreeze, + Effect::FireIgnite, + Effect::LavaIgnite, + Effect::Extinguish, +]; +/// `InsideBlockEffectApplier.StepBasedCollector`: each step's effects once, +/// in type order, steps in the order they were reached. +struct Collector { + last_step: i32, + step: [bool; 4], + effects: Vec, +} +impl Default for Collector { + fn default() -> Self { + Self { + last_step: -1, + step: [false; 4], + effects: Vec::new(), + } + } +} +impl Collector { + fn advance(&mut self, step: i32) { + if self.last_step != step { + self.last_step = step; + self.flush(); + } + } + fn apply(&mut self, effect: Effect) { + self.step[effect as usize] = true; + } + fn flush(&mut self) { + for effect in EFFECT_ORDER { + if std::mem::take(&mut self.step[effect as usize]) { + self.effects.push(effect); + } + } + } + fn finish(mut self) -> Vec { + self.flush(); + self.effects + } +} +struct Tags; +impl FluidMembership for Tags { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + if tag == WATER { + matches!(kind, FluidKind::Water | FluidKind::FlowingWater) + } else { + matches!(kind, FluidKind::Lava | FluidKind::FlowingLava) + } + } +} +type Error = Box; +impl FluidMembership for Ticker<'_, '_, '_, '_> { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + Tags.fluid_in_tag(kind, tag) + } +} +impl CurrentTarget for Ticker<'_, '_, '_, '_> { + type Error = Error; + fn is_player_class(&self) -> bool { + false + } + fn velocity(&mut self) -> Result { + Ok(self.p.velocity) + } + fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Error> { + let v = self.p.velocity; + let sum = Vec3::new(v.x + delta.x, v.y + delta.y, v.z + delta.z); + if delta.is_finite() && sum.is_finite() { + self.p.velocity = sum; + } + Ok(()) + } +} +impl FluidInteractionWorld for Ticker<'_, '_, '_, '_> { + type Error = Error; + type Chunk = (); + fn interaction_box(&mut self) -> Result, Error> { + Ok(Some( + bounds(self.p.position).deflate(Vec3::new(0.001, 0.001, 0.001)), + )) + } + fn loaded_chunk(&mut self, x: i32, z: i32) -> Result, Error> { + Ok(self.scene.world.chunks.contains_key(&(x, z)).then_some(())) + } + fn chunk_sections(&mut self, _: ()) -> Result, Error> { + static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS]; + Ok(FluidSections { + minimum_section_y: crate::chunk::MIN_Y >> 4, + has_fluid: &SECTIONS, + }) + } + fn bounding_box_min_y(&self) -> f64 { + self.p.position.y + } + fn block_x(&self) -> i32 { + self.p.position.x.floor() as i32 + } + fn eye_y(&mut self) -> Result { + Ok(self.p.position.y + f64::from(EYE_HEIGHT)) + } + fn block_z(&self) -> i32 { + self.p.position.z.floor() as i32 + } + fn fluid_state(&mut self, p: BlockPos) -> Result { + Ok(self.scene.fluids.fluid(self.scene.block(p))) + } + fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.height_at(self, [p.x, p.y, p.z]) + } + fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.camera_height_at(self, [p.x, p.y, p.z]) + } + fn flow(&mut self, f: FluidState, p: BlockPos) -> Result { + flow_at(self, f, p) + } +} +impl EntityFluidTickWorld for Ticker<'_, '_, '_, '_> { + /// `AbstractArrow.isPushedByFluid`: not when stuck. + fn is_pushed_by_fluid(&mut self) -> Result { + Ok(!self.st.in_ground) + } + fn reset_fall_distance(&mut self) -> Result<(), Error> { + self.st.fall_distance = 0.0; + Ok(()) + } + fn was_touching_water(&self) -> bool { + self.st.was_touching_water + } + fn first_tick(&self) -> bool { + self.st.first_tick + } + fn water_splash(&mut self) -> Result<(), Error> { + water_splash::water_splash(self, 1_000_000).map_err(|e| e.to_string())?; + Ok(()) + } + fn set_was_touching_water(&mut self, value: bool) { + self.st.was_touching_water = value; + } + fn fast_lava(&mut self) -> Result { + Ok(false) + } +} +impl FluidHeightWorld for Ticker<'_, '_, '_, '_> { + type Error = Error; + fn fluid(&mut self, p: [i32; 3]) -> Result { + Ok(self + .scene + .fluids + .fluid(self.scene.block(BlockPos::new(p[0], p[1], p[2])))) + } + fn sturdy_down(&mut self, p: [i32; 3]) -> Result { + let state = self.scene.block(BlockPos::new(p[0], p[1], p[2])); + Ok(self.scene.fluids.sturdy(state, Direction::Down)) + } +} +impl FluidFlowWorld for Ticker<'_, '_, '_, '_> { + type Error = Error; + type Block = BlockStateId; + fn fluid(&mut self, p: BlockPos) -> Result { + Ok(self.scene.fluids.fluid(self.scene.block(p))) + } + fn block(&mut self, p: BlockPos) -> Result { + Ok(self.scene.block(p)) + } + fn blocks_fluid_flow(&self, s: BlockStateId) -> bool { + self.scene.fluids.blocks_flow(s) + } + fn is_ice_class(&self, s: BlockStateId) -> bool { + self.scene.fluids.ice(s) + } + fn is_face_sturdy( + &mut self, + s: BlockStateId, + _: BlockPos, + d: Direction, + ) -> Result { + Ok(self.scene.fluids.sturdy(s, d)) + } +} +/// `Entity.doWaterSplashEffect` with the arrow's own random. +impl WaterSplashWorld for Ticker<'_, '_, '_, '_> { + type Error = Error; + type Entity = (); + type Sound = (); + fn this_entity(&self) {} + fn controlling_passenger(&mut self) -> Result, Error> { + Ok(None) + } + fn velocity(&mut self, _: ()) -> Result { + Ok(self.p.velocity) + } + fn splash_sound(&mut self, _: bool) -> Result<(), Error> { + Ok(()) + } + fn random_float(&mut self) -> Result { + Ok(self.st.random.next_float()) + } + fn random_double(&mut self) -> Result { + Ok(self.st.random.next_double()) + } + fn play_sound(&mut self, _: (), volume: f32, pitch: f32) -> Result<(), Error> { + self.st.events.push(ArrowEvent::Sound { + sound: ArrowSound::Splash, + volume, + pitch, + }); + Ok(()) + } + fn position(&self) -> Vec3 { + self.p.position + } + fn width(&self) -> f32 { + WIDTH + } + fn particle( + &mut self, + kind: SplashParticle, + position: Vec3, + velocity: Vec3, + ) -> Result<(), Error> { + self.st.events.push(ArrowEvent::Particle { + kind: match kind { + SplashParticle::Bubble => ArrowParticle::Bubble, + SplashParticle::Splash => ArrowParticle::Splash, + }, + position, + velocity, + }); + Ok(()) + } + fn splash_event(&mut self) -> Result<(), Error> { + self.st.events.push(ArrowEvent::SplashEvent); + Ok(()) + } +} diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index 4be39eac5..67914a780 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -64,6 +64,8 @@ pub struct Assets { pub animations: Vec, pub sprite_layers: std::collections::BTreeMap, pub translucent_layers: Vec, + /// Each layer's `MipmapGenerator` settings. + pub sprite_mips: Vec, /// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors). pub blocks_fluid_flow: BTreeSet, } @@ -248,6 +250,7 @@ impl Assets { animations: sprites.animations, sprite_layers: sprites.layers, translucent_layers: sprites.translucent, + sprite_mips: sprites.mips, blocks_fluid_flow, }) } diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 1e0d70d5a..6705235ae 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -617,6 +617,18 @@ impl Audio { let seed = self.random.next_long(); self.play_seeded(event, at, volume, pitch, seed); } + /// `AbstractWidget.playButtonClickSound`: an unseeded, relative UI sound. + pub fn play_button_click(&mut self) { + self.play_instance( + SoundInstance::for_ui( + "minecraft:ui.button.click", + 1.0, + 0.25, + SoundEngine::unseeded(), + ), + false, + ); + } /// `play` with the seed a sound packet carries. pub fn play_seeded( &mut self, @@ -749,6 +761,38 @@ impl Sounds for Audio { mod tests { use super::*; + #[test] + fn button_click_uses_vanilla_ui_parameters_without_advancing_world_random() { + let mut audio = Audio::silent(Path::new("/nonexistent/horizon-test-assets")); + audio.engine.registry.add_file( + "minecraft", + br#"{"ui.button.click":{"sounds":["gui/button"]}}"#, + &|_, _| true, + ); + // Exercise the mixer without opening an output device. The missing + // sample is harmless: this test checks the source the engine creates. + audio.engine.loaded = true; + audio.backend.live = true; + let mut random = audio.random.clone(); + audio.play_button_click(); + let instance = audio.engine.instance(1).expect("click reached the engine"); + assert_eq!(instance.identifier, "minecraft:ui.button.click"); + assert_eq!(instance.source, crate::sound_engine::UI); + assert_eq!(instance.volume, 0.25); + assert_eq!(instance.pitch, 1.0); + assert_eq!(instance.attenuation, Attenuation::None); + assert_eq!(instance.position, [0.0; 3]); + assert!(instance.relative); + assert!(!instance.looping); + assert_eq!(audio.random.next_long(), random.next_long()); + audio.pause(); + assert_eq!( + audio.backend.mixer.lock().unwrap().channels[&1].state, + State::Initial + ); + audio.stop_all(); + } + fn channel(samples: Vec, linear: Option, at: [f32; 3], looping: bool) -> Channel { Channel { samples: Some((Arc::new(samples), 48_000)), diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 74f4d4fcf..407b0dd69 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -9,9 +9,13 @@ use crate::{ hud::{HudAtlas, HudBatch}, hud_layout::{self, GuiDraw, PoseOp}, screen_draw::{self as d, Draw, Measure, TextField}, - text::{self, Style, Text}, + text::{self, ClickEvent, Style, Text}, }; +#[cfg(test)] +#[path = "chat_tests.rs"] +mod tests; + /// GuiMessageTag.systemSinglePlayer's indicator colour. pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0; @@ -293,6 +297,35 @@ impl Chat { let draws = self.layout(batch.height as i32, ticks, focused); hud_layout::paint(batch, atlas, &draws); } + /// The click action under a GUI-space cursor while chat is focused. + pub fn click_at( + &self, + font: &crate::font::Font, + height: i32, + x: f64, + y: f64, + ) -> Option { + let scale = self.options.scale as f32; + let mut x = x / f64::from(scale) - 4.0; + let bottom = hud_layout::floor((height - 40) as f32 / scale); + let from_bottom = f64::from(bottom) - y / f64::from(scale); + if x < 0.0 || x >= f64::from(self.max_width()) || from_bottom <= 0.0 { + return None; + } + let row = (from_bottom / f64::from(self.options.line_height())).ceil() as usize - 1; + if row >= self.lines_per_page(true) { + return None; + } + let line = self.lines.get(self.scroll + row)?; + let content = line.content.resolve_legacy(); + for (c, style) in content.chars() { + x -= f64::from(font.advance(c, style)); + if x < 0.0 { + return style.click.clone(); + } + } + None + } /// Plain text of the newest messages (for tests and the control socket). pub fn recent_lines(&self, n: usize) -> Vec { self.messages @@ -420,6 +453,11 @@ impl ChatScreen { pub fn value(&self) -> &str { &self.input.value } + /// Replace the input for a suggest-command link and refresh completions. + pub fn suggest_command(&mut self, m: &Measure, c: &Commands, command: &str) { + self.input.set_value(m, command); + self.edited(m, c); + } /// `ChatScreen.resize`: a new screen with the current text. pub fn resize(&mut self, m: &Measure, c: &Commands, width: i32, height: i32) { if (width, height) != (self.width, self.height) { diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs new file mode 100644 index 000000000..dd6192edd --- /dev/null +++ b/crates/horizon-client/src/chat_tests.rs @@ -0,0 +1,165 @@ +use super::*; +use crate::{font::Font, hud::Rect}; +use std::{collections::HashMap, path::Path}; + +fn font() -> Font { + // The missing-glyph metrics let these tests run without game assets. + Font::load( + Path::new("/nonexistent-horizon-chat-test-resources"), + &HashMap::new(), + &[], + (1, 1), + (0, 0), + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 1, + h: 1, + }, + ) +} + +fn add(chat: &mut Chat, font: &Font, content: Text) { + for content in font.wrap_components(&content, chat.max_width()) { + chat.lines.insert( + 0, + Line { + added: 0, + content, + indicator: None, + }, + ); + } +} + +#[test] +fn clicking_seed_copies_the_raw_value_only_inside_the_link() { + let font = font(); + for seed in [1, -42, i64::MIN, i64::MAX] { + let mut chat = Chat::default(); + let seed_text = Text::copyable(seed.to_string()).with_color(text::GOLD); + assert_eq!(seed_text.plain(), format!("[{seed}]")); + assert_eq!(seed_text.spans[0].style.color, Some(text::GOLD)); + assert_eq!(seed_text.spans[1].style.color, Some(text::GREEN)); + assert_eq!(seed_text.spans[2].style.color, Some(text::GOLD)); + add(&mut chat, &font, Text::literal("Seed: ").append(seed_text)); + let expected = Some(ClickEvent::CopyToClipboard(seed.to_string())); + let start = 4.0 + f64::from(font.width("Seed: [")); + let end = start + f64::from(font.width(&seed.to_string())); + assert_eq!(chat.click_at(&font, 360, start, 315.0), expected); + assert_eq!(chat.click_at(&font, 360, end - 0.5, 315.0), expected); + for (x, y) in [ + (start - 0.5, 315.0), + (end, 315.0), + (3.0, 315.0), + (start, 320.0), + (start, 310.0), + ] { + assert_eq!(chat.click_at(&font, 360, x, y), None, "{x}, {y}"); + } + } +} + +#[test] +fn click_targets_match_rendered_spans_when_scaled_wrapped_and_scrolled() { + let font = font(); + let screenshot = ClickEvent::OpenFile("/tmp/My screenshots/世界.png".into()); + for scale in [0.5, 0.75, 1.0] { + for line_spacing in [0.0, 0.5, 1.0] { + let mut chat = Chat::default(); + chat.options.scale = scale; + chat.options.width = 0.0; + chat.options.line_spacing = line_spacing; + for _ in 0..20 { + add( + &mut chat, + &font, + Text::literal("Saved screenshot as ").append(Text::styled( + "2026-10-14_18.55.14.png", + Style { + click: Some(screenshot.clone()), + bold: Some(true), + underlined: Some(true), + ..Style::default() + }, + )), + ); + } + for scroll in [0, 3, 12] { + chat.scroll = scroll; + let mut links = 0; + for draw in chat.layout(361, 0, true) { + if let GuiDraw::Text { text, x, y, .. } = draw { + let mut at = x as f64; + for (c, style) in text.chars() { + let width = f64::from(font.advance(c, style)); + let cursor_x = (4.0 + at + width / 2.0) * scale; + let cursor_y = (y as f64 + 3.0) * scale; + assert_eq!( + chat.click_at(&font, 361, cursor_x, cursor_y), + style.click, + "scale={scale}, spacing={line_spacing}, scroll={scroll}, char={c}" + ); + links += usize::from(style.click.is_some()); + at += width; + } + } + } + assert!(links > 0); + // The history above the focused viewport is not clickable. + let top = ((361 - 40) as f64 / scale).floor() + - chat.lines_per_page(true) as f64 * chat.options.line_height() as f64; + assert_eq!( + chat.click_at(&font, 361, 10.0 * scale, (top - 1.0) * scale), + None + ); + } + } + } +} + +#[test] +fn locate_coordinates_fill_chat_with_teleport_without_submitting() { + let font = font(); + let m = Measure(&font); + let registries = Registries::default(); + let commands = Commands { + dispatcher: crate::command::vanilla::game_dispatcher(), + registries: ®istries, + }; + // Structures and POIs use relative Y; biome results include absolute Y. + for (y, expected) in [ + (None, "/tp @s -1136 ~ 848"), + (Some(73), "/tp @s -1136 73 848"), + ] { + let link = Text::teleport_link(-1136, y, 848); + assert_eq!(link.component()["click_event"]["action"], "suggest_command"); + assert_eq!(link.component()["click_event"]["command"], expected); + let mut chat = Chat::default(); + add(&mut chat, &font, Text::literal("Found at ").append(link)); + let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360); + let x = 4.0 + f64::from(font.width("Found at ")); + assert!(!screen.click(&m, &commands, x, 315.0)); + let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else { + panic!("locate coordinates must suggest a command"); + }; + screen.suggest_command(&m, &commands, &command); + assert_eq!(screen.value(), expected); + assert_eq!(screen.input.cursor, expected.chars().count()); + assert_eq!(screen.input.highlight, screen.input.cursor); + // Submission is a separate, explicit Enter press. + assert_eq!( + screen.key( + &m, + &commands, + &[], + winit::keyboard::KeyCode::Enter, + false, + false + ), + ChatAction::Submit(expected.to_owned()) + ); + } +} diff --git a/crates/horizon-client/src/end_crystal.rs b/crates/horizon-client/src/end_crystal.rs new file mode 100644 index 000000000..037ccf6b1 --- /dev/null +++ b/crates/horizon-client/src/end_crystal.rs @@ -0,0 +1,38 @@ +//! `EndCrystalRenderer` and `EndCrystalModel.setupAnim`: the crystal's bob +//! and the poses of its base, glass and cube. +use crate::mobs::{Part, anim::Poses}; +use horizon_core::geometry::trig::Mth; + +/// `EndCrystalRenderer.getY`: the crystal's bob below its resting height. +pub fn y(age: f32) -> f32 { + let hh = (age * 0.2).msin() / 2.0 + 0.5; + (hh * hh + hh) * 0.4 - 1.4 +} + +/// `EndCrystalModel.setupAnim`: the base shown or not, the glass raised by +/// half the bob (in model pixels) and the three cubes turned with +/// `ModelPart.rotateBy`, which stores the composed rotation as ZYX angles. +pub fn poses(model: &Part, age: f32, show_bottom: bool) -> Poses { + let mut poses = Poses::new(model); + poses.visible("base", show_bottom); + let speed = age * 3.0; + let sin45 = std::f32::consts::FRAC_PI_4.sin(); + let tilt = glam::Quat::from_axis_angle( + glam::Vec3::new(sin45, 0.0, sin45), + std::f32::consts::FRAC_PI_3, + ); + let spin = glam::Quat::from_rotation_y(speed.to_radians()); + poses.get("outer_glass")[1] += y(age) * 16.0 / 2.0; + for (part, rotation) in [ + ("outer_glass", spin * tilt), + ("inner_glass", tilt * spin), + ("cube", tilt * spin), + ] { + let (z, y, x) = rotation.to_euler(glam::EulerRot::ZYX); + let pose = poses.get(part); + pose[3] = x; + pose[4] = y; + pose[5] = z; + } + poses +} diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index ede53244c..a1e18076e 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -175,80 +175,6 @@ impl ItemEntity { self.age < 6000 && self.position.y > -128.0 } } -/// Arrows (`AbstractArrow.tick`): 0.99 drag, 0.05 gravity, sticking in blocks. -#[derive(Clone, Debug)] -pub struct Arrow { - /// Shot by the player (hits mobs) rather than a mob (hits the player). - pub from_player: bool, - pub critical: bool, - pub position: Vec3, - pub previous: Vec3, - pub velocity: Vec3, - pub stuck: bool, - pub age: u32, - pub base_damage: f64, -} -pub enum ArrowHit { - None, - Player(f32), -} -impl Arrow { - pub fn tick( - &mut self, - world: &World, - facts: &BlockFacts, - player: Option, - ) -> (bool, ArrowHit) { - self.previous = self.position; - self.age += 1; - if self.stuck { - return (self.age < 1200, ArrowHit::None); - } - let steps = 4; - for _ in 0..steps { - let next = Vec3::new( - self.position.x + self.velocity.x / f64::from(steps), - self.position.y + self.velocity.y / f64::from(steps), - self.position.z + self.velocity.z / f64::from(steps), - ); - if let Some(b) = player { - let (min, max) = (b.min_position(), b.max_position()); - if next.x >= min.x - && next.x <= max.x - && next.y >= min.y - && next.y <= max.y - && next.z >= min.z - && next.z <= max.z - { - let speed = (self.velocity.x.powi(2) - + self.velocity.y.powi(2) - + self.velocity.z.powi(2)) - .sqrt(); - // AbstractArrow.onHitEntity: ceil(speed * baseDamage). - let damage = (speed * self.base_damage).ceil().max(0.0) as f32; - return (false, ArrowHit::Player(damage)); - } - } - let block = world.block( - next.x.floor() as i32, - next.y.floor() as i32, - next.z.floor() as i32, - ); - if facts.get(block).full_collision { - self.stuck = true; - self.age = 0; - return (true, ArrowHit::None); - } - self.position = next; - } - self.velocity = Vec3::new( - self.velocity.x * 0.99, - self.velocity.y * 0.99 - 0.05, - self.velocity.z * 0.99, - ); - (self.position.y > -128.0 && self.age < 1200, ArrowHit::None) - } -} /// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks. #[derive(Clone, Debug)] pub struct ExperienceOrb { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 95f293295..8428a9410 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -5,8 +5,10 @@ //! Horizon does not model (variants, attributes, equipment, custom names) //! survive a Horizon save. use crate::{ - entities::{ArmorStand, Arrow, ExperienceOrb, ItemEntity, ItemFrame, Painting}, - mobs::{Mob, MobType}, + arrows::Pickup, + entities::{ArmorStand, ExperienceOrb, ItemEntity, ItemFrame, Painting}, + mobs::{Mob, MobType, Who}, + projectiles::{Projectile, ProjectileKind}, save::{ doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, uuid_from_tag, @@ -180,14 +182,11 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } match id { "minecraft:creeper" => { - for (key, value) in [ - ("Fuse", Tag::Short(30)), - ("ExplosionRadius", Tag::Byte(3)), - ("ignited", Tag::Byte(0)), - ] { + for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] { map.entry(key.into()).or_insert(value); } map.insert("powered".into(), Tag::Byte(i8::from(m.extra.charged))); + map.insert("ignited".into(), Tag::Byte(i8::from(m.extra.flag))); } "minecraft:cat" => { if let Some(owner) = m.extra.owner { @@ -615,6 +614,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.invulnerable_flag = flag(tag, "Invulnerable"); if m.species() == crate::mobs::Species::Creeper { m.extra.charged = flag(tag, "powered"); + // Creeper.readAdditionalSaveData: `ignited` lights the fuse. + m.extra.flag = flag(tag, "ignited"); } if matches!( m.species(), @@ -928,68 +929,102 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec { vec![orb; count] } -/// `AbstractArrow`: damage, crit, inGround, life, pickup, item. -pub fn arrow_to_nbt(a: &Arrow, uuid: [i32; 4], owner: Option<[i32; 4]>) -> Tag { - let v = a.velocity; - let horizontal = (v.x * v.x + v.z * v.z).sqrt(); - let rotation = [ - (v.x.atan2(v.z).to_degrees()) as f32, - (v.y.atan2(horizontal).to_degrees()) as f32, - ]; +/// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow; +/// `in_block` is its `inBlockState`, `raw` the compound it was loaded with. +pub fn arrow_to_nbt( + p: &Projectile, + uuid: [i32; 4], + owner: Option<[i32; 4]>, + in_block: Option, + raw: Option<&Tag>, +) -> Option { + let a = p.arrow.as_deref()?; + let ProjectileKind::Arrow { + base_damage, + critical, + .. + } = p.kind + else { + return None; + }; let base = Base { id: "minecraft:arrow", uuid, - position: a.position, - motion: a.velocity, - rotation, + position: p.position, + motion: p.velocity, + rotation: [p.yaw, p.pitch], on_ground: false, - fall_distance: 0.0, + fall_distance: a.fall_distance, }; - let mut tag = base.tag(None); + let mut tag = base.tag(raw); for (key, value) in [ - ("damage", Tag::Double(a.base_damage.to_bits())), - ("crit", Tag::Byte(i8::from(a.critical))), - ("inGround", Tag::Byte(i8::from(a.stuck))), - ( - "life", - Tag::Short(if a.stuck { a.age.min(1200) as i16 } else { 0 }), - ), - // Pickup: allowed for the player's arrows, disallowed for mobs'. - ("pickup", Tag::Byte(i8::from(a.from_player))), - ("shake", Tag::Byte(0)), - ("PierceLevel", Tag::Byte(0)), - ("HasBeenShot", Tag::Byte(1)), - ("SoundEvent", string("minecraft:entity.arrow.hit")), - ( - "item", - Tag::compound([("id", string("minecraft:arrow")), ("count", Tag::Int(1))]), - ), + ("Fire", Tag::Short(a.fire_ticks as i16)), + ("life", Tag::Short(a.life as i16)), + ("shake", Tag::Byte(a.shake as i8)), + ("inGround", Tag::Byte(i8::from(a.in_ground))), + ("pickup", Tag::Byte(a.pickup.byte())), + ("damage", Tag::Double(base_damage.to_bits())), + ("crit", Tag::Byte(i8::from(critical))), + ("PierceLevel", Tag::Byte(a.pierce as i8)), + ("HasBeenShot", Tag::Byte(i8::from(a.has_been_shot))), + ("item", item_to_nbt(&a.pickup_item)), ] { put(&mut tag, key, value); } + if let Tag::Compound(map) = &mut tag { + map.entry("SoundEvent".into()) + .or_insert_with(|| string("minecraft:entity.arrow.hit")); + // Projectile: LeftOwner only when set; Owner as the UUID. + map.remove(&"LeftOwner".into()); + map.remove(&"inBlockState".into()); + } + if p.left_owner { + put(&mut tag, "LeftOwner", Tag::Byte(1)); + } + if let Some(state) = in_block { + put(&mut tag, "inBlockState", state); + } if let Some(owner) = owner { put(&mut tag, "Owner", Tag::IntArray(owner.to_vec())); } - tag + Some(tag) } -pub fn arrow_from_nbt(tag: &Tag, player: Option<[i32; 4]>) -> Option { +/// A saved arrow as a live one (`readAdditionalSaveData`), with its +/// `inBlockState` compound for the caller to resolve. `effect` is the tipped +/// arrow's lasting effect from its item. +pub fn arrow_from_nbt( + tag: &Tag, + player: Option<[i32; 4]>, + effect: impl FnOnce(&crate::items::ItemStack) -> Option<(&'static str, i32)>, +) -> Option<(Projectile, Option)> { let position = position(tag)?; - let stuck = flag(tag, "inGround"); - Some(Arrow { - from_player: player.is_some() && uuid_from_tag(tag.get("Owner")) == player - || number(tag.get("pickup")) == Some(1), - critical: flag(tag, "crit"), - position, - previous: position, - velocity: motion(tag), - stuck, - age: if stuck { - number(tag.get("life")).unwrap_or(0).max(0) as u32 - } else { - 0 - }, + let owner = uuid_from_tag(tag.get("Owner")); + let from_player = player.is_some() && owner == player; + let item = tag + .get("item") + .and_then(item_from_nbt) + .unwrap_or_else(|| crate::items::ItemStack::new("minecraft:arrow", 1)); + let kind = ProjectileKind::Arrow { base_damage: float(tag.get("damage")).unwrap_or(2.0), - }) + critical: flag(tag, "crit"), + effect: effect(&item), + }; + let mut p = Projectile::new(kind, position, from_player.then_some(Who::Player)); + p.velocity = motion(tag); + [p.yaw, p.pitch] = rotation(tag); + p.left_owner = flag(tag, "LeftOwner"); + let a = p.arrow.as_mut()?; + a.life = number(tag.get("life")).unwrap_or(0) as i16 as i32; + a.shake = (number(tag.get("shake")).unwrap_or(0) as i8 as u8).into(); + a.in_ground = flag(tag, "inGround"); + a.pickup = Pickup::from_byte(number(tag.get("pickup")).unwrap_or(0)); + a.pierce = number(tag.get("PierceLevel")).unwrap_or(0) as u8; + a.has_been_shot = flag(tag, "HasBeenShot"); + a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i16 as i32; + a.fall_distance = float(tag.get("fall_distance")).unwrap_or(0.0); + a.pickup_item = item; + p.stuck = a.in_ground; + Some((p, tag.get("inBlockState").cloned())) } /// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities. diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs new file mode 100644 index 000000000..86c301603 --- /dev/null +++ b/crates/horizon-client/src/extras.rs @@ -0,0 +1,796 @@ +//! Horizon's optional extras (zoom, FPS counter, keystroke overlay): their +//! settings, kept in `horizon-extras.txt` next to `options.txt` so that file +//! stays exactly vanilla's, and the logic behind them. Every extra is off by +//! default; see `docs/extras.md`. +use std::{collections::VecDeque, fs, path::Path}; + +pub const FILE: &str = "horizon-extras.txt"; +/// The name the options screen uses while the zoom key waits for a key. +pub const ZOOM_KEY: &str = "horizon.zoom"; +/// Zoom levels the default cycles through, and the wheel's limits. +pub const ZOOM_LEVELS: [u8; 6] = [2, 3, 4, 6, 8, 10]; +pub const ZOOM_MIN: f32 = 1.25; +/// `Camera.tickFov` keeps the field-of-view modifier at 0.1 or more. +pub const ZOOM_MAX: f32 = 10.0; +/// Each wheel step multiplies the zoom by this. +const ZOOM_STEP: f32 = 1.25; + +/// The minimap's sizes in GUI pixels, and its zooms in blocks per pixel. +pub const MINIMAP_SIZES: [(u8, &str); 3] = [(64, "Small"), (96, "Medium"), (128, "Large")]; +pub const MINIMAP_ZOOMS: [f32; 4] = [0.5, 1.0, 2.0, 4.0]; + +/// A screen corner for an overlay. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Corner { + TopLeft, + TopRight, + BottomLeft, + BottomRight, +} +impl Corner { + pub const ALL: [Corner; 4] = [ + Corner::TopLeft, + Corner::TopRight, + Corner::BottomLeft, + Corner::BottomRight, + ]; + pub fn name(self) -> &'static str { + match self { + Corner::TopLeft => "top_left", + Corner::TopRight => "top_right", + Corner::BottomLeft => "bottom_left", + Corner::BottomRight => "bottom_right", + } + } + pub fn label(self) -> &'static str { + match self { + Corner::TopLeft => "Top left", + Corner::TopRight => "Top right", + Corner::BottomLeft => "Bottom left", + Corner::BottomRight => "Bottom right", + } + } + fn parse(s: &str, default: Corner) -> Corner { + Self::ALL + .into_iter() + .find(|c| c.name() == s) + .unwrap_or(default) + } + pub fn top(self) -> bool { + matches!(self, Corner::TopLeft | Corner::TopRight) + } + pub fn left(self) -> bool { + matches!(self, Corner::TopLeft | Corner::BottomLeft) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Extras { + pub zoom: bool, + /// A vanilla key name (`key.keyboard.z`). + pub zoom_key: String, + /// The zoom the key starts at. + pub zoom_level: u8, + /// Ease through vanilla's FOV easing (as the spyglass does). + pub zoom_smooth: bool, + /// Divide mouse turning by the zoom. + pub zoom_sensitivity: bool, + pub fps: bool, + pub fps_corner: Corner, + /// Also show the minimum and 1% low. + pub fps_lows: bool, + pub keystrokes: bool, + pub keystrokes_corner: Corner, + /// Clicks per second under the mouse buttons. + pub keystrokes_cps: bool, + pub minimap: bool, + pub minimap_corner: Corner, + /// Side in GUI pixels (`MINIMAP_SIZES`). + pub minimap_size: u8, + pub minimap_round: bool, + /// Blocks per pixel (`MINIMAP_ZOOMS`). + pub minimap_zoom: f32, + /// Turn with the player (forward up) instead of north up. + pub minimap_rotate: bool, + /// Retry lost multiplayer connections (`reconnect`). + pub auto_reconnect: bool, +} +impl Default for Extras { + fn default() -> Self { + Self { + zoom: false, + zoom_key: "key.keyboard.z".into(), + zoom_level: 4, + zoom_smooth: true, + zoom_sensitivity: true, + fps: false, + fps_corner: Corner::TopLeft, + fps_lows: false, + keystrokes: false, + keystrokes_corner: Corner::TopLeft, + keystrokes_cps: true, + minimap: false, + minimap_corner: Corner::TopRight, + minimap_size: 96, + minimap_round: false, + minimap_zoom: 1.0, + minimap_rotate: false, + auto_reconnect: false, + } + } +} +fn bool_text(v: bool) -> &'static str { + if v { "true" } else { "false" } +} +impl Extras { + pub fn load(dir: &Path) -> Self { + fs::read_to_string(dir.join(FILE)) + .map(|t| Self::parse(&t)) + .unwrap_or_default() + } + pub fn parse(text: &str) -> Self { + let mut e = Self::default(); + for line in text.lines() { + let Some((key, value)) = line.split_once(':') else { + continue; + }; + let value = value.trim(); + let flag = |d: bool| match value { + "true" => true, + "false" => false, + _ => d, + }; + match key.trim() { + "zoom" => e.zoom = flag(e.zoom), + "zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(), + "zoomLevel" => { + if let Ok(v) = value.parse::() { + e.zoom_level = v.clamp(2, ZOOM_MAX as u8); + } + } + "zoomSmooth" => e.zoom_smooth = flag(e.zoom_smooth), + "zoomSensitivity" => e.zoom_sensitivity = flag(e.zoom_sensitivity), + "fps" => e.fps = flag(e.fps), + "fpsCorner" => e.fps_corner = Corner::parse(value, e.fps_corner), + "fpsLows" => e.fps_lows = flag(e.fps_lows), + "keystrokes" => e.keystrokes = flag(e.keystrokes), + "keystrokesCorner" => { + e.keystrokes_corner = Corner::parse(value, e.keystrokes_corner) + } + "keystrokesCps" => e.keystrokes_cps = flag(e.keystrokes_cps), + "minimap" => e.minimap = flag(e.minimap), + "minimapCorner" => e.minimap_corner = Corner::parse(value, e.minimap_corner), + "minimapSize" => { + if let Some(&(v, _)) = MINIMAP_SIZES.iter().find(|s| s.0.to_string() == value) { + e.minimap_size = v; + } + } + "minimapShape" => e.minimap_round = value == "round", + "minimapZoom" => { + if let Some(&z) = MINIMAP_ZOOMS.iter().find(|z| z.to_string() == value) { + e.minimap_zoom = z; + } + } + "minimapRotate" => e.minimap_rotate = flag(e.minimap_rotate), + "autoReconnect" => e.auto_reconnect = flag(e.auto_reconnect), + _ => {} + } + } + e + } + pub fn serialize(&self) -> String { + format!( + "zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\n", + bool_text(self.zoom), + self.zoom_key, + self.zoom_level, + bool_text(self.zoom_smooth), + bool_text(self.zoom_sensitivity), + bool_text(self.fps), + self.fps_corner.name(), + bool_text(self.fps_lows), + bool_text(self.keystrokes), + self.keystrokes_corner.name(), + bool_text(self.keystrokes_cps), + bool_text(self.minimap), + self.minimap_corner.name(), + self.minimap_size, + if self.minimap_round { + "round" + } else { + "square" + }, + self.minimap_zoom, + bool_text(self.minimap_rotate), + bool_text(self.auto_reconnect), + ) + } + /// Written only once something differs from the defaults, so a vanilla + /// setup gains no file. + pub fn save(&self, dir: &Path) { + let path = dir.join(FILE); + if *self == Self::default() && !path.exists() { + return; + } + let _ = fs::write(path, self.serialize()); + } +} + +/// The zoom key's state: held or not, and the zoom the wheel has set. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Zoom { + held: bool, + factor: f32, +} +impl Default for Zoom { + fn default() -> Self { + Self { + held: false, + factor: 1.0, + } + } +} +impl Zoom { + /// The key went down: start at the default level. + pub fn press(&mut self, level: u8) { + self.held = true; + self.factor = f32::from(level).clamp(ZOOM_MIN, ZOOM_MAX); + } + pub fn release(&mut self) { + self.held = false; + } + /// A press or release of the zoom key. Only a press while `playing` (no + /// screen or text field open) zooms; anywhere else the key belongs to + /// the screen, and the zoom lets go. + pub fn key(&mut self, pressed: bool, repeat: bool, playing: bool, level: u8) { + if !pressed || !playing { + self.release(); + } else if !repeat { + self.press(level); + } + } + pub fn held(&self) -> bool { + self.held + } + /// Wheel steps while held (positive zooms in); false when not zooming. + pub fn scroll(&mut self, steps: f32) -> bool { + if !self.held { + return false; + } + self.factor = (self.factor * ZOOM_STEP.powf(steps)).clamp(ZOOM_MIN, ZOOM_MAX); + true + } + /// The zoom in effect: 1 when the key is up or the spyglass is in use + /// (scoping keeps vanilla's spyglass view). + pub fn factor(&self, scoping: bool) -> f32 { + if self.held && !scoping { + self.factor + } else { + 1.0 + } + } +} +/// Vanilla key mappings bound to the zoom key. The key still reaches them +/// (a key bound twice triggers both, as vanilla's do), so the Extras page +/// says so. +pub fn zoom_key_conflicts(e: &Extras, keys: &crate::keybinds::KeyBinds) -> Vec<&'static str> { + if e.zoom_key == "key.keyboard.unknown" { + return Vec::new(); + } + crate::keybinds::MAPPINGS + .iter() + .map(|m| m.0) + .filter(|name| keys.get(name) == e.zoom_key) + .collect() +} +/// The field-of-view modifier target `Camera.tickFov` eases toward: vanilla's +/// (`getFieldOfViewModifier`) divided by the zoom. A zoom of 1 leaves it as is. +pub fn fov_target(vanilla: f32, zoom: f32) -> f32 { + if zoom == 1.0 { vanilla } else { vanilla / zoom } +} +/// The mouse turning scale while zoomed. +pub fn turn_scale(zoom: f32, lower_sensitivity: bool) -> f64 { + if lower_sensitivity && zoom > 1.0 { + 1.0 / f64::from(zoom) + } else { + 1.0 + } +} + +/// Frame times over the last few seconds: frames per second, the minimum +/// and the 1% low, recomputed twice a second. +pub struct FpsCounter { + /// (end time in seconds, frame milliseconds), oldest first. + frames: VecDeque<(f64, f32)>, + shown: FpsReading, + computed_at: f64, +} +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FpsReading { + pub fps: u32, + pub min: u32, + pub low: u32, +} +/// Seconds the minimum and 1% low look back. +const LOW_WINDOW: f64 = 5.0; +impl Default for FpsCounter { + fn default() -> Self { + Self { + frames: VecDeque::new(), + shown: FpsReading::default(), + computed_at: f64::NEG_INFINITY, + } + } +} +impl FpsCounter { + /// A frame that ended at `now` (seconds) and took `ms`. + pub fn record(&mut self, now: f64, ms: f32) { + self.frames.push_back((now, ms)); + while self + .frames + .front() + .is_some_and(|&(t, _)| now - t > LOW_WINDOW) + { + self.frames.pop_front(); + } + if now - self.computed_at >= 0.5 { + self.computed_at = now; + self.shown = self.compute(now); + } + } + fn compute(&self, now: f64) -> FpsReading { + let fps = self.frames.iter().filter(|&&(t, _)| now - t < 1.0).count() as u32; + let mut times: Vec = self.frames.iter().map(|f| f.1).collect(); + if times.is_empty() { + return FpsReading::default(); + } + times.sort_by(|a, b| b.total_cmp(a)); + let to_fps = |ms: f32| (1000.0 / ms.max(0.001)).round() as u32; + // The 1% low: the frame rate of the 99th percentile frame time. + let low = times[(times.len() - 1) / 100]; + FpsReading { + fps, + min: to_fps(times[0]), + low: to_fps(low), + } + } + pub fn reading(&self) -> FpsReading { + self.shown + } + pub fn clear(&mut self) { + *self = Self::default(); + } +} + +/// Clicks of one button in the last second. +#[derive(Default)] +pub struct Cps { + clicks: VecDeque, +} +impl Cps { + pub fn click(&mut self, now: f64) { + self.clicks.push_back(now); + self.forget(now); + } + fn forget(&mut self, now: f64) { + while self.clicks.front().is_some_and(|&t| now - t >= 1.0) { + self.clicks.pop_front(); + } + } + pub fn per_second(&mut self, now: f64) -> usize { + self.forget(now); + self.clicks.len() + } +} + +/// The settings the Extras page shows, one per row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Item { + Zoom, + ZoomKey, + ZoomLevel, + ZoomSmooth, + ZoomSensitivity, + Fps, + FpsCorner, + FpsLows, + Keystrokes, + KeystrokesCorner, + KeystrokesCps, + Minimap, + MinimapCorner, + MinimapSize, + MinimapShape, + MinimapZoom, + MinimapRotate, + AutoReconnect, +} +/// The Extras page: headers and items. +pub fn rows() -> Vec> { + use Item::*; + vec![ + Err("Zoom"), + Ok(Zoom), + Ok(ZoomKey), + Ok(ZoomLevel), + Ok(ZoomSmooth), + Ok(ZoomSensitivity), + Err("Minimap"), + Ok(Minimap), + Ok(MinimapCorner), + Ok(MinimapSize), + Ok(MinimapShape), + Ok(MinimapZoom), + Ok(MinimapRotate), + Err("FPS counter"), + Ok(Fps), + Ok(FpsCorner), + Ok(FpsLows), + Err("Keystrokes"), + Ok(Keystrokes), + Ok(KeystrokesCorner), + Ok(KeystrokesCps), + Err("Multiplayer"), + Ok(AutoReconnect), + ] +} +/// "1 block", "2 blocks", "½ block". +fn block_count(n: f32) -> String { + if n < 1.0 { + "½ block".into() + } else if n == 1.0 { + "1 block".into() + } else { + format!("{n} blocks") + } +} +fn next(all: &[T], current: T, back: bool) -> T { + let i = all.iter().position(|v| *v == current).unwrap_or(0); + let n = all.len(); + all[if back { (i + n - 1) % n } else { (i + 1) % n }] +} +impl Item { + pub fn caption(self) -> &'static str { + match self { + Item::Zoom => "Zoom", + Item::ZoomKey => "Zoom key", + Item::ZoomLevel => "Starting zoom", + Item::ZoomSmooth => "Smooth zoom", + Item::ZoomSensitivity => "Lower sensitivity while zoomed", + Item::Fps => "FPS counter", + Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => "Corner", + Item::Minimap => "Minimap", + Item::MinimapSize => "Size", + Item::MinimapShape => "Shape", + Item::MinimapZoom => "Zoom", + Item::MinimapRotate => "Turn with the player", + Item::AutoReconnect => "Auto-reconnect", + Item::FpsLows => "Minimum and 1% low", + Item::Keystrokes => "Keystrokes", + Item::KeystrokesCps => "Clicks per second", + } + } + /// What the row says under its caption. + pub fn description(self) -> &'static str { + match self { + Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.", + Item::ZoomKey => "Click, then press a key. Escape unbinds it.", + Item::ZoomLevel => "The zoom the key starts at.", + Item::ZoomSmooth => "Eases in and out like the spyglass.", + Item::ZoomSensitivity => "Turns slower the more you zoom in.", + Item::Fps => "Frames per second in a corner of the screen.", + Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => { + "Overlays in one corner stack." + } + Item::Minimap => "A map of the loaded terrain around you, in map colours.", + Item::MinimapSize => "How big the map is on screen.", + Item::MinimapShape => "Square or round.", + Item::MinimapZoom => "Blocks per pixel: smaller shows more detail, larger more land.", + Item::MinimapRotate => "Forward is up; off keeps north up.", + Item::AutoReconnect => { + "Rejoins a server after a lost connection or a restart, never after a kick or ban." + } + Item::FpsLows => "The slowest frame and the 1% low of the last 5 seconds.", + Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.", + Item::KeystrokesCps => "Clicks in the last second under each mouse button.", + } + } + /// The frame-time cost the main switch of an extra shows. + pub fn cost(self) -> Option { + use crate::graphics_style::Cost; + match self { + Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), + Item::Minimap => Some(Cost::Low), + Item::AutoReconnect => Some(Cost::None), + _ => None, + } + } + /// On/off items and their value. + pub fn switch(self, e: &Extras) -> Option { + Some(match self { + Item::Zoom => e.zoom, + Item::ZoomSmooth => e.zoom_smooth, + Item::ZoomSensitivity => e.zoom_sensitivity, + Item::Fps => e.fps, + Item::FpsLows => e.fps_lows, + Item::Keystrokes => e.keystrokes, + Item::KeystrokesCps => e.keystrokes_cps, + Item::Minimap => e.minimap, + Item::MinimapRotate => e.minimap_rotate, + Item::AutoReconnect => e.auto_reconnect, + _ => return None, + }) + } + /// The value of the other items, as their button shows it. + pub fn value(self, e: &Extras) -> String { + match self { + Item::ZoomKey => crate::keybinds::display_name(&e.zoom_key).plain(), + Item::ZoomLevel => format!("{}x", e.zoom_level), + Item::FpsCorner => e.fps_corner.label().into(), + Item::KeystrokesCorner => e.keystrokes_corner.label().into(), + Item::MinimapCorner => e.minimap_corner.label().into(), + Item::MinimapSize => MINIMAP_SIZES + .iter() + .find(|s| s.0 == e.minimap_size) + .map_or("Medium", |s| s.1) + .into(), + Item::MinimapShape => if e.minimap_round { "Round" } else { "Square" }.into(), + Item::MinimapZoom => format!("{} per pixel", block_count(e.minimap_zoom)), + other => match other.switch(e) { + Some(true) => "On".into(), + _ => "Off".into(), + }, + } + } + /// A click (`back` for the right button). The zoom key binds instead. + pub fn cycle(self, e: &mut Extras, back: bool) { + match self { + Item::Zoom => e.zoom = !e.zoom, + Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth, + Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity, + Item::Fps => e.fps = !e.fps, + Item::FpsLows => e.fps_lows = !e.fps_lows, + Item::Keystrokes => e.keystrokes = !e.keystrokes, + Item::KeystrokesCps => e.keystrokes_cps = !e.keystrokes_cps, + Item::ZoomLevel => e.zoom_level = next(&ZOOM_LEVELS, e.zoom_level, back), + Item::FpsCorner => e.fps_corner = next(&Corner::ALL, e.fps_corner, back), + Item::KeystrokesCorner => { + e.keystrokes_corner = next(&Corner::ALL, e.keystrokes_corner, back) + } + Item::Minimap => e.minimap = !e.minimap, + Item::MinimapRotate => e.minimap_rotate = !e.minimap_rotate, + Item::AutoReconnect => e.auto_reconnect = !e.auto_reconnect, + Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back), + Item::MinimapSize => { + let sizes: Vec = MINIMAP_SIZES.iter().map(|s| s.0).collect(); + e.minimap_size = next(&sizes, e.minimap_size, back); + } + Item::MinimapShape => e.minimap_round = !e.minimap_round, + Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back), + Item::ZoomKey => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn everything_is_off_by_default_and_round_trips() { + let d = Extras::default(); + assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect); + assert_eq!(Extras::parse(""), d); + assert_eq!(Extras::parse(&d.serialize()), d); + let mut e = d.clone(); + e.zoom = true; + e.zoom_key = "key.keyboard.c".into(); + e.zoom_level = 6; + e.fps_corner = Corner::BottomRight; + e.keystrokes = true; + e.keystrokes_cps = false; + e.minimap = true; + e.minimap_size = 128; + e.minimap_round = true; + e.minimap_zoom = 0.5; + e.minimap_rotate = true; + e.minimap_corner = Corner::BottomLeft; + e.auto_reconnect = true; + assert_eq!(Extras::parse(&e.serialize()), e); + } + + #[test] + fn bad_lines_keep_defaults() { + let e = Extras::parse("zoom:maybe\nzoomLevel:99\nfpsCorner:middle\nzoomKey:z\nnoise"); + assert!(!e.zoom); + assert_eq!(e.zoom_level, 10); + assert_eq!(e.fps_corner, Corner::TopLeft); + assert_eq!(e.zoom_key, "key.keyboard.z"); + } + + #[test] + fn default_zoom_key_is_free_in_vanilla() { + let key = Extras::default().zoom_key; + assert!(crate::keybinds::key_code(&key).is_some()); + assert!( + crate::keybinds::MAPPINGS.iter().all(|m| m.1 != key), + "{key} is a vanilla binding" + ); + } + + #[test] + fn zoom_is_vanilla_unless_held_and_not_scoping() { + let mut z = Zoom::default(); + assert_eq!(z.factor(false), 1.0); + assert_eq!(fov_target(1.1, z.factor(false)), 1.1); + assert!(!z.scroll(1.0), "the wheel is the hotbar's when not zooming"); + z.press(4); + assert_eq!(z.factor(false), 4.0); + assert_eq!(z.factor(true), 1.0, "the spyglass wins"); + assert!((fov_target(1.0, 4.0) - 0.25).abs() < 1e-6); + assert!(z.scroll(1.0)); + assert!((z.factor(false) - 5.0).abs() < 1e-5); + for _ in 0..40 { + z.scroll(1.0); + } + assert_eq!(z.factor(false), ZOOM_MAX); + for _ in 0..80 { + z.scroll(-1.0); + } + assert_eq!(z.factor(false), ZOOM_MIN); + z.release(); + assert_eq!(z.factor(false), 1.0); + z.press(2); + assert_eq!(z.factor(false), 2.0, "each press starts at the default"); + } + + #[test] + fn zoom_target_eases_like_the_spyglass() { + // Camera.tickFov halves the distance to the target each tick. + let mut camera = crate::camera::Camera::default(); + camera.tick(None, 1.0); + for _ in 0..30 { + camera.tick(None, 1.0); + } + let target = fov_target(1.0, 4.0); + camera.tick(None, target); + let first = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false); + assert!((first - 70.0 * 0.625).abs() < 1e-3, "{first}"); + for _ in 0..30 { + camera.tick(None, target); + } + let settled = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false); + assert!((settled - 70.0 / 4.0).abs() < 1e-3, "{settled}"); + // Deeper than the 0.1 floor stops there, as vanilla clamps. + for _ in 0..30 { + camera.tick(None, fov_target(1.0, 20.0)); + } + let floor = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false); + assert!((floor - 7.0).abs() < 1e-3, "{floor}"); + } + + #[test] + fn the_zoom_key_only_zooms_while_playing() { + let mut z = Zoom::default(); + // In chat, a sign, a text field or any screen: no zoom. + z.key(true, false, false, 4); + assert!(!z.held()); + z.key(true, false, true, 4); + assert!(z.held()); + // A screen opening while held lets go (its key presses are the screen's). + z.key(true, true, false, 4); + assert!(!z.held()); + // Key repeats do not restart a zoom the wheel changed. + z.key(true, false, true, 4); + z.scroll(1.0); + z.key(true, true, true, 4); + assert!((z.factor(false) - 5.0).abs() < 1e-5); + z.key(false, false, true, 4); + assert!(!z.held()); + } + + #[test] + fn zoom_key_conflicts_name_the_vanilla_mappings() { + let mut e = Extras::default(); + let mut keys = crate::keybinds::KeyBinds::default(); + assert!(zoom_key_conflicts(&e, &keys).is_empty()); + e.zoom_key = "key.keyboard.c".into(); + assert_eq!( + zoom_key_conflicts(&e, &keys), + [ + "key.saveToolbarActivator", + "key.debug.crash", + "key.debug.copyLocation" + ] + ); + keys.set("key.drop", "key.keyboard.z"); + e.zoom_key = "key.keyboard.z".into(); + assert_eq!(zoom_key_conflicts(&e, &keys), ["key.drop"]); + e.zoom_key = "key.keyboard.unknown".into(); + keys.set("key.smoothCamera", "key.keyboard.unknown"); + assert!(zoom_key_conflicts(&e, &keys).is_empty()); + } + + #[test] + fn sensitivity_scales_with_zoom() { + assert_eq!(turn_scale(1.0, true), 1.0); + assert_eq!(turn_scale(4.0, false), 1.0); + assert_eq!(turn_scale(4.0, true), 0.25); + } + + #[test] + fn fps_counter_reports_rate_minimum_and_low() { + let mut c = FpsCounter::default(); + let mut t = 0.0; + // Two seconds at 100 fps with one 50 ms hitch. + for i in 0..200 { + let ms = if i == 150 { 50.0 } else { 10.0 }; + t += f64::from(ms) / 1000.0; + c.record(t, ms); + } + c.computed_at = f64::NEG_INFINITY; + c.record(t + 0.01, 10.0); + let r = c.reading(); + assert!((95..=101).contains(&r.fps), "{r:?}"); + assert_eq!(r.min, 20); + assert_eq!(r.low, 100, "one frame in 200 is under the 1% mark"); + // Hitches beyond 1% of frames pull the 1% low down. + let mut c = FpsCounter::default(); + let mut t = 0.0; + for i in 0..100 { + let ms = if i % 25 == 0 { 40.0 } else { 10.0 }; + t += f64::from(ms) / 1000.0; + c.record(t, ms); + } + c.computed_at = f64::NEG_INFINITY; + c.record(t, 10.0); + assert_eq!(c.reading().low, 25); + } + + #[test] + fn old_frames_leave_the_window() { + let mut c = FpsCounter::default(); + c.record(0.0, 100.0); + for i in 1..=700 { + c.record(f64::from(i) / 100.0, 10.0); + } + assert_eq!(c.reading().min, 100, "the 100 ms frame is 7 s old"); + } + + #[test] + fn cps_counts_the_last_second() { + let mut cps = Cps::default(); + for i in 0..10 { + cps.click(f64::from(i) * 0.1); + } + assert_eq!(cps.per_second(0.95), 10); + assert_eq!(cps.per_second(1.25), 7); + assert_eq!(cps.per_second(3.0), 0); + } + + #[test] + fn items_cycle_through_their_values() { + let mut e = Extras::default(); + Item::ZoomLevel.cycle(&mut e, false); + assert_eq!(e.zoom_level, 6); + Item::ZoomLevel.cycle(&mut e, true); + Item::ZoomLevel.cycle(&mut e, true); + assert_eq!(e.zoom_level, 3); + Item::FpsCorner.cycle(&mut e, true); + assert_eq!(e.fps_corner, Corner::BottomRight); + Item::Zoom.cycle(&mut e, false); + assert_eq!(Item::Zoom.switch(&e), Some(true)); + assert_eq!(Item::ZoomKey.value(&e), "Z"); + Item::MinimapZoom.cycle(&mut e, true); + assert_eq!(Item::MinimapZoom.value(&e), "½ block per pixel"); + Item::MinimapSize.cycle(&mut e, false); + assert_eq!(Item::MinimapSize.value(&e), "Large"); + assert_eq!( + Extras::parse("minimapSize:7\nminimapZoom:3").minimap_zoom, + 1.0 + ); + for item in rows().into_iter().flatten() { + assert!(!item.caption().is_empty() && !item.description().is_empty()); + } + } +} diff --git a/crates/horizon-client/src/extras_hud.rs b/crates/horizon-client/src/extras_hud.rs new file mode 100644 index 000000000..df23b533f --- /dev/null +++ b/crates/horizon-client/src/extras_hud.rs @@ -0,0 +1,247 @@ +//! The extras' HUD overlays (FPS counter, keystrokes): small boxes in the +//! vanilla font, in GUI pixels, stacked per corner (`docs/extras.md`). +use crate::{ + extras::{Corner, FpsReading}, + hud::{HudAtlas, HudBatch, Rect, rgba}, +}; + +/// The gap between an overlay and the screen edge or the next overlay. +const MARGIN: f32 = 2.0; +const BACKGROUND: u32 = 0x7800_0000; + +/// Where the next overlay goes in each corner. +pub struct Corners { + width: f32, + height: f32, + /// Distance from the corner's top or bottom edge, per `Corner::ALL`. + used: [f32; 4], +} +impl Corners { + /// `top_right` reserves the status effect icons' rows. + pub fn new(width: f32, height: f32, top_right: f32) -> Self { + Self { + width, + height, + used: [0.0, top_right, 0.0, 0.0], + } + } + /// The top-left position of a `w` x `h` box in `corner`, below (or + /// above) what the corner already holds. + pub fn place(&mut self, corner: Corner, w: f32, h: f32) -> (f32, f32) { + let i = Corner::ALL.iter().position(|c| *c == corner).unwrap_or(0); + let edge = self.used[i] + MARGIN; + self.used[i] = edge + h; + let x = if corner.left() { + MARGIN + } else { + self.width - MARGIN - w + }; + let y = if corner.top() { + edge + } else { + self.height - edge - h + }; + (x, y) + } +} + +/// How the minimap shows: its corner and side in GUI pixels, its image (an +/// atlas rect), the player arrow (the map item's decoration sprite) turned +/// `arrow` degrees clockwise from up, and the rim's N toward `north` when the +/// map turns. +pub struct MinimapLook { + pub corner: Corner, + pub size: f32, + pub image: Rect, + pub arrow: f32, + pub north: Option<(f32, f32)>, +} +pub fn draw_minimap( + batch: &mut HudBatch, + atlas: &HudAtlas, + corners: &mut Corners, + look: &MinimapLook, +) { + let MinimapLook { + corner, + size, + image, + arrow, + north, + } = *look; + let (x, y) = corners.place(corner, size, size); + batch.rect_uv(x, y, size, size, image, u32::MAX); + let (cx, cy) = (x + size / 2.0, y + size / 2.0); + if let Some(r) = atlas.sprites.get("map/decorations/player").copied() { + // MapRenderer's decorations draw the sprite flipped: its arrow + // points down the texture, so up on screen is half a turn. + let (s, c) = (arrow + 180.0).to_radians().sin_cos(); + let p = |dx: f32, dy: f32| [cx + dx * c - dy * s, cy + dx * s + dy * c]; + let h = 4.0; + batch.quad( + [p(-h, h), p(h, h), p(h, -h), p(-h, -h)], + [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]], + u32::MAX, + ); + } + if let Some((nx, ny)) = north { + let reach = size / 2.0 - 6.0; + let tw = HudBatch::text_width(atlas, "N"); + let (tx, ty) = (cx + nx * reach - tw / 2.0, cy + ny * reach - 4.0); + batch.text( + atlas, + "N", + tx.round(), + ty.round(), + rgba(255, 255, 255, 255), + true, + ); + } +} + +/// The FPS counter's text. +pub fn fps_text(r: FpsReading, lows: bool) -> String { + if lows { + format!("{} fps min {} 1% {}", r.fps, r.min, r.low) + } else { + format!("{} fps", r.fps) + } +} +pub fn draw_fps( + batch: &mut HudBatch, + atlas: &HudAtlas, + corners: &mut Corners, + corner: Corner, + reading: FpsReading, + lows: bool, +) { + let text = fps_text(reading, lows); + let w = HudBatch::text_width(atlas, &text) + 4.0; + let (x, y) = corners.place(corner, w, 12.0); + batch.fill(atlas, x, y, w, 12.0, BACKGROUND); + batch.text( + atlas, + &text, + x + 2.0, + y + 2.0, + rgba(255, 255, 255, 255), + true, + ); +} + +/// What the keystroke overlay shows. +pub struct Keystrokes { + /// Forward, left, back, right: held, and the bound key's name. + pub moves: [(bool, String); 4], + pub jump: bool, + pub attack: bool, + pub use_: bool, + /// Clicks per second of the left and right buttons, when shown. + pub cps: Option<(usize, usize)>, +} +const KEY: f32 = 22.0; +const GAP: f32 = 2.0; +/// The overlay's size. +pub fn keystrokes_size() -> (f32, f32) { + (3.0 * KEY + 2.0 * GAP, 3.0 * KEY + 3.0 * GAP + 10.0) +} +fn key_box(batch: &mut HudBatch, atlas: &HudAtlas, rect: [f32; 4], held: bool, lines: &[&str]) { + let [x, y, w, h] = rect; + let (fill, ink) = if held { + (rgba(255, 255, 255, 176), rgba(20, 20, 20, 255)) + } else { + (BACKGROUND, rgba(255, 255, 255, 255)) + }; + batch.fill(atlas, x, y, w, h, fill); + let total = lines.len() as f32 * 9.0 - 1.0; + for (i, line) in lines.iter().enumerate() { + let tw = HudBatch::text_width(atlas, line); + let tx = (x + (w - tw) / 2.0).round(); + let ty = (y + (h - total) / 2.0).round() + i as f32 * 9.0; + batch.text(atlas, line, tx, ty, ink, !held); + } +} +pub fn draw_keystrokes( + batch: &mut HudBatch, + atlas: &HudAtlas, + corners: &mut Corners, + corner: Corner, + k: &Keystrokes, +) { + let (w, h) = keystrokes_size(); + let (x, y) = corners.place(corner, w, h); + let step = KEY + GAP; + let [forward, left, back, right] = &k.moves; + key_box( + batch, + atlas, + [x + step, y, KEY, KEY], + forward.0, + &[&forward.1], + ); + for (i, key) in [left, back, right].into_iter().enumerate() { + key_box( + batch, + atlas, + [x + i as f32 * step, y + step, KEY, KEY], + key.0, + &[&key.1], + ); + } + let mw = (w - GAP) / 2.0; + let my = y + 2.0 * step; + for (i, (held, label, cps)) in [ + (k.attack, "LMB", k.cps.map(|c| c.0)), + (k.use_, "RMB", k.cps.map(|c| c.1)), + ] + .into_iter() + .enumerate() + { + let rate = cps.map(|n| format!("{n} CPS")); + let lines: Vec<&str> = std::iter::once(label).chain(rate.as_deref()).collect(); + key_box( + batch, + atlas, + [x + i as f32 * (mw + GAP), my, mw, KEY], + held, + &lines, + ); + } + // The space bar: a line in a short key. + let sy = my + step; + key_box(batch, atlas, [x, sy, w, 10.0], k.jump, &[]); + let ink = if k.jump { + rgba(20, 20, 20, 255) + } else { + rgba(255, 255, 255, 255) + }; + batch.fill(atlas, x + w / 2.0 - 12.0, sy + 4.0, 24.0, 2.0, ink); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn corners_stack_away_from_their_edge() { + let mut c = Corners::new(400.0, 300.0, 26.0); + assert_eq!(c.place(Corner::TopLeft, 50.0, 12.0), (2.0, 2.0)); + assert_eq!(c.place(Corner::TopLeft, 70.0, 20.0), (2.0, 16.0)); + // Top right starts under the effect icons. + assert_eq!(c.place(Corner::TopRight, 50.0, 12.0), (348.0, 28.0)); + assert_eq!(c.place(Corner::BottomRight, 50.0, 12.0), (348.0, 286.0)); + assert_eq!(c.place(Corner::BottomRight, 50.0, 10.0), (348.0, 274.0)); + assert_eq!(c.place(Corner::BottomLeft, 10.0, 10.0), (2.0, 288.0)); + } + + #[test] + fn fps_text_with_and_without_lows() { + let r = FpsReading { + fps: 144, + min: 61, + low: 98, + }; + assert_eq!(fps_text(r, false), "144 fps"); + assert_eq!(fps_text(r, true), "144 fps min 61 1% 98"); + } +} diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 835a36a90..801b1e303 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -211,6 +211,9 @@ pub struct FogInputs<'a> { pub blindness: Option<(i32, bool)>, /// The darkness effect's blend factor, while the effect is on. pub darkness: Option, + /// `BossHealthOverlay.shouldCreateWorldFog`: a boss bar with + /// `createWorldFog` is shown (the Ender Dragon's). + pub boss_world_fog: bool, } /// `FogRenderer.setupFog` + `computeFogColor`. @@ -338,6 +341,12 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog fog.environmental_end = min_end.max(sky.fog_end + -256.0 * state.rain_fog_multiplier); fog.sky_end = rd.min(512.0); fog.cloud_end = ((input.cloud_range_chunks * 16) as f32).min(sky.cloud_fog_end); + if input.boss_world_fog { + fog.environmental_start = fog.environmental_start.min(10.0); + fog.environmental_end = fog.environmental_end.min(96.0); + fog.sky_end = fog.environmental_end; + fog.cloud_end = fog.environmental_end; + } } } let span = (rd / 10.0).clamp(4.0, 64.0); @@ -385,9 +394,57 @@ mod tests { skybox: true, blindness: None, darkness: None, + boss_world_fog: false, } } #[test] + fn boss_world_fog_closes_in() { + // AtmosphericFogEnvironment.setupFog under a createWorldFog boss bar. + let sky = Sky { + fog_end: 1024.0, + cloud_fog_end: 2048.0, + ..Sky::default() + }; + let tables = FogTables { + water_fog_end: vec![1.0], + }; + let mut input = inputs(&sky); + input.boss_world_fog = true; + let fog = setup_fog(&tables, &FogState::default(), &input); + assert_eq!( + (fog.environmental_start, fog.environmental_end), + (0.0, 96.0) + ); + assert_eq!((fog.sky_end, fog.cloud_end), (96.0, 96.0)); + // Under water the water environment applies instead. + input.fog_type = FogType::Water; + let water = setup_fog(&tables, &FogState::default(), &input); + assert_eq!(water.environmental_start, -8.0); + } + #[test] + fn void_darkness_starts_32_above_the_floor() { + let sky = Sky { + fog_end: 1024.0, + fog_color: [0.5; 3], + sky_color: [0.5; 3], + ..Sky::default() + }; + let tables = FogTables { + water_fog_end: vec![1.0], + }; + let mut input = inputs(&sky); + // The End's floor is y 0: y 16 is halfway into the darkness. + input.min_y = 0; + input.camera_y = 16.0; + let fog = setup_fog(&tables, &FogState::default(), &input); + assert_eq!(fog.color[0], 0.5 * 0.25); + input.camera_y = 32.0; + assert_eq!( + setup_fog(&tables, &FogState::default(), &input).color[0], + 0.5 + ); + } + #[test] fn render_distance_fog_span() { let sky = Sky { fog_end: 1024.0, diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index a99bfaf57..b4a225030 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -38,6 +38,7 @@ const REFRESH: u64 = id("mp.refresh", 0); const FIELD_A: u64 = id("mp.field", 0); const FIELD_B: u64 = id("mp.field", 1); const DONE: u64 = id("mp.done", 0); +const CANCEL_RETRY: u64 = id("mp.cancel_retry", 0); /// The launcher's opening (`launcher/src/main.rs`): the wordmark holds over /// the backdrop, then the interface comes in. A click or a key skips ahead. @@ -80,7 +81,12 @@ impl Default for Opening { fn page(mode: &Mode) -> usize { match mode { Mode::Main => 0, - Mode::Select { .. } | Mode::Create { .. } => 1, + Mode::Select { .. } + | Mode::Create { .. } + | Mode::Edit { .. } + | Mode::Backup { .. } + | Mode::Delete { .. } + | Mode::Error { .. } => 1, Mode::Multiplayer(_) => 2, } } @@ -90,17 +96,30 @@ impl Title { /// Horizon's layout for every title mode. `backdrop` is how much of the /// live backdrop is visible (0 shows the plain cold background). pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) { + if matches!( + self.mode, + Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } + ) { + self.draw(ui.atlas, ui.batch, ui.cursor); + return; + } let reveal = self.opening_phase(backdrop >= 1.0); if backdrop < 1.0 { ui.cold_background(1.0 - backdrop); } let shade = t::ease_out_cubic(reveal); + // The world stays in view on the home page; deeper pages veil it more. let veil = if matches!(self.mode, Mode::Main) { - 0.42 + horizon_theme::HOME_VEIL } else { - 0.66 + horizon_theme::VEIL }; - ui.atmosphere(veil * shade, shade); + ui.muted = if matches!(self.mode, Mode::Main) { + color::MUTED + } else { + color::FAINT + }; + ui.atmosphere(veil, shade); let side = t::ease_out_cubic((reveal - 0.2) / 0.7); let main = t::ease_out_cubic((reveal - 0.35) / 0.65); @@ -134,6 +153,7 @@ impl Title { let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2); multiplayer_page(ui, x, w, screen, caret); } + _ => unreachable!("World-management screens use the classic layout"), } } ui.opacity = 1.0; @@ -142,7 +162,7 @@ impl Title { // The wordmark rises and fades as the interface comes in. let word = 1.0 - t::ease_out_cubic(reveal / 0.6); ui.opacity = word; - let tw = ui.measure(Face::Display, t::WORDMARK, "Horizon"); + let tw = ui.measure(Face::Display, t::WORDMARK, "horizon"); let line = (t::WORDMARK * 1.2).round(); ui.text_line( Face::Display, @@ -150,8 +170,8 @@ impl Title { line, ((ui.w - tw) / 2.0).round(), (ui.h - line) / 2.0 - 28.0 * (1.0 - word), - color::WHITE, - "Horizon", + color::TEXT, + "horizon", ); ui.opacity = 1.0; } @@ -174,19 +194,9 @@ impl Title { skipped } fn sidebar(&self, ui: &mut Ui) { - let h = ui.h; - ui.fill(0.0, 0.0, SIDEBAR, h, color::with_alpha(color::SIDEBAR, 0.8)); - ui.vline(SIDEBAR - 1.0, 0.0, h, color::BORDER); - ui.text_line( - Face::Display, - 22.0, - 30.0, - 22.0, - 16.0, - color::TEXT, - "Horizon", - ); - ui.sidebar_list(NAV, 12.0, 66.0, SIDEBAR - 24.0, &PAGES, page(&self.mode)); + let (h, muted) = (ui.h, ui.muted); + ui.sidebar_frame("Horizon"); + ui.sidebar_list(NAV, 12.0, 72.0, SIDEBAR - 24.0, &PAGES, page(&self.mode)); let qy = h - 12.0 - 18.0 - 12.0 - CONTROL; let hover = ui.interact(QUIT, 12.0, qy, SIDEBAR - 24.0, CONTROL, true); ui.rounded( @@ -194,51 +204,45 @@ impl Title { qy, SIDEBAR - 24.0, CONTROL, - t::RADIUS, - color::with_alpha(color::HOVER, 0.7 * hover), + t::PILL, + color::with_alpha(color::RAISED, 0.8 * hover), ); ui.text_line( Face::Regular, BODY, CONTROL, - 22.0, + 24.0, qy, - color::mix(color::MUTED, color::TEXT, hover), + color::mix(muted, color::TEXT, hover), "Quit game", ); - ui.text( - Face::Regular, - SMALL, - 22.0, - h - 12.0 - 18.0, - color::FAINT, - "Horizon 26.3", - ); + ui.caps(24.0, h - 12.0 - 18.0, muted, "Horizon 26.3"); } /// Home: the launcher's Play page over the backdrop. fn home(&self, ui: &mut Ui, x: f32, w: f32) { + ui.wordmark(x, w, ui.h - 64.0, 220.0); + let muted = ui.muted; let mut y = 36.0 + 28.0; - ui.text( - Face::Medium, - SMALL, + ui.caps( x, y, - color::FAINT, + muted, "Minecraft 26.3 · Java Edition, rewritten in Rust", ); - y += 22.0; - ui.text_line(Face::Display, t::HERO, 58.0, x, y, color::TEXT, "Horizon"); - y += 58.0 + 12.0; + y += 24.0; + let line = (t::HERO * 1.1).round(); + ui.text_line(Face::Display, t::HERO, line, x, y, color::TEXT, "Horizon"); + y += line + 10.0; ui.text( Face::Regular, t::LARGE, x, y, - color::MUTED, + muted, "The world you know, rebuilt from the ground up.", ); - y += 22.0 + 24.0; - let pw = ui.button_width("Singleplayer", true).max(120.0); + y += 22.0 + 28.0; + let pw = ui.button_width("Singleplayer", true).max(132.0); ui.button( PLAY, [x, y, pw, CONTROL_LARGE], @@ -254,7 +258,8 @@ impl Title { Kind::Secondary, true, ); - y += CONTROL_LARGE + 24.0; + y += CONTROL_LARGE + 32.0; + ui.row_index = 0; ui.divider(x, y, w); let worlds = self.recent_worlds(); let last = worlds.first(); @@ -284,14 +289,11 @@ impl Title { }; y += ui.row(x, y, "Saves", &count, w - t::ROW_LABEL - 16.0); ui.divider(x, y, w); - let note = "Not affiliated with Mojang or Microsoft"; - ui.text( - Face::Regular, - SMALL, + ui.caps( x, ui.h - 12.0 - 18.0, - color::FAINT, - note, + muted, + "Not affiliated with Mojang or Microsoft", ); } /// A click in Horizon's layout (`x`, `y` in GUI pixels). @@ -305,6 +307,12 @@ impl Title { if self.skip_opening() { return Action::None; } + if matches!( + self.mode, + Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } + ) { + return self.click(x, y, (batch.width, batch.height)).0; + } let hit = { let mut ui = Ui::dry(atlas, batch, (x, y)); self.draw_horizon(&mut ui, 1.0); @@ -390,6 +398,7 @@ impl Title { MAKE => return self.create_action(), _ => {} }, + Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } => {} Mode::Multiplayer(screen) => { let id = match hit { JOIN => Some(40), @@ -404,6 +413,7 @@ impl Title { Screen::Direct { .. } => 53, Screen::Disconnected { .. } => 54, }), + CANCEL_RETRY => Some(55), DONE => Some(match screen { Screen::Direct { .. } => 52, _ => 50, @@ -469,8 +479,9 @@ fn actions_right(ui: &mut Ui, right: f32, y: f32, items: &[(u64, &str, Kind, boo } rx } -/// A selectable list row: the launcher's row look with a hover layer and -/// the raised selection with its 1px border. Returns the row height. +/// A selectable list row: its number, the name and a line under it, a mono +/// detail on the right; a soft plate fades in under the pointer and stays +/// under the selection, reaching past the row. Returns the row height. #[allow(clippy::too_many_arguments)] fn list_row( ui: &mut Ui, @@ -484,50 +495,60 @@ fn list_row( right: &str, dot: Option, ) -> f32 { - let h = 60.0; - let hover = ui.interact(rid, x - 12.0, y + 2.0, w + 24.0, h - 4.0, true); + let h = 64.0; + let hover = ui.interact(rid, x - 16.0, y + 2.0, w + 32.0, h - 4.0, true); let sel = ui.tween(rid ^ 0x5e1ec7, if selected { 1.0 } else { 0.0 }, t::quick()); ui.rounded( - x - 12.0, - y + 4.0, - w + 24.0, - h - 8.0, - t::RADIUS, - color::with_alpha(color::HOVER, 0.7 * hover), + x - 16.0, + y + 3.0, + w + 32.0, + h - 6.0, + t::RADIUS_PLATE, + color::with_alpha(color::RAISED, (0.7 * hover).max(sel)), ); - ui.rounded( - x - 12.0, - y + 4.0, - w + 24.0, - h - 8.0, - t::RADIUS, - color::with_alpha(color::RAISED, sel), + ui.row_index += 1; + let n = format!("{:02}", ui.row_index); + ui.text( + Face::Mono, + t::MICRO, + x, + y + 15.0, + color::mix(color::FAINT, color::TEXT, sel), + &n, ); - ui.border( - x - 12.0, - y + 4.0, - w + 24.0, - h - 8.0, - t::RADIUS, - color::with_alpha(color::BORDER, sel), - ); - let mut tx = x; + let mut tx = x + t::INDEX; if let Some(dot) = dot { - ui.rounded(x, y + 17.0, 6.0, 6.0, 3.0, dot); + ui.rounded(tx, y + 19.0, 6.0, 6.0, 3.0, dot); tx += 16.0; } - let title = ui.fit(Face::Medium, BODY, title, w - 200.0); - ui.text(Face::Medium, BODY, tx, y + 10.0, color::TEXT, &title); - let meta = ui.fit(Face::Regular, SMALL, meta, w - 200.0); - ui.text(Face::Regular, SMALL, tx, y + 31.0, color::MUTED, &meta); - ui.text_right(Face::Regular, SMALL, x + w, y + 21.0, color::FAINT, right); + let title = ui.fit(Face::Medium, t::LARGE + 2.0, title, w - 240.0); + ui.text( + Face::Medium, + t::LARGE + 2.0, + tx, + y + 10.0, + color::TEXT, + &title, + ); + let meta = ui.fit(Face::Regular, SMALL, meta, w - 240.0); + ui.text(Face::Regular, SMALL, tx, y + 35.0, color::FAINT, &meta); + let right = right.to_uppercase(); + ui.text_right(Face::Mono, t::MICRO, x + w, y + 25.0, color::FAINT, &right); ui.divider(x, y + h, w); h } -/// An empty list: a serif line and a hint. +/// An empty list: a short line in heading type and a hint. fn empty(ui: &mut Ui, x: f32, y: f32, title: &str, hint: &str) { - ui.text_line(Face::Display, 22.0, 30.0, x, y + 32.0, color::TEXT, title); - ui.text(Face::Regular, BODY, x, y + 66.0, color::MUTED, hint); + ui.text_line( + Face::Display, + t::HEADING, + 28.0, + x, + y + 32.0, + color::TEXT, + title, + ); + ui.text(Face::Regular, BODY, x, y + 64.0, color::FAINT, hint); } fn worlds_page( @@ -809,7 +830,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { ); ui.divider(x, y + rh, w); } - Screen::Disconnected { reason } => { + Screen::Disconnected { reason, retry } => { let mut y = header( ui, x, @@ -821,8 +842,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { // The launcher's error note: a danger dot beside the message. let lines = wrap(ui, reason, w - 40.0); let box_h = 24.0 + lines.len() as f32 * 19.0; - ui.rounded(x, y, w, box_h, t::RADIUS, color::RAISED); - ui.border(x, y, w, box_h, t::RADIUS, color::BORDER); + ui.rounded(x, y, w, box_h, t::RADIUS_PLATE, color::RAISED); ui.rounded(x + 12.0, y + 18.0, 6.0, 6.0, 3.0, color::DANGER); for (i, line) in lines.iter().enumerate() { ui.text_line( @@ -836,6 +856,12 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { ); } y += box_h + 16.0; + if let Some(r) = retry { + // Auto-reconnect's countdown, with a way out. + let text = r.text(std::time::Instant::now()); + ui.text_line(Face::Regular, BODY, 19.0, x, y, color::MUTED, &text); + y += 19.0 + 12.0; + } let bw = ui.button_width("Back to servers", false); ui.button( BACK, @@ -844,6 +870,16 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { Kind::Secondary, true, ); + if retry.is_some() { + let cw = ui.button_width("Cancel reconnecting", false); + ui.button( + CANCEL_RETRY, + [x + bw + 8.0, y, cw, CONTROL], + "Cancel reconnecting", + Kind::Ghost, + true, + ); + } } } } @@ -882,44 +918,28 @@ pub mod pause { let (w, h) = (ui.w, ui.h); let p = t::ease_out_quint(opened.elapsed().as_secs_f32() / t::move_()); ui.opacity = p; - ui.atmosphere(0.35, 1.0); + ui.atmosphere(horizon_theme::VEIL, 1.0); ui.offset = (-16.0 * (1.0 - p), 0.0); - ui.fill(0.0, 0.0, SIDEBAR, h, color::with_alpha(color::SIDEBAR, 0.8)); - ui.vline(SIDEBAR - 1.0, 0.0, h, color::BORDER); - ui.text_line( - Face::Display, - 22.0, - 30.0, - 22.0, - 16.0, - color::TEXT, - "Horizon", - ); + ui.sidebar_frame("Horizon"); ui.sidebar_list( id("pause.nav", 0), 12.0, - 66.0, + 72.0, SIDEBAR - 24.0, &["Game", "Advancements", "Statistics", "Options"], 0, ); - ui.text( - Face::Regular, - SMALL, - 22.0, - h - 12.0 - 18.0, - color::FAINT, - "Horizon 26.3", - ); + ui.caps(24.0, h - 12.0 - 18.0, color::FAINT, "Horizon 26.3"); ui.offset = (0.0, 8.0 * (1.0 - p)); let x = SIDEBAR + 48.0; let cw = (w - x - 48.0).min(760.0); - let mut y = 36.0; - ui.text(Face::Medium, SMALL, x, y, color::FAINT, "Game paused"); - y += 22.0; + let mut y = 36.0 + 28.0; + ui.caps(x, y, color::FAINT, "Game paused"); + y += 24.0; + let line = (t::HERO * 1.1).round(); let title = ui.fit(Face::Display, t::HERO, world, cw); - ui.text_line(Face::Display, t::HERO, 58.0, x, y, color::TEXT, &title); - y += 58.0 + 24.0; + ui.text_line(Face::Display, t::HERO, line, x, y, color::TEXT, &title); + y += line + 32.0; let bw = ui.button_width("Back to game", true).max(120.0); ui.button( act(0), @@ -936,7 +956,8 @@ pub mod pause { Kind::Secondary, true, ); - y += CONTROL_LARGE + 24.0; + y += CONTROL_LARGE + 32.0; + ui.row_index = 0; ui.divider(x, y, cw); let rh = ui.row( x, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ddeda8208..46a1d09e2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,6 +34,7 @@ mod dragon; mod enchant_effects; mod end; mod explosion; +mod extras; mod fangs; mod fireworks; mod fishing; @@ -129,7 +130,7 @@ use horizon_client::{ containers::{BlockEntity, Providers}, crafting::Recipes, creative::{Creative, Names}, - entities::{Arrow, Experience, ExperienceOrb, ItemEntity}, + entities::{Experience, ExperienceOrb, ItemEntity}, environment::Environment, gfx::{Frame, Renderer}, hud::{HudAtlas, HudBatch, rgba}, @@ -557,6 +558,8 @@ impl LevelAccess for GameLevel<'_> { #[derive(Clone, Debug)] struct FallingBlock { state: BlockStateId, + /// `DATA_START_POS`: spawn position used to select weighted block models. + start_pos: BlockPos, position: Vec3, previous: Vec3, velocity: Vec3, @@ -731,7 +734,6 @@ struct Game<'a> { /// A new player's spawn search, while its candidates' chunks load. player_spawn: Option, mobs: Vec, - arrows: Vec, creatures: creatures::Creatures, sculk: sculk::SculkState, raiding: raids::Raiding, @@ -832,6 +834,8 @@ struct Game<'a> { armor_stand_assets: armor_stands::ArmorStandAssets, boats: Vec, boat_models: boats::BoatModels, + /// EndCrystalModel's baked layer. + crystal_model: Option, carts: Vec, /// Songs playing from jukeboxes (tracked sound handles). jukebox_sounds: HashMap<(i32, i32, i32), u64>, @@ -884,6 +888,8 @@ struct Game<'a> { pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, /// Recent frame times for the performance overlay. frame_graph: horizon_client::perf_overlay::FrameGraph, + /// Horizon's extras (zoom, FPS counter, keystrokes): `game/extras.rs`. + extras: extras::ExtrasState, /// Meshed sections waiting for an upload budget (Horizon settings). pending_uploads: Vec<((i32, i32, i32), horizon_client::mesher::SectionMesh)>, /// This frame's view frustum, for culling entities and block entities. @@ -1674,6 +1680,11 @@ impl Game<'_> { LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } + LevelEvent::LevelEvent { + id: 2015, + pos, + data, + } => self.dragon_egg_particles([pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id: 2013, pos, @@ -1744,6 +1755,7 @@ impl Game<'_> { ); self.falling.push(FallingBlock { state, + start_pos: pos, position: p, previous: p, velocity: Vec3::ZERO, @@ -3105,6 +3117,7 @@ impl Game<'_> { if running { horizon_client::spans::time("entity_portals", || self.handle_entity_portals()); horizon_client::spans::time("tick_items", || self.tick_items()); + horizon_client::spans::time("touch_arrows", || self.touch_arrows()); } horizon_client::spans::time("spawn_loaded_entities", || self.spawn_loaded_entities()); if running { @@ -3243,7 +3256,8 @@ impl Game<'_> { x_rot_o: self.pitch, y_rot_o: self.yaw, }; - rotation.turn(xo, yo); + let zoom = self.zoom_turn_scale(); + rotation.turn(xo * zoom, yo * zoom); self.yaw = rotation.y_rot; self.pitch = rotation.x_rot; } @@ -3325,6 +3339,9 @@ impl Game<'_> { self.draw_options(&mut batch); return batch; } + if let Some(title) = &mut self.title { + title.poll_backup(); + } if let Some(title) = &self.title { if horizon_client::ui_theme::horizon() { let fade = self.backdrop_fade(); @@ -3364,11 +3381,15 @@ impl Game<'_> { self.draw_spyglass(&mut batch); // Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth / // extractVehicleHealth and the experience bar, laid out by hud_layout. - // Horizon has no attack cooldown yet: the strength is always full. let indicator = self.settings.attack_indicator; + 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()); if self.camera_type.first_person() && !spectator { - let attack = (indicator == 1).then_some(1.0); - let draws = hud_layout::crosshair(wi, hi, attack, false); + let attack = (indicator == 1).then_some(strength); + let full = attack.is_some_and(|a| { + hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) + }); + let draws = hud_layout::crosshair(wi, hi, attack, full); hud_layout::paint(&mut batch, &self.res.atlas, &draws); } if !spectator { @@ -3378,7 +3399,7 @@ impl Game<'_> { offhand: self.offhand.is_some(), slots: std::array::from_fn(|i| self.inventory[i].as_ref().map(|_| 0.0)), offhand_pop: 0.0, - attack: (indicator == 2).then_some(1.0), + attack: (indicator == 2).then_some(strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); hud_layout::paint(&mut batch, &self.res.atlas, &draws); @@ -3398,6 +3419,7 @@ impl Game<'_> { self.draw_effect_icons(&mut batch); // Hud: the action bar and titles draw over the hotbar (nextStratum). self.draw_boss_bars(&mut batch); + self.draw_extras(&mut batch); } // Hud.extractSleepOverlay, under the sidebar, titles and chat. if let Some((_, ticks)) = self.sleeping { @@ -4911,56 +4933,6 @@ impl Game<'_> { self.guest_model_geometry(camera, alpha, &mut out); self.fangs_geometry(camera, alpha, &mut out); self.name_tag_geometry(camera, alpha, &mut out); - // Arrows: two crossed quads along the flight direction. - if let Some(r) = self - .res - .atlas - .sprites - .get("entity/projectiles/arrow") - .copied() - { - for a in &self.arrows { - let p = glam::DVec3::new( - a.previous.x + (a.position.x - a.previous.x) * alpha, - a.previous.y + (a.position.y - a.previous.y) * alpha, - a.previous.z + (a.position.z - a.previous.z) * alpha, - ) - camera; - let dir = glam::Vec3::new( - a.velocity.x as f32, - a.velocity.y as f32, - a.velocity.z as f32, - ) - .normalize_or(glam::Vec3::X); - let side = dir.cross(glam::Vec3::Y).normalize_or(glam::Vec3::Z) * 0.08; - let up = dir.cross(side).normalize_or(glam::Vec3::Y) * 0.08; - let c = p.as_vec3(); - let (u1, v1) = ( - r.u0 + (r.u1 - r.u0) * 0.5, - r.v0 + (r.v1 - r.v0) * (5.0 / 32.0), - ); - for off in [side, up] { - let q = [ - c - dir * 0.25 - off, - c + dir * 0.25 - off, - c + dir * 0.25 + off, - c - dir * 0.25 + off, - ]; - for (v, uv) in q - .iter() - .zip([[r.u0, v1], [u1, v1], [u1, r.v0], [r.u0, r.v0]]) - { - out.push(Vertex { - normal: [0; 4], - pos: v.to_array(), - uv, - layer: 0, - color: 0xFFFF_FFFF, - light: 240 | 240 << 8, - }); - } - } - } - } // Entity shadows (EntityRenderer.extractShadow). if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; @@ -5122,12 +5094,9 @@ impl Game<'_> { } } } - // Falling blocks: a unit cube with the block's texture. - for f in self.falling.clone() { - let Some((sprite, tint)) = self.particle_sprite(f.state) else { - continue; - }; - let Some(r) = self.res.atlas.sprites.get(&sprite).copied() else { + // Falling blocks use their baked model, including non-cubic shapes. + for f in &self.falling { + let Some((_, tint)) = self.particle_sprite(f.state) else { continue; }; let p = glam::DVec3::new( @@ -5142,50 +5111,17 @@ impl Game<'_> { f.position.z.floor() as i32, ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); - let v = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x, y, z); - let faces = [ - ( - [v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)], - 1.0, - ), - ( - [v(0., 0., 0.), v(1., 0., 0.), v(1., 0., 1.), v(0., 0., 1.)], - 0.5, - ), - ( - [v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)], - 0.8, - ), - ( - [v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)], - 0.8, - ), - ( - [v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)], - 0.6, - ), - ( - [v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)], - 0.6, - ), - ]; - for (corners, shade) in faces { - let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32; - let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16); - for (p, uv) in - corners - .iter() - .zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) - { - out.push(Vertex { - normal: [0; 4], - pos: p.to_array(), - uv, - layer: 0, - color, - light: packed, - }); - } + let start = out.len(); + self.block_model_vertices( + f.state, + f.start_pos, + glam::Mat4::from_translation(o), + packed, + &mut out, + ); + let tint = horizon_client::mobs::render::abgr(tint); + for vertex in &mut out[start..] { + vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint); } } self.tnt_geometry(camera, alpha, &mut out); @@ -5889,7 +5825,7 @@ impl Game<'_> { self.mobs.clear(); self.creatures.reset_trader(); self.portals = Default::default(); - self.arrows.clear(); + self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); self.orbs.clear(); @@ -6041,7 +5977,7 @@ impl Game<'_> { self.falling.clear(); self.tnts.clear(); self.mobs.clear(); - self.arrows.clear(); + self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); self.orbs.clear(); @@ -6191,7 +6127,7 @@ impl Game<'_> { self.world = World::new(self.res.facts.air, 0); self.player = None; self.mobs.clear(); - self.arrows.clear(); + self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); self.screen = Screen::Playing; @@ -6989,6 +6925,25 @@ impl Game<'_> { p, Some(horizon_client::mobs::Who::Player), ); + // ProjectileWeaponItem.useAmmo: creative and Infinity draw without + // using the ammo, so the arrow is CREATIVE_ONLY; else setOwner(player) + // lets it be picked up. + let ammo = arrow_slot + .and_then(|i| self.inventory[i].clone()) + .unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1)); + if let Some(a) = arrow.arrow.as_mut() { + a.set_item(&horizon_client::arrows::drawn_ammo( + &ammo, + self.creative || infinity, + )); + a.set_owner(Some(horizon_client::mobs::Who::Player)); + } + // Flame: the arrow is spawned burning (EnchantmentHelper.onProjectileSpawned). + if let Some(seconds) = self.bow_projectile_ignite() + && let Some(a) = arrow.arrow.as_mut() + { + a.ignite_for_seconds(seconds); + } let (velocity, on_ground) = self .player .as_ref() @@ -7195,6 +7150,7 @@ impl Game<'_> { assets.sprite_size, assets.sprite_minimum_size, assets.texture_layers, + &assets.sprite_mips, &assets.animations, ( &self.res.atlas.pixels, @@ -7213,6 +7169,10 @@ impl Game<'_> { Ok(renderer) } fn apply_settings(&mut self) { + if let Some(r) = &self.renderer { + self.settings + .clamp_gui_scale([r.config.width as i32, r.config.height as i32]); + } self.streaming.radius = self.settings.render_distance; self.streaming.biome_blend = self.settings.biome_blend; self.streaming.smooth_lighting = self.settings.smooth_lighting; @@ -8455,9 +8415,16 @@ impl ApplicationHandler for Game<'_> { // The Window constructor: created fullscreen when options.txt says so. let fullscreen = self.settings.fullscreen; self.fullscreen = horizon_client::window::FullscreenState::new(fullscreen); + let attributes = Window::default_attributes() + .with_title("Horizon") + .with_window_icon(horizon_client::window::icon()); + // Wayland names the window by its app id, which the horizon.desktop entry matches. + #[cfg(target_os = "linux")] + let attributes = winit::platform::wayland::WindowAttributesExtWayland::with_name( + attributes, "horizon", "horizon", + ); let window = match event_loop.create_window( - Window::default_attributes() - .with_title("Horizon") + attributes .with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0)) .with_fullscreen(fullscreen.then_some(winit::window::Fullscreen::Borderless(None))), ) { @@ -8477,6 +8444,7 @@ impl ApplicationHandler for Game<'_> { } } self.window = Some(window); + self.apply_settings(); self.previous = Instant::now(); } fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { @@ -8603,8 +8571,20 @@ impl ApplicationHandler for Game<'_> { }) * wheel_sensitivity }; let d = scaled(raw_y) as f32; + if let Some(title) = &mut self.title + && !horizon_client::ui_theme::horizon() + { + let size = self + .window + .as_ref() + .map(|w| w.inner_size()) + .unwrap_or_default(); + let batch = HudBatch::new([size.width, size.height]); + title.scroll_worlds(d, self.cursor, (batch.width, batch.height)); + } if self.screen == Screen::Playing && self.player.is_some() + && !self.extras_scroll(d) && let Some((wheel, _)) = self.mouse .on_scroll(raw_x, raw_y, discrete, wheel_sensitivity) @@ -8656,13 +8636,19 @@ impl ApplicationHandler for Game<'_> { .unwrap_or([1, 1]); let mut b = HudBatch::new(size); let atlas = &self.res.atlas; - let action = self.title.as_mut().map_or(Action::None, |t| { + let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| { if horizon_client::ui_theme::horizon() { - t.click_horizon(atlas, &mut b, self.cursor.0, self.cursor.1) + ( + t.click_horizon(atlas, &mut b, self.cursor.0, self.cursor.1), + false, + ) } else { t.click(self.cursor.0, self.cursor.1, (b.width, b.height)) } }); + if sound { + self.audio.play_button_click(); + } match action { Action::Quit => event_loop.exit(), Action::Options => self.open_options(true), @@ -8708,6 +8694,7 @@ impl ApplicationHandler for Game<'_> { self.capture(true); return Ok(()); } + self.extras_mouse(button, pressed); match self.settings.keys.translate_mouse(button) { Some(Err(b)) => self.play_mouse(b, pressed)?, Some(Ok(k)) if pressed => { @@ -8740,11 +8727,17 @@ impl ApplicationHandler for Game<'_> { Screen::Creative if button == MouseButton::Left => { self.creative_screen.release(); } - Screen::Paused if pressed && self.pause_menu => self.pause_click()?, + Screen::Paused + if pressed && button == MouseButton::Left && self.pause_menu => + { + self.pause_click()? + } Screen::WorldOptions if pressed && button == MouseButton::Left => { self.world_options_click() } - Screen::Dead if pressed => self.death_click()?, + Screen::Dead if pressed && button == MouseButton::Left => { + self.death_click()? + } Screen::Advancements if button == MouseButton::Left => { let size = self .renderer @@ -8846,6 +8839,11 @@ impl ApplicationHandler for Game<'_> { return Ok(()); } match event.physical_key { + PhysicalKey::Code(KeyCode::Enter | KeyCode::NumpadEnter) => { + if let Some(t) = self.title.as_mut() { + t.confirm_edit(); + } + } PhysicalKey::Code(KeyCode::Backspace) => self.title_edit(None, true), PhysicalKey::Code(KeyCode::Tab) => { if let Some(t) = self.title.as_mut() { @@ -8865,6 +8863,7 @@ impl ApplicationHandler for Game<'_> { let PhysicalKey::Code(key) = event.physical_key else { return Ok(()); }; + self.extras_key(key, event.state == ElementState::Pressed, event.repeat); // key.smoothCamera toggles the cinematic camera. if self.screen == Screen::Playing && event.state == ElementState::Pressed @@ -8929,6 +8928,8 @@ impl ApplicationHandler for Game<'_> { self.sprint_report(&report); } } + self.extras_frame(elapsed); + self.extras_retry()?; self.apply_mouse_look(); self.pad_look(elapsed.as_secs_f32()); self.advance_flight(); @@ -9321,7 +9322,6 @@ pub fn run() -> Result<()> { spawn_spiral: Default::default(), player_spawn: None, mobs: Vec::new(), - arrows: Vec::new(), creatures: Default::default(), sculk: Default::default(), raiding: Default::default(), @@ -9392,6 +9392,7 @@ pub fn run() -> Result<()> { armor_stand_assets: armor_stands::ArmorStandAssets::load(&root), boats: Vec::new(), boat_models: boats::BoatModels::load(&root), + crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), carts: Vec::new(), jukebox_sounds: HashMap::new(), bolts: Vec::new(), @@ -9436,6 +9437,7 @@ pub fn run() -> Result<()> { view_frustum: None, pending_uploads: Vec::new(), frame_graph: Default::default(), + extras: Default::default(), sky_darken_memo: Default::default(), persist: Default::default(), remote: None, diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 8b1b8071e..e2b02d199 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -490,6 +490,22 @@ impl Game<'_> { "focus": match focus { 0 => "name", 1 => "seed", _ => "none" }, "creative": creative, }), + Mode::Edit { + world, + name, + focused, + } => { + json!({ "mode": "edit-world", "folder": world.folder, "fields": { "name": name }, "focus": if *focused { "name" } else { "none" } }) + } + Mode::Backup { world, .. } => { + json!({ "mode": "creating-backup", "folder": world.folder }) + } + Mode::Delete { world } => { + json!({ "mode": "delete-world", "folder": world.folder, "name": world.name }) + } + Mode::Error { message, .. } => { + json!({ "mode": "world-operation-error", "message": message }) + } Mode::Multiplayer(_) => json!({ "mode": "multiplayer" }), } } @@ -1312,7 +1328,14 @@ impl Game<'_> { } } } - _ => return Err("--field works on the create-world screen".into()), + horizon_client::title::Mode::Edit { focused, .. } if field == "name" => { + *focused = true + } + _ => { + return Err( + "--field works on the create-world or edit-world screen".into() + ); + } } } if replace { diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 720f56c66..169148dcb 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -7,7 +7,7 @@ use horizon_client::{ gamerules::GameRules, hud::{HudBatch, rgba}, screen_draw::Measure, - text::Text, + text::{ClickEvent, Style, Text}, }; use std::collections::BTreeMap; use winit::{ @@ -78,8 +78,8 @@ pub struct UiState { pub hide_gui: bool, /// Death message key set by the cause of death (e.g. /kill). pub death_cause: Option, - /// File name of an F2 screenshot waiting for its frame. - pub screenshot_message: Option, + /// Path of an F2 screenshot waiting for its frame. + pub screenshot_message: Option, /// The options screens. pub options: horizon_client::options_ui::OptionsUi, /// The prepared resources before resource packs are layered on. @@ -538,14 +538,37 @@ impl Game<'_> { let height = self.renderer.as_ref().map_or(720.0, |r| { HudBatch::new([r.config.width, r.config.height]).height }); - let _ = height; let m = Measure(&self.res.atlas.font); let c = Commands { dispatcher: vanilla::game_dispatcher(), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { - screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64); + if screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64) { + return; + } + } else { + return; + } + match self.ui.chat.click_at( + &self.res.atlas.font, + height as i32, + cursor.0 as f64, + cursor.1 as f64, + ) { + Some(ClickEvent::CopyToClipboard(value)) => { + use horizon_client::clipboard::Clipboard; + self.clipboard.set(&value); + } + Some(ClickEvent::OpenFile(path)) => { + super::packs::open_folder(std::path::Path::new(&path)); + } + Some(ClickEvent::SuggestCommand(command)) => { + if let Some(screen) = self.ui.chat_screen.as_mut() { + screen.suggest_command(&m, &c, &command); + } + } + None => {} } } /// Chat lines over the HUD (focused while the chat screen is open). @@ -745,16 +768,28 @@ impl Game<'_> { let Some(renderer) = self.renderer.as_mut() else { return; }; - renderer.screenshot = Some(dir.join(&name)); - self.ui.screenshot_message = Some(name); + let path = dir.join(name); + renderer.screenshot = Some(path.clone()); + self.ui.screenshot_message = Some(path); } /// After a frame: report a finished F2 screenshot in chat. pub(super) fn finish_screenshot(&mut self, result: &std::result::Result<[u32; 2], String>) { - let Some(name) = self.ui.screenshot_message.take() else { + let Some(path) = self.ui.screenshot_message.take() else { return; }; let message = match result { - Ok(_) => Text::translate("screenshot.success", &[Text::literal(name).underlined()]), + Ok(_) => { + let name = path.file_name().unwrap_or_default().to_string_lossy(); + let link = Text::styled( + name, + Style { + underlined: Some(true), + click: Some(ClickEvent::OpenFile(path.to_string_lossy().into_owned())), + ..Style::default() + }, + ); + Text::translate("screenshot.success", &[link]) + } Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]), }; let focused = self.screen == Screen::Chat; diff --git a/crates/horizon-client/src/game/clipboard.rs b/crates/horizon-client/src/game/clipboard.rs index 6b6b338ab..c28aa900c 100644 --- a/crates/horizon-client/src/game/clipboard.rs +++ b/crates/horizon-client/src/game/clipboard.rs @@ -47,7 +47,7 @@ impl Game<'_> { return; }; if let Some((id, value, max)) = title.focused_field() { - Self::append_shortcut( + let changed = Self::append_shortcut( &mut self.text_selection, &mut self.clipboard, id, @@ -55,6 +55,9 @@ impl Game<'_> { shortcut, max, ); + if changed { + title.search_changed(); + } } } /// Typing or a backspace in an append-only field of the title screens: @@ -66,6 +69,9 @@ impl Game<'_> { let cleared = title .focused_field() .is_some_and(|(id, value, _)| self.text_selection.take(id, value)); + if cleared { + title.search_changed(); + } if backspace { if !cleared { title.backspace(); diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 15d43c80b..e212a4b98 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -109,7 +109,7 @@ impl Game<'_> { let Some(input) = &e.input else { return }; let cursor = e.cursor.min(input.len()); let suggest = Style { - suggest: Some(format!("/{command}")), + click: Some(text::ClickEvent::SuggestCommand(format!("/{command}"))), ..Style::default() }; let mut context = Text::empty(); @@ -228,7 +228,8 @@ impl Game<'_> { .get(i) .map(|o| [o.position.x, o.position.y, o.position.z]), Target::Arrow(i) => self - .arrows + .creatures + .projectiles .get(i) .map(|a| [a.position.x, a.position.y, a.position.z]), Target::Stand(id) => self @@ -392,7 +393,14 @@ impl Game<'_> { ); candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id))); candidates.extend((0..self.orbs.len()).map(Target::Orb)); - candidates.extend((0..self.arrows.len()).map(Target::Arrow)); + candidates.extend( + self.creatures + .projectiles + .iter() + .enumerate() + .filter(|(_, p)| p.arrow.is_some()) + .map(|(i, _)| Target::Arrow(i)), + ); candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id))); candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id))); candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id))); @@ -569,14 +577,7 @@ impl Game<'_> { "difficulty" => self.cmd_difficulty(ctx), "seed" => { let seed = self.level.seed.to_string(); - let green = Style { - color: Some(text::GREEN), - suggest: None, - ..Style::default() - }; - let value = Text::literal("[") - .append(Text::styled(seed.clone(), green)) - .append("]"); + let value = Text::copyable(seed); self.system_message(Text::translate("commands.seed.success", &[value])); Ok(self.level.seed as i32) } @@ -960,7 +961,7 @@ impl Game<'_> { } } Target::Arrow(i) => { - if let Some(a) = self.arrows.get_mut(i) { + if let Some(a) = self.creatures.projectiles.get_mut(i) { a.position = v; a.previous = v; } @@ -1294,8 +1295,13 @@ impl Game<'_> { } } Target::Arrow(i) => { - if i < self.arrows.len() { - self.arrows[i].age = u32::MAX / 2; + if let Some(a) = self + .creatures + .projectiles + .get_mut(i) + .and_then(|p| p.arrow.as_mut()) + { + a.removed = true; } } Target::Stand(id) => self.armor_stands.retain(|a| a.id != id), @@ -1325,7 +1331,9 @@ impl Game<'_> { self.kill_target(t); } self.orbs.retain(|o| o.age < u32::MAX / 2); - self.arrows.retain(|a| a.age < u32::MAX / 2); + self.creatures + .projectiles + .retain(|p| !p.arrow.as_ref().is_some_and(|a| a.removed)); let message = if targets.len() == 1 { Text::translate("commands.kill.success.single", &[names[0].clone()]) } else { @@ -2342,22 +2350,7 @@ impl Game<'_> { &[&poi], ))); }; - let coords = Text::translate( - "chat.coordinates", - &[ - Text::literal(p[0].to_string()), - Text::literal("~"), - Text::literal(p[2].to_string()), - ], - ); - let link = Text::literal("[") - .append(coords) - .append("]") - .with_style(&Style { - color: Some(text::GREEN), - suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])), - ..Style::default() - }); + let link = Text::teleport_link(p[0], None, p[2]); let (dx, dz) = (p[0] - from[0], p[2] - from[2]); let distance = ((dx * dx + dz * dz) as f32).sqrt().floor() as i32; let shown = if poi.starts_with('#') { @@ -2413,15 +2406,7 @@ impl Game<'_> { } else { biome.clone() }; - let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]); - let link = Text::literal("[") - .append(coords) - .append("]") - .with_style(&Style { - color: Some(text::GREEN), - suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])), - ..Style::default() - }); + let link = Text::teleport_link(p[0], Some(p[1]), p[2]); let distance = (d2 as f32).sqrt().floor() as i32; self.feedback(Text::translate( "commands.locate.biome.success", @@ -2449,22 +2434,7 @@ impl Game<'_> { &[&s], ))); }; - let coords = Text::translate( - "chat.coordinates", - &[ - Text::literal(p[0].to_string()), - Text::literal("~"), - Text::literal(p[2].to_string()), - ], - ); - let link = Text::literal("[") - .append(coords) - .append("]") - .with_style(&Style { - color: Some(text::GREEN), - suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])), - ..Style::default() - }); + let link = Text::teleport_link(p[0], None, p[2]); let (dx, dz) = (f64::from(p[0] - from[0]), f64::from(p[2] - from[2])); let distance = (dx * dx + dz * dz).sqrt().floor() as i32; let shown = if s.starts_with('#') { diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 3398aa7dd..a10fff3bd 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -109,9 +109,18 @@ impl Game<'_> { } Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()), Target::Arrow(i) => { - let a = self.arrows.get(i)?; - let owner = if a.from_player { player_uuid } else { None }; - entity_nbt::arrow_to_nbt(a, random_uuid(), owner) + let p = self.creatures.projectiles.get(i)?; + let owner = if p.owner == Some(horizon_client::mobs::Who::Player) { + player_uuid + } else { + None + }; + let in_block = p + .arrow + .as_ref() + .and_then(|a| a.last_state) + .map(|s| self.state_to_nbt(s)); + entity_nbt::arrow_to_nbt(p, random_uuid(), owner, in_block, None)? } }) } diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index 6429b8089..ab41596ee 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -320,10 +320,10 @@ impl Game<'_> { let color = self.waypoint_icon(*t).color.unwrap_or(-1) as u32 & 0xFF_FFFF; let style = Style { color: Some(color), - suggest: Some(format!( + click: Some(text::ClickEvent::SuggestCommand(format!( "/execute in {dimension} run tp @s {} {} {}", pos[0], pos[1], pos[2] - )), + ))), hover: Some(Box::new(Text::translate("chat.coordinates.tooltip", &[]))), ..Style::default() }; @@ -701,7 +701,7 @@ impl Game<'_> { let mut t = Text::translate("chat.square_brackets", &[inner]); if let Some(cmd) = run { t = t.with_style(&Style { - suggest: None, + click: None, ..Style::default() }); let _ = cmd; diff --git a/crates/horizon-client/src/game/commands/misc.rs b/crates/horizon-client/src/game/commands/misc.rs index 2c653ddf2..1dff6f706 100644 --- a/crates/horizon-client/src/game/commands/misc.rs +++ b/crates/horizon-client/src/game/commands/misc.rs @@ -328,7 +328,7 @@ impl Game<'_> { let message = self.expand_selectors(&raw); let hover = text::Style { hover: Some(Box::new(Text::translate("chat.type.team.hover", &[]))), - suggest: Some("/teammsg ".into()), + click: Some(text::ClickEvent::SuggestCommand("/teammsg ".into())), ..text::Style::default() }; let team_name = team.formatted_display_name().with_style(&hover); diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index bc584990d..567dd3a72 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -163,6 +163,12 @@ impl Game<'_> { self.debug_key(key, KeyAction::Release); } } + // The zoom extra sees the key as the keyboard hook does. + let action = arg(2)?; + self.extras_key(physical, action != "up", false); + if action == "tap" { + self.extras_key(physical, false, false); + } // Text screens consume raw presses; releases follow key binds. let typing = matches!(self.screen, Screen::Chat | Screen::Options); let key = if typing && arg(2)? != "up" { @@ -228,9 +234,17 @@ impl Game<'_> { .into()); } match arg(2)? { - "down" => self.play_mouse(button, true)?, - "up" => self.play_mouse(button, false)?, + "down" => { + self.extras_mouse(button, true); + self.play_mouse(button, true)? + } + "up" => { + self.extras_mouse(button, false); + self.play_mouse(button, false)? + } "click" => { + self.extras_mouse(button, true); + self.extras_mouse(button, false); self.play_mouse(button, true)?; self.play_mouse(button, false)?; } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 5a161b7d0..c262b34f4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -98,6 +98,60 @@ impl ProjectileWorld for ProjWorld<'_, '_> { .full_collision } } +/// `FlameFeatureRenderer`: fire quads stacked up a burning entity's box, +/// turned to the camera around Y, at full block light. `at` is the entity's +/// feet relative to the camera. +fn flame_geometry( + atlas: &horizon_client::hud::HudAtlas, + at: glam::Vec3, + width: f32, + height: f32, + camera_yaw: f32, + light: u8, + out: &mut Vec, +) { + let (Some(fire0), Some(fire1)) = ( + atlas.sprites.get("block/fire_0").copied(), + atlas.sprites.get("block/fire_1").copied(), + ) else { + return; + }; + let s = width * 1.4; + let mut h = height / s; + // Mth.rotationAroundAxis(Y, camera.orientation): the camera's turn about Y. + let turn = glam::Mat3::from_rotation_y(std::f32::consts::PI - camera_yaw.to_radians()); + let lift = 0.3 - (h as i32) as f32 * 0.02; + let packed = (u32::from(light >> 4) * 16) | ((15 * 16) << 8); + let (mut r, mut yo, mut zo, mut ss) = (0.5f32, 0.0f32, 0.0f32, 0); + while h > 0.0 { + let tex = if ss % 2 == 0 { fire0 } else { fire1 }; + let (mut u0, v0, mut u1, v1) = (tex.u0, tex.v0, tex.u1, tex.v1); + if ss / 2 % 2 == 0 { + std::mem::swap(&mut u0, &mut u1); + } + for (x, y, uv) in [ + (-r, -yo, [u1, v1]), + (r, -yo, [u0, v1]), + (r, 1.4 - yo, [u0, v0]), + (-r, 1.4 - yo, [u1, v0]), + ] { + let p = at + turn * glam::Vec3::new(x, y, zo + lift) * s; + out.push(Vertex { + normal: [0; 4], + pos: p.to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light: packed, + }); + } + h -= 0.45; + yo -= 0.45; + r *= 0.9; + zo -= 0.03; + ss += 1; + } +} pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { m.seen(player) } @@ -323,6 +377,7 @@ impl Game<'_> { world: &self.world, registry: self.res.assets.registry, facts: &self.res.facts, + movement: &self.motion.blocks, collision: self.collision, data: &self.res.mob_data, player: self.player_view(), @@ -680,6 +735,7 @@ impl Game<'_> { pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { + MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at), MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { self.audio @@ -1369,11 +1425,68 @@ impl Game<'_> { let _ = player.hurt(&self.motion.health, self.world.health_rules, id, amount); } } + /// `Player.aiStep` touching arrows in its box grown by (1, 0.5, 1): + /// `AbstractArrow.playerTouch`, then `Player.take`'s pickup sound at the + /// arrow (`ClientPacketListener.handleTakeItemEntity`). + pub(super) fn touch_arrows(&mut self) { + use horizon_client::arrows::Touch; + let Some(p) = self.player.as_ref() else { + return; + }; + if p.health.dead_or_dying() || self.spectator() { + return; + } + let w = f64::from(p.dimensions.width) / 2.0; + let reach = Aabb::new( + Vec3::new(p.position.x - w, p.position.y, p.position.z - w), + Vec3::new( + p.position.x + w, + p.position.y + f64::from(p.dimensions.height), + p.position.z + w, + ), + ) + .inflate(Vec3::new(1.0, 0.5, 1.0)); + // Player.hasInfiniteMaterials. + let creative = self.creative; + let mut projectiles = std::mem::take(&mut self.creatures.projectiles); + projectiles.retain(|shot| { + let Some(a) = shot.arrow.as_ref().filter(|a| !a.removed) else { + return true; + }; + let at = shot.position; + let bounds = Aabb::new( + Vec3::new(at.x - 0.25, at.y, at.z - 0.25), + Vec3::new(at.x + 0.25, at.y + 0.5, at.z + 0.25), + ); + if !bounds.intersects(reach) { + return true; + } + let taken = match a.player_touch(creative) { + Touch::Ignore => false, + Touch::Take => true, + // Inventory.add: a creative player takes what does not fit. + Touch::Give(stack) => self.give(stack).is_none() || creative, + }; + if taken { + let r = &mut self.world.random; + let pitch = (r.next_float() - r.next_float()) * 1.4 + 2.0; + self.audio.play( + "minecraft:entity.item.pickup", + Some([at.x, at.y, at.z]), + 0.2, + pitch, + ); + } + !taken + }); + self.creatures.projectiles = projectiles; + } + fn tick_projectiles(&mut self) -> Result<()> { let mut projectiles = std::mem::take(&mut self.creatures.projectiles); let mut hits = Vec::new(); - let mut trails = Vec::new(); let mut deflections: Vec<[f64; 3]> = Vec::new(); + let mut arrow_events = Vec::new(); { let mut targets: Vec<(Who, Aabb)> = self .mobs @@ -1406,10 +1519,33 @@ impl Game<'_> { self.world.random.next_float() }; let w = self.mob_world_base(&[]); + // Level.isRainingAt: raining, open to the sky (the biome's + // precipitation is not checked here). + let (raining, world) = (w.raining, w.world); + let rain = move |p: BlockPos| raining && world.light(p.x, p.y, p.z) >> 4 == 15; + let scene = horizon_client::arrows::ArrowScene { + world: w.world, + registry: w.registry, + facts: w.facts, + collision: w.collision, + fluids: &self.motion.fluids, + raining: &rain, + mob_griefing: self.ui.rules.bool("mob_griefing"), + tnt_explodes: self.ui.rules.bool("tnt_explodes"), + }; + // Arrows also hit minecarts (VehicleEntity is pickable). + let mut arrow_targets = targets.clone(); + arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds()))); let pw = ProjWorld { w: &w, targets }; projectiles.retain_mut(|p| { - trails.extend(p.arrow_trail(pw.in_water(p.position))); - let (keep, hit) = p.tick(&pw); + let (keep, hit) = if p.arrow.is_some() { + horizon_client::arrows::tick(p, &scene, &arrow_targets) + } else { + p.tick(&pw) + }; + if let Some(a) = p.arrow.as_mut() { + arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); + } let wind = matches!( p.kind, ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge @@ -1423,6 +1559,9 @@ impl Game<'_> { && breezes.contains(&id) { super::wind::reverse(p, jitter); + if let Some(a) = p.arrow.as_mut() { + a.removed = false; + } deflections.push([at.x, at.y, at.z]); return true; } @@ -1444,23 +1583,97 @@ impl Game<'_> { keep }); } - for (ty, at, velocity) in trails { - self.particles.add( - &horizon_client::particles::ParticleOptions::simple(ty), - at, - velocity, - ); - } for at in deflections { self.audio .play("minecraft:entity.breeze.deflect", Some(at), 1.0, 1.0); } + for (at, event) in arrow_events { + self.arrow_event(at, event); + } self.creatures.projectiles.append(&mut projectiles); for (p, hit) in hits { self.projectile_hit(&p, hit)?; } Ok(()) } + /// What an arrow's tick asked for: its particles and sounds. + fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) { + use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction}; + use horizon_client::particles::{ParticleOptions, ParticleType}; + let kind = |k| match k { + ArrowParticle::Bubble => ParticleType::Bubble, + ArrowParticle::Crit => ParticleType::Crit, + ArrowParticle::Splash => ParticleType::Splash, + }; + match event { + ArrowEvent::Particle { + kind: k, + position, + velocity, + } => self.particles.add( + &ParticleOptions::simple(kind(k)), + [position.x, position.y, position.z], + [velocity.x, velocity.y, velocity.z], + ), + ArrowEvent::Sound { + sound, + volume, + pitch, + } => { + let name = match sound { + ArrowSound::Splash => "minecraft:entity.generic.splash", + ArrowSound::HitGround => "minecraft:entity.arrow.hit", + ArrowSound::Extinguish => "minecraft:entity.generic.extinguish_fire", + }; + self.audio + .play(name, Some([at.x, at.y, at.z]), volume, pitch); + } + ArrowEvent::BubbleColumnParticles { pos } => { + // Entity.sendBubbleColumnParticles: the level random places them. + for _ in 0..2 { + let r = &mut self.world.random; + let splash = [ + f64::from(pos.x) + r.next_double(), + f64::from(pos.y + 1), + f64::from(pos.z) + r.next_double(), + ]; + let bubble = [ + f64::from(pos.x) + r.next_double(), + f64::from(pos.y + 1), + f64::from(pos.z) + r.next_double(), + ]; + self.particles.send_particles( + &ParticleOptions::simple(ParticleType::Splash), + splash, + [0.0; 3], + 1.0, + 1, + ); + self.particles.send_particles( + &ParticleOptions::simple(ParticleType::Bubble), + bubble, + [0.0, 0.01, 0.0], + 0.2, + 1, + ); + } + } + ArrowEvent::Block { pos, reaction } => match reaction { + BlockReaction::PrimeTnt => { + self.spawn_primed_tnt(pos, false); + self.with_level(|b, level, ticks| b.remove_block(level, ticks, pos, false)); + let _ = self.process_level_events(); + } + BlockReaction::Light(lit) => { + let _ = self.level_set([pos.x, pos.y, pos.z], lit); + } + }, + ArrowEvent::SplashEvent => { + self.projectile_event("minecraft:splash", None, [at.x, at.y, at.z]); + } + ArrowEvent::ShootEvent => {} + } + } fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> { self.combat.projectile_owner = match p.owner { Some(Who::Mob(id)) => Some(id), @@ -1489,6 +1702,25 @@ impl Game<'_> { self.hit_special(id, amount, p.owner == Some(Who::Player)); return Ok(()); } + if let ( + ProjectileKind::Arrow { .. }, + Hit::Entity { + who: Who::Mob(id), .. + }, + ) = (&p.kind, hit) + && let Some(i) = self.carts.iter().position(|c| c.id == id) + { + // AbstractArrow.onHitEntity on a minecart. + let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage; + let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire()); + let creative = p.owner == Some(Who::Player) && self.creative; + self.arrow_hits_cart(i, amount, p.velocity, burning, creative); + if let Some((sound, volume, pitch)) = arrow_impact_sound(&mut self.world.random, true) { + self.audio + .play(sound, Some([at.x, at.y, at.z]), volume, pitch); + } + return Ok(()); + } let atp = [at.x, at.y, at.z]; // Projectile.onHit: the landing is heard. self.projectile_event("minecraft:projectile_land", p.owner, atp); @@ -1516,7 +1748,8 @@ impl Game<'_> { velocity: [p.velocity.x * k, 0.1, p.velocity.z * k], }])?; } - if p.bonus.flame { + // AbstractArrow.onHitEntity: a burning arrow sets its target alight. + if p.arrow.as_ref().is_some_and(|a| a.on_fire()) { self.handle_mob_events(vec![MobEvent::Ignite { target: who, seconds: 5, @@ -1552,13 +1785,8 @@ impl Game<'_> { self.audio.play(sound, Some(atp), volume, pitch); } } - (ProjectileKind::Arrow { .. }, Hit::Block { .. }) => { - if let Some((sound, volume, pitch)) = - arrow_impact_sound(&mut self.world.random, true) - { - self.audio.play(sound, Some(atp), volume, pitch); - } - } + // AbstractArrow.onHitBlock plays its sound itself (ArrowEvent). + (ProjectileKind::Arrow { .. }, Hit::Block { .. }) => {} (ProjectileKind::Snowball, hit) => { if let Hit::Entity { who: Who::Mob(id), .. @@ -2522,6 +2750,9 @@ impl Game<'_> { 0, out, ); + if a.arrow.as_ref().is_some_and(|s| s.on_fire()) { + flame_geometry(atlas, c, 0.5, 0.5, self.yaw, light, out); + } continue; } // WindChargeRenderer. diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index b2ae95387..335f62785 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -88,8 +88,12 @@ impl Game<'_> { } else { 1 }; + let slot_ammo = self.arrow_slot(); + let ammo = slot_ammo + .and_then(|i| self.inventory[i].clone()) + .unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1)); if !self.creative { - let Some(i) = self.arrow_slot() else { return }; + let Some(i) = slot_ammo else { return }; if let Some(s) = self.inventory[i].as_mut() { s.count -= 1; if s.count == 0 { @@ -97,8 +101,12 @@ impl Game<'_> { } } } + // useAmmo: the extra multishot arrows and creative's are intangible. + let drawn = (0..shots) + .map(|i| horizon_client::arrows::drawn_ammo(&ammo, self.creative || i > 0)) + .collect(); if let Some(bow) = self.inventory[slot].as_mut() { - bow.data_mut().charged = vec![ItemStack::new("minecraft:arrow", 1); shots]; + bow.data_mut().charged = drawn; } let pitch = 1.0 / (self.world.random.next_float() * 0.5 + 1.0) + 0.2; self.audio.play(sounds[2], at, 1.0, pitch); @@ -119,7 +127,7 @@ impl Game<'_> { let spread = if count > 1 { 10.0 } else { 0.0 }; let view = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); let up = glam::DVec3::from_array(view_vector(self.yaw, self.pitch - 90.0)); - for (index, _) in charged.iter().enumerate() { + for (index, ammo) in charged.iter().enumerate() { let angle = if count > 1 { -spread + 2.0 * spread * index as f64 / (count - 1) as f64 } else { @@ -142,6 +150,10 @@ impl Game<'_> { Vec3::new(eye[0], eye[1] - 0.1, eye[2]), Some(Who::Player), ); + if let Some(a) = arrow.arrow.as_mut() { + a.set_item(ammo); + a.set_owner(Some(Who::Player)); + } arrow.shoot(&mut self.world.random, dir.to_array(), 3.15, 1.0); self.creatures.projectiles.push(arrow); self.player_projectile_shot(); diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index f40949ba1..6c50b80ae 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -967,18 +967,7 @@ impl Game<'_> { "minecraft:tipped_arrow" => ProjectileKind::Arrow { base_damage: 2.0, critical: false, - effect: stack - .potion() - .and_then(horizon_client::brewing::potion) - .and_then(|def| { - def.effects - .iter() - .find(|(id, _, _)| { - !horizon_client::brewing::effect(id) - .is_some_and(|e| e.instant) - }) - .map(|(id, duration, _)| (*id, (duration / 8).max(1))) - }), + effect: tipped_effect(&stack), }, "minecraft:fire_charge" | "minecraft:wind_charge" => { // asProjectile aims with the level's random first; the @@ -1001,6 +990,12 @@ impl Game<'_> { _ => ProjectileKind::Snowball, }; let mut shot = Projectile::new(kind, at, None); + // ArrowItem/SpectralArrowItem.asProjectile: dispensed arrows + // may be picked up. + if let Some(a) = shot.arrow.as_mut() { + a.set_item(&one); + a.pickup = horizon_client::arrows::Pickup::Allowed; + } shot.shoot(&mut own, dir, power, uncertainty); self.creatures.projectiles.push(shot); } @@ -2098,3 +2093,16 @@ impl Game<'_> { )) } } +/// A tipped arrow's lasting effect at an eighth of the potion's duration +/// (`Arrow.doPostHurtEffects`). +pub(super) fn tipped_effect(stack: &ItemStack) -> Option<(&'static str, i32)> { + stack + .potion() + .and_then(horizon_client::brewing::potion) + .and_then(|def| { + def.effects + .iter() + .find(|(id, _, _)| !horizon_client::brewing::effect(id).is_some_and(|e| e.instant)) + .map(|(id, duration, _)| (*id, (duration / 8).max(1))) + }) +} diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index a1cf7bfc2..5d1eef394 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1849,7 +1849,7 @@ impl Game<'_> { /// raids' and the custom bars, in that order. pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) { let mut bars = Vec::new(); - if let Some(d) = self.dragon.as_ref().filter(|_| self.dim == Dim::End) { + if let Some(d) = self.dragon.as_ref().filter(|_| self.dragon_bar_shown()) { bars.push(hud_overlays::BossBar { name: Text::literal( self.translate("entity.minecraft.ender_dragon", "Ender Dragon"), @@ -1870,6 +1870,11 @@ impl Game<'_> { ); hud_layout::paint(batch, &self.res.atlas, &draws); } + /// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`, + /// with `setCreateWorldFog`). + pub(super) fn dragon_bar_shown(&self) -> bool { + self.dim == Dim::End && self.dragon.is_some() + } /// `music.dragon` while the boss bar plays music. pub(super) fn boss_music(&self) -> bool { self.dim == Dim::End && self.dragon.is_some() || self.wither_near() @@ -2066,9 +2071,7 @@ impl Game<'_> { } // The healing beam to the nearest crystal. if let Some(c) = d.nearest_crystal.and_then(|i| self.crystals.get(i)) { - let age = c.time as f32 + a; - let hh = (age * 0.2).sin() / 2.0 + 0.5; - let bob = f64::from((hh * hh + hh) * 0.4 - 1.4); + let bob = f64::from(horizon_client::end_crystal::y(c.time as f32 + a)); let to = glam::DVec3::new(c.position.x, c.position.y + bob, c.position.z); self.crystal_beam(pos, to - pos, self.ticks as f32 + a, camera, out); } @@ -2122,7 +2125,7 @@ impl Game<'_> { } /// `submitCrystalBeams`: an eight-sided tube from `from` (+2 up) along /// `delta`, the beam texture scrolling along it. - fn crystal_beam( + pub(super) fn crystal_beam( &self, from: glam::DVec3, delta: glam::DVec3, diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 30e48ff70..1e36b00f0 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -393,6 +393,45 @@ impl Game<'_> { ) == 0.0; (f64::from(power), infinity) } + /// `EnchantmentHelper.onProjectileSpawned` ignite effects of the held bow + /// (flame): the seconds the new arrow burns for. + pub(super) fn bow_projectile_ignite(&mut self) -> Option { + let bow = self.inventory[self.selected].clone()?; + let ctx = EffectContext { + this: Some("minecraft:arrow"), + items: Some(&self.res.items), + ..Default::default() + }; + let mut ignite: Option = None; + for (id, level) in bow.enchantments() { + let Some(def) = self.res.stations.enchantments.get(id) else { + continue; + }; + for effect in def.effects["minecraft:projectile_spawned"] + .as_array() + .into_iter() + .flatten() + { + if effect["effect"]["type"] != "minecraft:ignite" { + continue; + } + let ok = effect.get("requirements").is_none_or(|r| { + self.res.stations.enchantments.condition( + r, + *level, + &ctx, + &mut self.world.random, + ) + }); + if ok { + let seconds = + horizon_client::enchant::level_value(&effect["effect"]["duration"], *level); + ignite = Some(ignite.map_or(seconds, |s: f32| s.max(seconds))); + } + } + } + ignite + } /// Enchantment attribute modifiers of worn armor (respiration, depth strider...). pub(super) fn apply_enchantment_attributes(&mut self) { let mut wanted: Vec<(String, String, f64, String)> = Vec::new(); diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 126bd322b..5ac4b5c45 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -881,130 +881,67 @@ impl Game<'_> { Ok(()) } - /// The End crystals on the spikes and thrown eyes of ender, as - /// camera-relative entity geometry (End portals and gateways are block - /// entities). + /// End crystals (on the spikes, or placed in any dimension) and thrown + /// eyes of ender, as camera-relative entity geometry (End portals and + /// gateways are block entities). pub(super) fn end_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - if self.dim == Dim::End { - self.end_crystal_geometry(camera, out); - } + self.end_crystal_geometry(camera, out); self.eye_geometry(camera, out); } - /// EndCrystalRenderer and EndCrystalModel for the end crystals. + /// EndCrystalRenderer and EndCrystalModel for the end crystals, and the + /// beam to a crystal's target (the spikes being summoned back). fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let Some(r) = self - .res - .atlas - .sprites - .get("entity/end_crystal/end_crystal") - .copied() - else { + let (Some(model), Some(r)) = ( + self.crystal_model.as_ref(), + self.res + .atlas + .sprites + .get("entity/end_crystal/end_crystal") + .copied(), + ) else { return; }; - let sin45 = std::f32::consts::FRAC_PI_4.sin(); - let axis = glam::Vec3::new(sin45, 0.0, sin45).normalize(); - let tilt = glam::Quat::from_axis_angle(axis, std::f32::consts::FRAC_PI_3); - // A 8×8×8 model box at texture offset (u, v) of the 64×32 texture. - let uv = |u: f32, v: f32, w: f32, h: f32| { - let su = |x: f32| r.u0 + (r.u1 - r.u0) * x / 64.0; - let sv = |y: f32| r.v0 + (r.v1 - r.v0) * y / 32.0; - (su(u), su(u + w), sv(v), sv(v + h)) - }; + let uv = [r.u0, r.v0, r.u1, r.v1]; + let partial = self.clock.fraction() as f32; for crystal in &self.crystals { let feet = glam::DVec3::new(crystal.position.x, crystal.position.y, crystal.position.z); - let age = crystal.time as f32 + self.clock.fraction() as f32; - let spin = glam::Quat::from_rotation_y((age * 3.0).to_radians()); - let hh = (age * 0.2).sin() / 2.0 + 0.5; - let bob = (hh * hh + hh) * 0.4 - 1.4; let rel = feet - camera; if rel.length_squared() > 256.0 * 256.0 { continue; } + let age = crystal.time as f32 + partial; let light = self.world.light( feet.x.floor() as i32, feet.y.floor() as i32, feet.z.floor() as i32, ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); - // poseStack.scale(2) then translate(0, -0.5, 0); outer_glass at y 24 px + bob. - let center = rel.as_vec3() + glam::Vec3::new(0.0, 2.0 * (24.0 / 16.0 - 0.5) + bob, 0.0); - let outer = spin * tilt; - let inner = tilt * spin; - let parts = [ - (outer, 1.0, 0.0), - (outer * inner, 0.875, 0.0), - (outer * inner * inner, 0.875 * 0.765_625, 32.0), - ]; - for (rotation, scale, u) in parts { - // Half extent: 4 px, times the renderer's scale of 2. - let h = 0.25 * 2.0 * scale; - let corner = |x: f32, y: f32, z: f32| { - center + rotation * glam::Vec3::new(x * h, y * h, z * h) - }; - let faces: [([f32; 3], [f32; 3], [f32; 3], (f32, f32, f32, f32)); 6] = [ - ( - [-1.0, 1.0, -1.0], - [1.0, 0.0, 0.0], - [0.0, 0.0, 1.0], - uv(u + 8.0, 0.0, 8.0, 8.0), - ), - ( - [-1.0, -1.0, -1.0], - [1.0, 0.0, 0.0], - [0.0, 0.0, 1.0], - uv(u + 16.0, 0.0, 8.0, 8.0), - ), - ( - [-1.0, -1.0, -1.0], - [0.0, 0.0, 1.0], - [0.0, 1.0, 0.0], - uv(u, 8.0, 8.0, 8.0), - ), - ( - [-1.0, -1.0, -1.0], - [1.0, 0.0, 0.0], - [0.0, 1.0, 0.0], - uv(u + 8.0, 8.0, 8.0, 8.0), - ), - ( - [1.0, -1.0, -1.0], - [0.0, 0.0, 1.0], - [0.0, 1.0, 0.0], - uv(u + 16.0, 8.0, 8.0, 8.0), - ), - ( - [-1.0, -1.0, 1.0], - [1.0, 0.0, 0.0], - [0.0, 1.0, 0.0], - uv(u + 24.0, 8.0, 8.0, 8.0), - ), - ]; - for (o, a, b, (u0, u1, v0, v1)) in faces { - let p = |s: f32, t: f32| { - corner( - o[0] + 2.0 * (a[0] * s + b[0] * t), - o[1] + 2.0 * (a[1] * s + b[1] * t), - o[2] + 2.0 * (a[2] * s + b[2] * t), - ) - }; - let quad = [ - (p(0.0, 0.0), [u0, v1]), - (p(1.0, 0.0), [u1, v1]), - (p(1.0, 1.0), [u1, v0]), - (p(0.0, 1.0), [u0, v0]), - ]; - for (pos, uv) in quad { - out.push(Vertex { - normal: [0; 4], - pos: pos.to_array(), - uv, - layer: 0, - color: 0xFFFF_FFFF, - light: packed, - }); - } - } + let poses = horizon_client::end_crystal::poses(model, age, crystal.show_bottom); + // poseStack.scale(2) then translate(0, -0.5, 0), not flipped. + let base = glam::Mat4::from_translation(rel.as_vec3()) + * glam::Mat4::from_scale(glam::Vec3::splat(2.0)) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.5, 0.0)); + horizon_client::mobs::render::draw( + model, + base, + &poses, + uv, + 0xFFFF_FFFF, + packed, + 0, + out, + ); + if let Some(target) = crystal.beam { + // The beam from the target's centre up to the bobbing crystal. + let from = glam::DVec3::new( + f64::from(target[0]) + 0.5, + f64::from(target[1]) + 0.5, + f64::from(target[2]) + 0.5, + ); + let delta = feet - from + + glam::DVec3::new(0.0, f64::from(horizon_client::end_crystal::y(age)), 0.0); + self.crystal_beam(from, delta, age, camera, out); } } } diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs new file mode 100644 index 000000000..b934f8279 --- /dev/null +++ b/crates/horizon-client/src/game/extras.rs @@ -0,0 +1,304 @@ +//! Horizon's extras in the game (`docs/extras.md`): the zoom key and wheel, +//! clicks for the keystroke overlay, frame times for the FPS counter, the +//! minimap's tiles and image, and their HUD. Each hook does nothing while its +//! extra is off. +use super::{Dim, Game, Screen}; +use horizon_client::{ + extras::{Corner, Cps, FpsCounter, Zoom, fov_target, turn_scale}, + extras_hud::{self, Corners, Keystrokes}, + hud::{HudBatch, MINIMAP_SPRITE}, + keybinds, + minimap::{self, Layer, Minimap, View}, + multiplayer, + reconnect::{Retry, Tracker}, + title::Mode, +}; +use std::time::Duration; +use winit::{event::MouseButton, keyboard::KeyCode}; + +#[derive(Default)] +pub(super) struct ExtrasState { + zoom: Zoom, + fps: FpsCounter, + /// Left and right mouse buttons: held, and their clicks. + mouse: [bool; 2], + cps: [Cps; 2], + minimap: Minimap, + /// The dimension the minimap's tiles belong to. + minimap_dim: Option, + /// Auto-reconnect's attempts at the current server. + reconnect: Tracker, +} +/// CPU time the minimap's tiles may take per frame. +const MINIMAP_BUDGET: Duration = Duration::from_micros(300); + +impl Game<'_> { + fn extras_now(&self) -> f64 { + self.started.elapsed().as_secs_f64() + } + fn zoom_key(&self) -> Option { + let e = &self.settings.extras; + e.zoom.then(|| keybinds::key_code(&e.zoom_key)).flatten() + } + /// A key press or release. The zoom key zooms only while playing with + /// no text open; the key itself always goes on to the screen and the key + /// binds, as a vanilla key mapping's would. + pub(super) fn extras_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) { + if self.zoom_key() != Some(key) { + return; + } + let playing = self.screen == Screen::Playing + && self.title.is_none() + && self.sign_edit.is_none() + && self.book.is_none(); + let level = self.settings.extras.zoom_level; + self.extras.zoom.key(pressed, repeat, playing, level); + } + /// Wheel steps while playing; true when zooming took them from the hotbar. + pub(super) fn extras_scroll(&mut self, steps: f32) -> bool { + self.settings.extras.zoom && self.extras.zoom.scroll(steps) + } + /// Mouse buttons while playing, for the keystroke overlay. + pub(super) fn extras_mouse(&mut self, button: MouseButton, pressed: bool) { + let i = match button { + MouseButton::Left => 0, + MouseButton::Right => 1, + _ => return, + }; + self.extras.mouse[i] = pressed; + if pressed && self.settings.extras.keystrokes { + let now = self.extras_now(); + self.extras.cps[i].click(now); + } + } + /// Once per frame: the frame's time, and keys let go behind screens. + pub(super) fn extras_frame(&mut self, elapsed: Duration) { + // Under agent control the window may lack focus without pausing. + let focused = self.focused || self.control.is_some(); + let playing = self.screen == Screen::Playing && self.title.is_none() && focused; + if !playing || !self.settings.extras.zoom { + self.extras.zoom.release(); + } + if !playing { + self.extras.mouse = [false; 2]; + } + self.update_minimap(); + if self.settings.extras.fps { + let now = self.extras_now(); + self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0); + } else { + self.extras.fps.clear(); + } + } + /// Auto-reconnect: a connection to `address` as `name` starts. + pub(super) fn extras_connecting(&mut self, address: &str, name: &str) { + self.extras.reconnect.connecting(address, name); + } + /// Auto-reconnect: the server let the player in. + pub(super) fn extras_joined(&mut self) { + self.extras.reconnect.joined(std::time::Instant::now()); + } + /// Auto-reconnect: the player left the server on purpose. + pub(super) fn extras_left(&mut self) { + self.extras.reconnect.reset(); + } + /// Auto-reconnect's next attempt after a disconnect, when it is on and + /// the reason allows one. + pub(super) fn reconnect_after(&mut self, reason: &str, from_server: bool) -> Option { + if !self.settings.extras.auto_reconnect { + self.extras.reconnect.reset(); + return None; + } + let now = std::time::Instant::now(); + self.extras.reconnect.ended(reason, from_server, now) + } + /// Show the attempt's countdown on the Disconnected screen. + pub(super) fn offer_reconnect(&mut self, retry: Option) { + let Some(retry) = retry else { + return; + }; + if let Some(title) = self.title.as_mut() + && let Mode::Multiplayer(multiplayer::Screen::Disconnected { retry: slot, .. }) = + &mut title.mode + { + log::info!( + "Horizon: reconnecting to {} in {} s", + retry.address, + retry.seconds_left(std::time::Instant::now()) + ); + *slot = Some(retry); + } + } + /// Auto-reconnect: connect again once the countdown is over. An + /// online-mode server gets the signed-in account again: `connect_server` + /// takes it from `auth::current()`, held in memory for the whole run + /// (the launcher's session file is gone after the first read). + pub(super) fn extras_retry(&mut self) -> horizon_client::Result<()> { + if let Some(retry) = self.title.as_mut().and_then(|t| t.due_retry()) { + self.connect_server(&retry.address, &retry.name)?; + } + Ok(()) + } + /// The minimap's view of the player, if it shows. + fn minimap_view(&self) -> Option { + let e = &self.settings.extras; + let p = self.player.as_ref()?; + let shown = e.minimap && self.title.is_none() && !self.ui.hide_gui; + shown.then_some(View { + x: p.position.x, + z: p.position.z, + yaw: self.yaw, + rotate: e.minimap_rotate, + blocks_per_pixel: e.minimap_zoom, + round: e.minimap_round, + }) + } + /// Refresh the minimap's tiles within the frame budget, recompose its + /// image when the view or a tile changed, and queue the upload. + fn update_minimap(&mut self) { + let Some(view) = self.minimap_view() else { + if !self.settings.extras.minimap || self.player.is_none() { + self.extras.minimap.clear(); + self.extras.minimap_dim = None; + } + return; + }; + if self.extras.minimap_dim != Some(self.dim) { + self.extras.minimap.clear(); + self.extras.minimap_dim = Some(self.dim); + } + let Some(p) = self.player.as_ref() else { + return; + }; + let head = (p.position.y + f64::from(p.dimensions.eye_height)).floor() as i32; + let (bx, bz) = (view.x.floor() as i32, view.z.floor() as i32); + // Underground, under a roof or in the Nether: the floor around the player. + let covered = self.world.light(bx, head, bz) >> 4 == 0; + let layer = if self.dim == Dim::Nether || covered { + Layer::Below(head) + } else { + Layer::Surface + }; + // The chunks the image can reach (its corners when it turns). + let reach = minimap::SIZE as f32 / 2.0 * view.blocks_per_pixel * std::f32::consts::SQRT_2; + let radius = ((reach / 16.0).ceil() as i32 + 1).min(self.settings.render_distance.max(2)); + self.extras.minimap.update( + &self.world, + &self.res.facts, + (bx >> 4, bz >> 4), + radius, + layer, + MINIMAP_BUDGET, + ); + if !self.extras.minimap.compose(view) { + return; + } + let Some(rect) = self.res.atlas.sprites.get(MINIMAP_SPRITE).copied() else { + return; + }; + let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + self.map_patches.push(horizon_client::font::Patch { + x: (rect.u0 * w).round() as u32, + y: (rect.v0 * h).round() as u32, + width: minimap::SIZE as u32, + height: minimap::SIZE as u32, + rgba: self.extras.minimap.image.clone(), + }); + } + /// The zoom in effect (1 unless the key is held). + fn zoom_factor(&self) -> f32 { + self.extras.zoom.factor(self.scoping()) + } + /// The field-of-view modifier target, divided by a smooth zoom. + pub(super) fn zoomed_fov_target(&self, vanilla: f32) -> f32 { + if self.settings.extras.zoom_smooth { + fov_target(vanilla, self.zoom_factor()) + } else { + vanilla + } + } + /// The field of view in degrees, divided by an instant zoom. + pub(super) fn zoomed_fov_degrees(&self, fov: f32) -> f32 { + if self.settings.extras.zoom_smooth { + fov + } else { + fov / self.zoom_factor() + } + } + /// Mouse turning while zoomed. + pub(super) fn zoom_turn_scale(&self) -> f64 { + turn_scale(self.zoom_factor(), self.settings.extras.zoom_sensitivity) + } + /// The FPS counter and keystrokes, in the HUD layer (hidden with F1 by + /// the caller). The top left corner gives way to the debug screen. + pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) { + let e = &self.settings.extras; + if !e.fps && !e.keystrokes && !e.minimap { + return; + } + let (fps_on, fps_corner, lows) = (e.fps, e.fps_corner, e.fps_lows); + let (keys_on, keys_corner, cps_on) = (e.keystrokes, e.keystrokes_corner, e.keystrokes_cps); + let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size)); + let visible = |corner| !(self.debug && corner == Corner::TopLeft); + let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); + let atlas = &self.res.atlas; + if let Some(view) = self.minimap_view() + && visible(map_corner) + && !self.extras.minimap.image.is_empty() + && let Some(image) = atlas.sprites.get(MINIMAP_SPRITE).copied() + { + let (arrow, north) = if view.rotate { + (0.0, Some(view.north())) + } else { + (180.0 + view.yaw, None) + }; + let look = extras_hud::MinimapLook { + corner: map_corner, + size: map_size, + image, + arrow, + north, + }; + extras_hud::draw_minimap(batch, atlas, &mut corners, &look); + } + if fps_on && visible(fps_corner) { + let reading = self.extras.fps.reading(); + extras_hud::draw_fps(batch, atlas, &mut corners, fps_corner, reading, lows); + } + if keys_on && visible(keys_corner) { + let now = self.extras_now(); + let cps = cps_on.then(|| { + let [l, r] = &mut self.extras.cps; + (l.per_second(now), r.per_second(now)) + }); + let held = |k| self.keys.contains(&k); + let label = |name| keybinds::display_name(self.settings.keys.get(name)).plain(); + let k = Keystrokes { + moves: [ + (held(KeyCode::KeyW), label("key.forward")), + (held(KeyCode::KeyA), label("key.left")), + (held(KeyCode::KeyS), label("key.back")), + (held(KeyCode::KeyD), label("key.right")), + ], + jump: held(KeyCode::Space), + attack: self.extras.mouse[0], + use_: self.extras.mouse[1], + cps, + }; + extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k); + } + } + /// The height the status effect icons take at the top right + /// (`Hud.extractEffects`: beneficial at y 1, harmful at y 26). + fn effect_rows_height(&self) -> f32 { + let effects = &self.potions.effects.list; + if effects.is_empty() || self.screen != Screen::Playing { + return 0.0; + } + let harmful = effects.iter().any(|e| { + horizon_client::brewing::effect(e.id) + .is_some_and(|d| d.category != horizon_client::brewing::Category::Beneficial) + }); + if harmful { 50.0 } else { 25.0 } + } +} diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 4f715d697..102248861 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -54,6 +54,7 @@ impl Game<'_> { let target = self .fov_player() .map_or(1.0, |p| field_of_view_modifier(&p, first_person, effect)); + let target = self.zoomed_fov_target(target); let eye = self.player.as_ref().map(|p| p.dimensions.eye_height); self.view.tick(eye, target); } @@ -77,14 +78,15 @@ impl Game<'_> { } /// `Camera.calculateFov` with `modifyFovBasedOnDeathOrFluid`. pub(super) fn fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 { - self.view.calculate_fov( + let fov = self.view.calculate_fov( partial, self.settings.fov as i32, self.fov_effect_scale(), self.death_time(), self.camera_fluid(camera), false, - ) + ); + self.zoomed_fov_degrees(fov) } /// `Camera.calculateHudFov`: the first-person hand's field of view. pub(super) fn hud_fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 { diff --git a/crates/horizon-client/src/game/functions.rs b/crates/horizon-client/src/game/functions.rs index b0c3aed9d..9cb0c5c47 100644 --- a/crates/horizon-client/src/game/functions.rs +++ b/crates/horizon-client/src/game/functions.rs @@ -535,7 +535,9 @@ impl Game<'_> { let hint = if enabled { "disable" } else { "enable" }; let style = text::Style { color: Some(if enabled { text::GREEN } else { text::RED }), - suggest: Some(format!("/datapack {hint} \"{id}\"")), + click: Some(text::ClickEvent::SuggestCommand(format!( + "/datapack {hint} \"{id}\"" + ))), ..text::Style::default() }; let description = self diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 5ad7a7f22..c88f213e5 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -212,8 +212,26 @@ impl Game<'_> { } } } + /// `Minecraft.crosshairPickEntity` when it is a `LivingEntity`: whether + /// it is alive (the nearest entity under the crosshair, before any block). + pub(super) fn crosshair_living(&self) -> Option { + let nearest = |hits: &[Option]| hits.iter().flatten().copied().reduce(f64::min); + let living = nearest(&[ + self.mob_hit().map(|h| h.1), + self.armor_stand_hit().map(|h| h.1), + self.dragon_hit().map(|h| h.1), + ])?; + let other = nearest(&[ + self.painting_hit().map(|h| h.1), + self.frame_hit().map(|h| h.1), + self.boat_hit().map(|h| h.1), + self.cart_hit().map(|h| h.1), + ]); + // Only alive mobs are hit, so a picked living entity is alive. + (self.before_block(living) && other.is_none_or(|o| living <= o)).then_some(true) + } /// `Attributes.ATTACK_SPEED` with the main-hand item's modifier. - fn main_hand_attack_speed(&self) -> f64 { + pub(super) fn main_hand_attack_speed(&self) -> f64 { horizon_client::attack_strength::BASE_ATTACK_SPEED + self .held() diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 6fd7e4dd8..ed29d0305 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -128,6 +128,9 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { if m.health < m.kind.max_health { meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0)))); } + if kind == "minecraft:rabbit" && m.no_ai { + meta.push((15, serializer::BYTE, Value::Byte(1))); + } if m.is_baby() && let Some(index) = baby_index(kind) { @@ -222,9 +225,17 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { meta.push((18, serializer::INT, Value::Int(e.size))); } } - // Creeper.DATA_IS_POWERED. - "minecraft:creeper" if e.charged => { - meta.push((17, serializer::BOOLEAN, Value::Bool(true))); + // Creeper.DATA_SWELL_DIR, DATA_IS_POWERED and DATA_IS_IGNITED: the + // guest swells the creeper from them. The direction always goes in, + // as only changed entries are sent and it drops back to -1. + "minecraft:creeper" => { + meta.push((16, serializer::INT, Value::Int(e.counter))); + if e.charged { + meta.push((17, serializer::BOOLEAN, Value::Bool(true))); + } + if e.flag { + meta.push((18, serializer::BOOLEAN, Value::Bool(true))); + } } // Enderman.DATA_CARRY_STATE. "minecraft:enderman" => { @@ -701,8 +712,10 @@ impl Game<'_> { } for e in events { if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e { + // The acting guest does not predict the egg's teleport particles. + let except = if *id == 2015 { None } else { self.lan_acting }; self.lan_events - .push((*id, [pos.x, pos.y, pos.z], *data, self.lan_acting)); + .push((*id, [pos.x, pos.y, pos.z], *data, except)); } } } diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 8f2612472..c36ce5d84 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -282,6 +282,9 @@ impl Game<'_> { o.active(*button) && ui::hovered(self.cursor, *x, *y, *bw, 20.0) }) .map(|b| b.0); + if hit.is_some() { + self.audio.play_button_click(); + } match hit { Some(Button::DefaultMode) => o.default_mode = (o.default_mode + 1) % 4, Some(Button::PersonalMode) => o.personal_mode = (o.personal_mode + 1) % 4, diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 678020712..4516ce7dd 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,12 +1,16 @@ //! Level events whose client handler (`LevelEventHandler`) spawns particles -//! on a block: electric sparks (3002), waxing (3003), wax off (3004) and -//! scraping (3005). +//! on a block: dragon egg teleportation (2015), electric sparks (3002), +//! waxing (3003), wax off (3004) and scraping (3005). use super::Game; use horizon_client::particles::{self, ParticleOptions, ParticleType}; use horizon_core::position::BlockPos; use horizon_world::level::LevelEvent; impl Game<'_> { + pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) { + self.particles + .block_teleportation(pos, data, self.settings.particles); + } /// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client /// level's random. pub(super) fn block_particle_event(&mut self, id: i32, pos: BlockPos, data: i32) { diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index c14931e14..b81d09325 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -16,6 +16,7 @@ use horizon_client::{ }; use horizon_core::{ geometry::{Aabb, Vec3}, + position::BlockPos, random::RandomSource, }; use horizon_world::registry::BlockStateId; @@ -1042,18 +1043,46 @@ impl Game<'_> { if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) { return false; } + let burning = self + .held() + .is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0); + self.hurt_cart(i, damage, self.creative, burning); + self.swing_arm(); + true + } + /// An arrow hit cart `i` (`MinecartTNT.hurtServer`, then + /// `VehicleEntity.hurtServer`): a burning arrow sets off a TNT minecart. + pub(super) fn arrow_hits_cart( + &mut self, + i: usize, + damage: f32, + arrow_velocity: Vec3, + burning: bool, + creative: bool, + ) { + if i >= self.carts.len() { + return; + } + if burning && self.carts[i].kind == CartKind::Tnt { + let c = self.carts.remove(i); + self.explode_cart(&c, arrow_velocity.length_squared()); + return; + } + self.hurt_cart(i, damage, creative, false); + } + /// `VehicleEntity.hurtServer`: shake, add the damage, break past 40 (at + /// once for creative players); TNT minecarts prime instead when moving + /// or hurt by fire. + fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) { let c = &mut self.carts[i]; c.hurt_dir = -c.hurt_dir; c.hurt_time = 10; c.damage += damage * 10.0; - let destroyed = self.creative || c.damage > 40.0; + let destroyed = creative || c.damage > 40.0; if destroyed { let mut c = self.carts.remove(i); let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; - let burning = self - .held() - .is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0); - if c.kind == CartKind::Tnt && (burning || speed >= 0.01) { + if c.kind == CartKind::Tnt && (fire || speed >= 0.01) { // MinecartTNT.destroy: prime instead of breaking. if c.fuse < 0 { self.prime_cart(&mut c); @@ -1067,29 +1096,23 @@ impl Game<'_> { for s in c.items.iter().flatten() { self.spawn_item(s.clone(), at, [0.0, 0.1, 0.0], 10); } - if !self.creative { + if !creative { self.spawn_item(ItemStack::new(c.kind.id(), 1), at, [0.0, 0.1, 0.0], 10); } } } } - self.swing_arm(); - true } /// A block model's faces under `m` (block space 0..1), lit flat. - fn block_model_vertices( + pub(super) fn block_model_vertices( &self, state: BlockStateId, + seed_pos: BlockPos, m: glam::Mat4, light: u32, out: &mut Vec, ) { - let Ok(models) = self - .res - .assets - .model_catalog - .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) - else { + let Ok(models) = self.res.assets.model_catalog.collect(state, seed_pos) else { return; }; for (_, model) in &models { @@ -1238,7 +1261,7 @@ impl Game<'_> { * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); let flash = c.kind == CartKind::Tnt && c.fuse > -1 && (c.fuse / 5) % 2 == 0; let start = out.len(); - self.block_model_vertices(state, m, packed, out); + self.block_model_vertices(state, BlockPos::default(), m, packed, out); if flash { // submitWhiteSolidBlock: OverlayTexture.u(1.0) on the cart's own light. for v in &mut out[start..] { diff --git a/crates/horizon-client/src/game/net_harness.rs b/crates/horizon-client/src/game/net_harness.rs index 681a950b0..1ec573e7c 100644 --- a/crates/horizon-client/src/game/net_harness.rs +++ b/crates/horizon-client/src/game/net_harness.rs @@ -30,7 +30,7 @@ impl Game<'_> { if self.remote.is_none() { error = Some(match self.title.as_ref().map(|t| &t.mode) { Some(horizon_client::title::Mode::Multiplayer( - horizon_client::multiplayer::Screen::Disconnected { reason }, + horizon_client::multiplayer::Screen::Disconnected { reason, .. }, )) => format!("disconnected: {reason}"), _ => "disconnected".to_owned(), }); diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index e4d44fe9d..fa631e114 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -44,12 +44,20 @@ impl Game<'_> { } pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> { if !pressed { - self.ui.options.release(); + if right { + return Ok(()); + } + let events = self.ui.options.release(); self.dragging = false; - return Ok(()); + return self.handle_option_events(events); + } + if !right { + self.dragging = true; } - self.dragging = true; let size = self.gui_size(); + let framebuffer = self.renderer.as_ref().map_or([1280, 720], |r| { + [r.config.width as i32, r.config.height as i32] + }); let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, @@ -57,6 +65,7 @@ impl Game<'_> { self.cursor.0, self.cursor.1, size, + framebuffer, false, right, ); @@ -65,6 +74,9 @@ impl Game<'_> { } pub(super) fn options_drag(&mut self) -> Result<()> { let size = self.gui_size(); + let framebuffer = self.renderer.as_ref().map_or([1280, 720], |r| { + [r.config.width as i32, r.config.height as i32] + }); let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, @@ -72,6 +84,7 @@ impl Game<'_> { self.cursor.0, self.cursor.1, size, + framebuffer, true, false, ); @@ -115,6 +128,7 @@ impl Game<'_> { pub(super) fn handle_option_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { + Event::ButtonClick => self.audio.play_button_click(), Event::Changed => { self.settings.save(&Self::options_path()); self.apply_settings(); diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 8eeb4e7c4..d7bb6d558 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -6,6 +6,7 @@ use horizon_client::{ Result, chunk::Chunk, entity_nbt, + mobs::Who, save::{ChunkExtras, random_uuid}, }; use horizon_core::{geometry::Vec3, position::ChunkPos, random::RandomSource, ticks::ChunkTicks}; @@ -186,8 +187,15 @@ impl Game<'_> { } "minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)), "minecraft:arrow" => { - if let Some(a) = entity_nbt::arrow_from_nbt(&tag, player_uuid) { - self.arrows.push(a); + if let Some((mut p, in_block)) = entity_nbt::arrow_from_nbt( + &tag, + player_uuid, + super::dispenser::tipped_effect, + ) { + if let Some(a) = p.arrow.as_mut() { + a.last_state = in_block.and_then(|t| self.state_from_nbt(&t)); + } + self.creatures.projectiles.push(p); } } "minecraft:falling_block" => { @@ -198,6 +206,8 @@ impl Game<'_> { let (no_gravity, drop_item) = entity_nbt::falling_block_flags(&tag); self.falling.push(FallingBlock { state, + // DATA_START_POS is not persisted by vanilla. + start_pos: horizon_core::position::BlockPos::default(), position, previous: position, velocity, @@ -517,7 +527,7 @@ impl Game<'_> { .id(&state) .or_else(|| registry.default_state(&state.name)) } - fn state_to_nbt(&self, state: BlockStateId) -> Tag { + pub(in crate::game) fn state_to_nbt(&self, state: BlockStateId) -> Tag { let registry = self.res.assets.registry; match registry.state(state) { Some(s) if registry.default_state(&s.name) == Some(state) => { @@ -579,14 +589,23 @@ impl Game<'_> { .push(with_raw(entity_nbt::orb_to_nbt(o, uuid), raw.as_ref())); } } - for a in &self.arrows { - if keys.contains(&chunk_of(a.position)) { - let owner = if a.from_player { player_uuid } else { None }; - let (uuid, raw) = anon(&self.persist, "minecraft:arrow", a.position); - out.entry(chunk_of(a.position)).or_default().push(with_raw( - entity_nbt::arrow_to_nbt(a, uuid, owner), - raw.as_ref(), - )); + for p in &self.creatures.projectiles { + if !keys.contains(&chunk_of(p.position)) { + continue; + } + let owner = if p.owner == Some(Who::Player) { + player_uuid + } else { + None + }; + let (uuid, raw) = anon(&self.persist, "minecraft:arrow", p.position); + let in_block = p + .arrow + .as_ref() + .and_then(|a| a.last_state) + .map(|s| self.state_to_nbt(s)); + if let Some(tag) = entity_nbt::arrow_to_nbt(p, uuid, owner, in_block, raw.as_ref()) { + out.entry(chunk_of(p.position)).or_default().push(tag); } } for f in &self.falling { @@ -796,7 +815,9 @@ impl Game<'_> { keep }); self.orbs.retain(|o| !gone(o.position)); - self.arrows.retain(|a| !gone(a.position)); + self.creatures + .projectiles + .retain(|p| p.arrow.is_none() || !gone(p.position)); self.falling.retain(|f| !gone(f.position)); self.persist .anon diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 1b381ffaf..3b7eeb7f3 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -162,6 +162,7 @@ impl Game<'_> { let auth = horizon_client::auth::current(); let name = auth.as_ref().map_or(name, |a| a.name.as_str()); let session = Session::connect(address, name, auth.clone(), view, lang.clone()); + self.extras_connecting(address, name); let player_type = super::perspective::player_type(&root); let mut streaming = Streaming::new( Arc::new(NoTerrain), @@ -182,7 +183,7 @@ impl Game<'_> { self.player = None; self.spawn = None; self.mobs.clear(); - self.arrows.clear(); + self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); self.orbs.clear(); @@ -260,6 +261,10 @@ impl Game<'_> { /// Disconnect and return to the multiplayer screen (DisconnectedScreen). pub(super) fn leave_server(&mut self, reason: Option) -> Result<()> { + if reason.is_none() { + // Leaving on purpose: nothing for auto-reconnect to retry. + self.extras_left(); + } if let Some(mut r) = self.remote.take() { r.session.disconnect(); } @@ -284,7 +289,10 @@ impl Game<'_> { let saves = std::env::current_dir()?.join("saves"); let mut title = horizon_client::title::Title::new(saves.clone()); title.mode = horizon_client::title::Mode::Multiplayer(match reason { - Some(reason) => horizon_client::multiplayer::Screen::Disconnected { reason }, + Some(reason) => horizon_client::multiplayer::Screen::Disconnected { + reason, + retry: None, + }, None => horizon_client::multiplayer::Screen::list(&saves), }); self.title = Some(title); @@ -374,6 +382,7 @@ impl Game<'_> { uuid, } => { self.set_registries(registries); + self.extras_joined(); if let Some(r) = self.remote.as_mut() { r.joined = true; r.profile = uuid; @@ -389,9 +398,15 @@ impl Game<'_> { } } } - Event::Disconnected(reason) => { + Event::Disconnected { + reason, + from_server, + } => { log::info!("Horizon: disconnected: {reason}"); - return self.leave_server(Some(reason)); + let retry = self.reconnect_after(&reason, from_server); + self.leave_server(Some(reason))?; + self.offer_reconnect(retry); + return Ok(()); } Event::Packet(packet) => self.handle_packet(*packet)?, } @@ -805,6 +820,9 @@ impl Game<'_> { } } C::BlockChangedAck(_) => {} + C::LevelEvent(p) if p.kind == 2015 => { + self.dragon_egg_particles(p.pos, p.data); + } C::LevelEvent(p) if p.kind == 2001 => { // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. let state = BlockStateId(p.data.max(0) as u32); @@ -918,6 +936,30 @@ impl Game<'_> { } } C::SetEntityData(p) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + && m.species() == horizon_client::mobs::Species::Rabbit + { + for (index, _, value) in &p.values { + match (index, value) { + (15, Value::Byte(flags)) => m.no_ai = flags & 1 != 0, + (16, Value::Bool(baby)) => m.extra.age = if *baby { -1 } else { 0 }, + _ => {} + } + } + } + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + && m.species() == horizon_client::mobs::Species::Creeper + { + for (index, _, value) in &p.values { + match (index, value) { + // Creeper.DATA_SWELL_DIR, DATA_IS_POWERED, DATA_IS_IGNITED. + (16, Value::Int(dir)) => m.extra.counter = *dir, + (17, Value::Bool(powered)) => m.extra.charged = *powered, + (18, Value::Bool(ignited)) => m.extra.flag = *ignited, + _ => {} + } + } + } for (index, _, value) in &p.values { if *index == ITEM_ENTITY_ITEM && let Value::Item(stack) = value @@ -948,6 +990,12 @@ impl Game<'_> { } } C::EntityEvent(p) => { + if p.event == 1 + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + && m.species() == horizon_client::mobs::Species::Rabbit + { + horizon_client::mobs::rabbit::hop_event(m); + } // EntityEvent.DEATH: start the death animation. if p.event == 3 && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) @@ -1723,6 +1771,12 @@ impl Game<'_> { m.previous_body_yaw = m.body_yaw; m.previous_limb_speed = m.limb_speed; m.age += 1; + if m.species() == horizon_client::mobs::Species::Rabbit { + horizon_client::mobs::rabbit::base_tick(m); + } + if m.species() == horizon_client::mobs::Species::Creeper { + horizon_client::mobs::hostile::creeper_client_tick(m); + } if m.hurt_time > 0 { m.hurt_time -= 1; } @@ -1745,6 +1799,9 @@ impl Game<'_> { let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0); m.limb_speed += (target - m.limb_speed) * 0.4; m.limb_position += m.limb_speed; + if m.species() == horizon_client::mobs::Species::Rabbit { + horizon_client::mobs::rabbit::post_tick(m); + } } for d in &mut self.dropped { d.previous = d.position; diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index dbd77eb9f..e365e2080 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -85,7 +85,8 @@ impl Game<'_> { render_distance_chunks: self.streaming.radius, cloud_range_chunks: self.settings.cloud_range, camera_y: camera.y, - min_y: MIN_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, forward: forward.map(|c| c as f32), rain, @@ -93,6 +94,7 @@ impl Game<'_> { skybox: self.dim == Dim::Overworld, blindness: None, darkness: self.darkness_fog(), + boss_world_fog: self.dragon_bar_shown(), }) } /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 1de93e862..7858cdfe2 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -151,6 +151,9 @@ impl Game<'_> { .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0)) .map(|b| b.4) }; + if hit.is_some() && !horizon_client::ui_theme::horizon() { + self.audio.play_button_click(); + } match hit { Some(0) => { self.screen = Screen::Playing; @@ -255,6 +258,9 @@ impl Game<'_> { .into_iter() .find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)) .map(|d| d.3); + if hit.is_some() { + self.audio.play_button_click(); + } match hit { Some(0) if self.remote.is_some() => { self.ui.death_text = None; diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index f749151c4..038b3dcda 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -145,6 +145,7 @@ impl Game<'_> { let (x, y) = (b.width / 2.0 - 100.0, b.height / 4.0 + 144.0); let (mx, my) = self.cursor; if mx >= x && mx < x + 200.0 && my >= y && my < y + 20.0 { + self.audio.play_button_click(); self.close_sign_editor(); } } diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 3b48e929f..105e27984 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -346,11 +346,6 @@ impl Game<'_> { push(p.position, &mut p.velocity, self); } self.creatures.projectiles = projectiles; - let mut arrows = std::mem::take(&mut self.arrows); - for a in arrows.iter_mut().filter(|a| !a.stuck) { - push(a.position, &mut a.velocity, self); - } - self.arrows = arrows; let mut tnts = std::mem::take(&mut self.tnts); for t in &mut tnts { push(t.position, &mut t.velocity, self); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 9d70861e7..3b013352d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -273,6 +273,8 @@ pub struct Renderer { lightmap_view: wgpu::TextureView, lightmap_sampler: wgpu::Sampler, animations: Vec<(SpriteAnimation, usize)>, + /// Each sprite layer's MipmapGenerator settings, for animation frames. + sprite_mips: Vec, /// Edge length of the block sprite array's layers. sprite_size: u32, sprite_minimum_size: u32, @@ -321,41 +323,41 @@ pub struct Renderer { pub animated_textures: bool, present_modes: Vec, } -fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec, u32) { +/// Every layer's mip levels, layer major (`first` is the first layer's +/// index into `settings`), made by `MipmapGenerator`. +fn mip_chain( + pixels: &[u8], + size: u32, + settings: &[crate::mipmap::Settings], + first: u32, + layers: u32, +) -> (Vec, u32) { let levels = size.trailing_zeros() + 1; + let layer_bytes = (size * size * 4) as usize; let mut out = Vec::new(); for layer in 0..layers as usize { - let base = - &pixels[layer * (size * size * 4) as usize..(layer + 1) * (size * size * 4) as usize]; - let mut level = base.to_vec(); - let mut s = size as usize; - out.extend_from_slice(&level); - for _ in 1..levels { - let n = s / 2; - let mut next = vec![0u8; n * n * 4]; - for y in 0..n { - for x in 0..n { - let mut acc = [0u32; 4]; - let mut weight = 0u32; - for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { - let p = &level[((y * 2 + dy) * s + x * 2 + dx) * 4..][..4]; - let a = u32::from(p[3]); - for c in 0..3 { - acc[c] += u32::from(p[c]) * a; - } - acc[3] += a; - weight += a; - } - let o = &mut next[(y * n + x) * 4..][..4]; - for c in 0..3 { - o[c] = acc[c].checked_div(weight).unwrap_or(0) as u8; - } - o[3] = (acc[3] / 4) as u8; - } - } - out.extend_from_slice(&next); - level = next; - s = n; + let base = crate::mipmap::Image { + width: size, + height: size, + pixels: pixels[layer * layer_bytes..(layer + 1) * layer_bytes] + .as_chunks::<4>() + .0 + .to_vec(), + }; + let s = settings + .get(first as usize + layer) + .copied() + .unwrap_or_default(); + let has_transparent = s.has_transparent || base.pixels.iter().any(|p| p[3] == 0); + for image in crate::mipmap::generate( + base, + levels - 1, + s.strategy, + s.alpha_cutoff_bias, + has_transparent, + s.item, + ) { + out.extend(image.pixels.iter().flatten()); } } (out, levels) @@ -397,6 +399,7 @@ impl Renderer { sprite_size: u32, sprite_minimum_size: u32, layers: u32, + sprite_mips: &[crate::mipmap::Settings], animations: &[SpriteAnimation], hud_atlas: (&[u8], u32, u32), forcefield: (&[u8], u32), @@ -718,7 +721,7 @@ impl Renderer { usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, layers); + let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, sprite_mips, 0, layers); let sprite_texture = device.create_texture_with_data( &queue, &wgpu::TextureDescriptor { @@ -1103,7 +1106,8 @@ impl Renderer { // WorldBorderRenderer: misc/forcefield.png as a MipmappedTexture // (repeat, linear minification with mipmaps, nearest magnification). let (forcefield_pixels, forcefield_size) = forcefield; - let (forcefield_mips, forcefield_levels) = mip_chain(forcefield_pixels, forcefield_size, 1); + let (forcefield_mips, forcefield_levels) = + mip_chain(forcefield_pixels, forcefield_size, &[], 0, 1); let forcefield_texture = device.create_texture_with_data( &queue, &wgpu::TextureDescriptor { @@ -1410,6 +1414,7 @@ impl Renderer { lightmap_view, lightmap_sampler, animations: animations.iter().map(|a| (a.clone(), usize::MAX)).collect(), + sprite_mips: sprite_mips.to_vec(), sprite_size, sprite_minimum_size, indices, @@ -1793,6 +1798,7 @@ impl Renderer { tick, self.sprite_size, self.mip_levels, + &self.sprite_mips, |layer, level, size, pixels| { self.queue.write_texture( wgpu::TexelCopyTextureInfo { @@ -2694,6 +2700,7 @@ fn animate_sprites( tick: u64, size: u32, max_levels: u32, + settings: &[crate::mipmap::Settings], mut write: impl FnMut(u32, u32, u32, &[u8]), ) { for (animation, previous) in animations { @@ -2702,7 +2709,7 @@ fn animate_sprites( continue; } *previous = frame; - let (mips, levels) = mip_chain(animation.pixels(frame), size, 1); + let (mips, levels) = mip_chain(animation.pixels(frame), size, settings, animation.layer, 1); let mut offset = 0; for level in 0..levels.min(max_levels) { let edge = size >> level; @@ -2727,7 +2734,8 @@ mod sprite_upload_tests { for size in [16, 32] { let animation = crate::sprites::test_animation(size, 7); let pixels = animation.pixels(animation.frame(1)).to_vec(); - let (expected, levels) = mip_chain(&pixels, size, 1); + let settings = []; + let (expected, levels) = mip_chain(&pixels, size, &settings, 7, 1); let mut animations = vec![(animation, 0)]; let mut writes = Vec::new(); let mut record = |layer, level, edge, data: &[u8]| { @@ -2736,9 +2744,9 @@ mod sprite_upload_tests { assert_eq!(data.len(), (edge * edge * 4) as usize); writes.push(data.to_vec()); }; - animate_sprites(&mut animations, 0, size, levels, &mut record); - animate_sprites(&mut animations, 1, size, levels, &mut record); - animate_sprites(&mut animations, 1, size, levels, &mut record); + animate_sprites(&mut animations, 0, size, levels, &settings, &mut record); + animate_sprites(&mut animations, 1, size, levels, &settings, &mut record); + animate_sprites(&mut animations, 1, size, levels, &settings, &mut record); assert_eq!(writes.len(), levels as usize); assert_eq!(writes[0], pixels); assert_eq!(writes.concat(), expected); diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index fc9eef76f..d72f8de86 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -401,14 +401,6 @@ impl Item { } pub fn label(self, s: &Settings) -> Text { match self { - // The vanilla button shows the scale alone, under its own caption. - Item::Vanilla(Opt::GuiScale) => Text::translate( - "options.generic_value", - &[ - Text::translate("options.guiScale", &[]), - Opt::GuiScale.label(s), - ], - ), Item::Vanilla(o) => o.label(s), Item::Horizon(h) => h.label(s), } @@ -420,9 +412,9 @@ impl Item { } self.touched(s); } - pub fn cycle(self, s: &mut Settings, back: bool) { + pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) { match self { - Item::Vanilla(o) => o.cycle(s, back), + Item::Vanilla(o) => o.cycle(s, back, framebuffer), Item::Horizon(h) => h.cycle(s, back), } self.touched(s); @@ -456,6 +448,7 @@ impl Item { /// What the options screens must do after an interaction here. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Action { + ButtonClick, Changed, OpenAdvanced, OpenSimple, @@ -655,6 +648,7 @@ impl GraphicsUi { s: &mut Settings, (x, y): (f32, f32), (w, h): (f32, f32), + framebuffer: [i32; 2], drag: bool, right: bool, ) -> Vec { @@ -671,6 +665,9 @@ impl GraphicsUi { } return Vec::new(); } + if right { + return Vec::new(); + } for wd in widgets { if !ui::hovered((x, y), wd.x, wd.y, wd.w, 20.0) { continue; @@ -679,13 +676,14 @@ impl GraphicsUi { continue; } return match wd.target { - Target::Button(action) => vec![action], + Target::Button(action) => vec![Action::ButtonClick, action], Target::Item(item) => { if item.slider(s).is_some() { self.dragging = Some(item); item.set_slider(s, ui::slider_value(wd.x, wd.w, x)); } else { - item.cycle(s, right); + item.cycle(s, right, framebuffer); + return vec![Action::ButtonClick, Action::Changed]; } vec![Action::Changed] } @@ -693,8 +691,8 @@ impl GraphicsUi { } Vec::new() } - pub fn release(&mut self) { - self.dragging = None; + pub fn release(&mut self) -> bool { + self.dragging.take().is_some() } pub fn scroll(&mut self, level: Level, h: f32, amount: f32) { let content = Self::content_height(level); @@ -708,6 +706,58 @@ impl GraphicsUi { mod tests { use super::*; + #[test] + fn graphics_buttons_sound_on_press_and_sliders_on_release() { + let mut s = Settings::default(); + let mut ui = GraphicsUi::default(); + let size = (480.0, 320.0); + let (widgets, _, _) = ui.layout(Level::Simple, size.0, size.1); + let button = widgets + .iter() + .find(|w| matches!(w.target, Target::Button(_))) + .unwrap(); + let point = (button.x + 1.0, button.y + 1.0); + assert!( + ui.click(Level::Simple, &mut s, point, size, [854, 480], false, true) + .is_empty() + ); + assert_eq!( + ui.click(Level::Simple, &mut s, point, size, [854, 480], false, false)[0], + Action::ButtonClick + ); + assert!(!ui.release()); + let slider = widgets + .iter() + .find(|w| matches!(w.target, Target::Item(i) if i.slider(&s).is_some())) + .unwrap(); + assert_eq!( + ui.click( + Level::Simple, + &mut s, + (slider.x + 1.0, slider.y + 1.0), + size, + [854, 480], + false, + false + ), + vec![Action::Changed] + ); + assert_eq!( + ui.click( + Level::Simple, + &mut s, + (-100.0, -100.0), + size, + [854, 480], + true, + false + ), + vec![Action::Changed] + ); + assert!(ui.release()); + assert!(!ui.release()); + } + #[test] fn scrolling_stops_at_both_limits_before_layout() { for level in [Level::Simple, Level::Advanced] { @@ -768,16 +818,16 @@ mod tests { #[test] fn presets_set_vanilla_and_horizon_options() { let mut s = Settings::default(); - Item::Horizon(H::Preset).cycle(&mut s, false); + Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480]); assert_eq!(s.horizon.preset, Preset::Performance); assert_eq!(s.render_distance, 8); assert_eq!(s.clouds, "false"); // Any quality change leaves the preset. - Item::Vanilla(Opt::Clouds).cycle(&mut s, false); + Item::Vanilla(Opt::Clouds).cycle(&mut s, false, [854, 480]); assert_eq!(s.horizon.preset, Preset::Custom); // Display preferences keep it. - Item::Horizon(H::Preset).cycle(&mut s, true); - Item::Vanilla(Opt::Vsync).cycle(&mut s, false); + Item::Horizon(H::Preset).cycle(&mut s, true, [854, 480]); + Item::Vanilla(Opt::Vsync).cycle(&mut s, false, [854, 480]); assert_eq!(s.horizon.preset, Preset::Ultra); } diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 091acf822..e9bca28b0 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -32,8 +32,12 @@ pub struct HudAtlas { pub const GLYPH_ROWS: u32 = 512; /// 128x128 atlas slots for map textures. pub const MAP_SLOTS: usize = 16; +/// The atlas slot the minimap extra draws into. +pub const MINIMAP_SPRITE: &str = "horizon/minimap"; /// Atlas slots for downloaded player skins (`skins/`), 64x64 each. pub const SKIN_SLOTS: usize = 32; +/// Reused by the visible rows of the classic world selector. +pub const WORLD_ICON_SLOTS: usize = 32; pub fn decode(path: &Path) -> Result<(u32, u32, Vec)> { decode_bytes(&fs::read(path)?) } @@ -201,10 +205,25 @@ impl HudAtlas { for i in 0..MAP_SLOTS { images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4])); } + // The minimap extra's image (game/extras.rs). + images.push(( + MINIMAP_SPRITE.into(), + crate::minimap::SIZE as u32, + crate::minimap::SIZE as u32, + vec![0; crate::minimap::SIZE * crate::minimap::SIZE * 4], + )); // Downloaded skins (game/scoreboard.rs) likewise. for i in 0..SKIN_SLOTS { images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4])); } + for i in 0..WORLD_ICON_SLOTS { + images.push(( + format!("horizon/world-icon{i}"), + 64, + 64, + vec![0; 64 * 64 * 4], + )); + } // Horizon-style menu text and corner masks (ui_theme), rasterized at run time. images.push(( "horizon/ui-text".into(), @@ -314,6 +333,9 @@ pub struct HudBatch { pub height: f32, /// Glyph pixels to upload into the atlas before drawing. pub patches: Vec, + /// Vertex ranges drawn with `RenderPipelines.CROSSHAIR`'s + /// `BlendFunction.INVERT` instead of alpha blending. + pub invert: Vec>, } pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 { u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r) @@ -336,8 +358,37 @@ impl HudBatch { width: (window[0] as f32 / scale as f32).ceil(), height: (window[1] as f32 / scale as f32).ceil(), patches: Vec::new(), + invert: Vec::new(), } } + /// Draw the vertices added since `start` with the inverting blend. + pub fn invert_since(&mut self, start: usize) { + let range = start as u32..self.vertices.len() as u32; + if range.is_empty() { + return; + } + match self.invert.last_mut() { + Some(last) if last.end == range.start => last.end = range.end, + _ => self.invert.push(range), + } + } + /// The vertex ranges in order, each with whether it inverts. + pub fn runs(&self) -> Vec<(std::ops::Range, bool)> { + let mut out = Vec::new(); + let mut at = 0; + for r in &self.invert { + if r.start > at { + out.push((at..r.start, false)); + } + out.push((r.clone(), true)); + at = r.end; + } + let end = self.vertices.len() as u32; + if end > at { + out.push((at..end, false)); + } + out + } /// `AbstractContainerScreen.init`: center in integer GUI coordinates. pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) { ( @@ -627,6 +678,8 @@ pub struct HudRenderer { /// The shared atlas texture, for run-time glyph uploads. pub atlas_texture: Option, pipeline: wgpu::RenderPipeline, + /// `RenderPipelines.CROSSHAIR`. + invert_pipeline: wgpu::RenderPipeline, group: wgpu::BindGroup, uniform: wgpu::Buffer, buffer: wgpu::Buffer, @@ -707,35 +760,55 @@ impl HudRenderer { ..Default::default() }); let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4]; - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("HUD"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - compilation_options: Default::default(), - buffers: &[Some(wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as u64, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &attributes, - })], + let create = |label, blend| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + compilation_options: Default::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &attributes, + })], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(blend), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }; + let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING); + // BlendFunction.INVERT: ONE_MINUS_DST_COLOR, ONE_MINUS_SRC_COLOR, + // ONE, ZERO. + let invert_pipeline = create( + "HUD crosshair", + wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::OneMinusDst, + dst_factor: wgpu::BlendFactor::OneMinusSrc, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::Zero, + operation: wgpu::BlendOperation::Add, + }, }, - primitive: Default::default(), - depth_stencil: None, - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format, - blend: Some(wgpu::BlendState::ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - multiview_mask: None, - cache: None, - }); + ); let capacity = 1 << 16; let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("HUD vertices"), @@ -747,6 +820,7 @@ impl HudRenderer { atlas_texture: None, fire_animations: Vec::new(), pipeline, + invert_pipeline, group, uniform, buffer, @@ -860,10 +934,16 @@ impl HudRenderer { color_attachments: &attachments, ..Default::default() }); - pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, &self.group, &[]); pass.set_vertex_buffer(0, self.buffer.slice(..)); - pass.draw(0..count as u32, 0..1); + for (range, invert) in batch.runs() { + pass.set_pipeline(if invert { + &self.invert_pipeline + } else { + &self.pipeline + }); + pass.draw(range, 0..1); + } } } @@ -871,6 +951,25 @@ impl HudRenderer { mod tests { use super::*; + #[test] + fn inverted_ranges_split_the_draws_in_order() { + let mut batch = HudBatch::new([854, 480]); + let quad = |b: &mut HudBatch| b.quad([[0.0; 2]; 4], [[0.0; 2]; 4], 0); + quad(&mut batch); + let start = batch.vertices.len(); + quad(&mut batch); + batch.invert_since(start); + let start = batch.vertices.len(); + quad(&mut batch); + batch.invert_since(start); + batch.invert_since(batch.vertices.len()); + quad(&mut batch); + assert_eq!(batch.invert, vec![6..18]); + assert_eq!( + batch.runs(), + vec![(0..6, false), (6..18, true), (18..24, false)] + ); + } #[test] fn container_origins_use_java_integer_division() { // Odd scaled dimensions, odd image sizes and an oversized panel. @@ -881,6 +980,7 @@ mod tests { width: width as f32, height: height as f32, patches: Vec::new(), + invert: Vec::new(), }; for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] { assert_eq!( diff --git a/crates/horizon-client/src/hud_layout.rs b/crates/horizon-client/src/hud_layout.rs index ab28ece3e..d2f3df0d9 100644 --- a/crates/horizon-client/src/hud_layout.rs +++ b/crates/horizon-client/src/hud_layout.rs @@ -44,6 +44,8 @@ pub enum Blend { Vignette, /// `GUI_NAUSEA_OVERLAY`: additive. Nausea, + /// `CROSSHAIR`: `BlendFunction.INVERT`, the colour under it inverted. + Crosshair, } impl Blend { pub fn pipeline(self) -> &'static str { @@ -51,6 +53,7 @@ impl Blend { Blend::Textured => "pipeline/gui_textured", Blend::Vignette => "pipeline/vignette", Blend::Nausea => "pipeline/gui_nausea_overlay", + Blend::Crosshair => "pipeline/crosshair", } } } @@ -58,8 +61,8 @@ impl Blend { /// One `GuiGraphicsExtractor` call. #[derive(Clone, Debug, PartialEq)] pub enum GuiDraw { - /// `blitSprite(sprite, x, y, w, h, color)`; `region` = (spriteW, - /// spriteH, u, v) for the partial overload. + /// `blitSprite(pipeline, sprite, x, y, w, h, color)`; `region` = + /// (spriteW, spriteH, u, v) for the partial overload. Sprite { sprite: Cow<'static, str>, x: i32, @@ -68,6 +71,7 @@ pub enum GuiDraw { h: i32, region: Option<[i32; 4]>, color: u32, + blend: Blend, }, /// `blitSprite(pipeline, TextureAtlasSprite, ...)` with a block atlas /// sprite (the nether portal overlay). @@ -136,6 +140,7 @@ fn sprite(sprite: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw { h, region: None, color: WHITE, + blend: Blend::Textured, } } fn region( @@ -154,8 +159,16 @@ fn region( h, region: Some([size[0], size[1], uv[0], uv[1]]), color: WHITE, + blend: Blend::Textured, } } +/// A draw through `RenderPipelines.CROSSHAIR`. +fn crosshair_blend(mut d: GuiDraw) -> GuiDraw { + if let GuiDraw::Sprite { blend, .. } = &mut d { + *blend = Blend::Crosshair; + } + d +} /// `graphics.fill`: the corners are sorted. pub fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: u32) -> GuiDraw { GuiDraw::Fill { @@ -365,10 +378,25 @@ pub fn hotbar(w: i32, h: i32, i: &HotbarInputs) -> Vec { out } -/// `Hud.extractCrosshair` (first person, not hidden for spectators): -/// `attack` is `getAttackStrengthScale(0)` in CROSSHAIR indicator mode and -/// `full` whether the full indicator shows for a target in reach. +/// `Hud.extractCrosshair`'s full attack indicator: at full strength on a +/// living, alive `crosshairPickEntity` (`target`) with a weapon slower than +/// `MIN_CROSSHAIR_ATTACK_SPEED` (`delay` is +/// `getCurrentItemAttackStrengthDelay`). +pub fn full_attack_indicator(scale: f32, delay: f32, target: Option) -> bool { + scale >= 1.0 && delay > 5.0 && target == Some(true) +} + +/// `Hud.extractCrosshair` (first person, not hidden for spectators), every +/// sprite through the inverting `CROSSHAIR` pipeline: `attack` is +/// `getAttackStrengthScale(0)` in CROSSHAIR indicator mode and `full` +/// whether the full indicator shows ([`full_attack_indicator`]). pub fn crosshair(w: i32, h: i32, attack: Option, full: bool) -> Vec { + crosshair_draws(w, h, attack, full) + .into_iter() + .map(crosshair_blend) + .collect() +} +fn crosshair_draws(w: i32, h: i32, attack: Option, full: bool) -> Vec { let mut out = vec![sprite("hud/crosshair", (w - 15) / 2, (h - 15) / 2, 15, 15)]; if let Some(scale) = attack { let (x, y) = (w / 2 - 8, h / 2 - 7 + 16); @@ -760,6 +788,7 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra h, region, color, + blend, } => { let Some(mut r) = atlas.sprites.get(&format!("gui/sprites/{sprite}")).copied() else { @@ -775,6 +804,9 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra r.v0 = v0; } batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, abgr(*color)); + if *blend == Blend::Crosshair { + batch.invert_since(start); + } } GuiDraw::AtlasSprite { sprite, diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index 8468735c3..539e00a33 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -160,6 +160,7 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec { h: 24, region: None, color: crate::hud_layout::WHITE, + blend: crate::hud_layout::Blend::Textured, }); out.push(GuiDraw::Sprite { sprite: Cow::Owned(format!("mob_effect/{}", e.id)), @@ -169,6 +170,7 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec { h: 18, region: None, color: white(alpha), + blend: crate::hud_layout::Blend::Textured, }); } out @@ -477,6 +479,7 @@ pub fn boss_overlay(w: i32, h: i32, bars: &[BossBar], font: &Font) -> Vec Vec { h: 5, region, color: crate::hud_layout::WHITE, + blend: crate::hud_layout::Blend::Textured, }; let mut out = vec![sprite("hud/jump_bar_background", 182, None)]; if cooldown > 0 { diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 54e385383..6ca321edd 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -263,6 +263,22 @@ impl ChunkEncoder { } sections.push(encoded); } + // A loaded chunk's block entities enter its maps in the save's order + // (ChunkAccess.pendingBlockEntities, then LevelChunk.blockEntities): + // keys that share a bucket keep that order. Others follow in scan order. + if let Some(order) = chunk.saved.as_ref().map(|s| &s.block_entity_order) + && !order.is_empty() + { + let at = |e: &BlockEntityInfo| { + let pos = ( + chunk.x * 16 + i32::from(e.packed_xz as u8 >> 4), + i32::from(e.y), + chunk.z * 16 + i32::from(e.packed_xz as u8 & 15), + ); + order.iter().position(|p| *p == pos).unwrap_or(usize::MAX) + }; + entity_infos.sort_by_key(at); + } java_hash_order(&mut entity_infos, |e| { ( chunk.x * 16 + i32::from(e.packed_xz as u8 >> 4), diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 6929aa9a4..58616e569 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -4,6 +4,7 @@ pub mod advancements; pub mod ambience; pub mod animate_tick; +pub mod arrows; pub mod assets; pub mod atlas_sources; pub mod attack_strength; @@ -44,9 +45,12 @@ pub mod datapack; pub mod debug_keys; pub mod effects; pub mod enchant; +pub mod end_crystal; pub mod entities; pub mod entity_nbt; pub mod environment; +pub mod extras; +pub mod extras_hud; pub mod fast_hash; pub mod fastutil_order; pub mod fire_render; @@ -86,6 +90,8 @@ pub mod logging; pub mod menu; pub mod merchant; pub mod mesher; +pub mod minimap; +pub mod mipmap; pub mod mobs; pub mod models; pub mod motion; @@ -112,6 +118,7 @@ pub mod raid; pub mod random_sequences; pub mod recipe_book; pub mod recipe_book_screen; +pub mod reconnect; pub mod save; pub mod scoreboard; pub mod scoreboard_cmd; diff --git a/crates/horizon-client/src/minimap.rs b/crates/horizon-client/src/minimap.rs new file mode 100644 index 000000000..8015e2ab2 --- /dev/null +++ b/crates/horizon-client/src/minimap.rs @@ -0,0 +1,679 @@ +//! The minimap extra (`docs/extras.md`): a 16x16 tile per loaded chunk with +//! each column's vanilla map colour (`MapColor`, as `MapItem.update` picks +//! it), height and water depth, and a 128x128 image composed from the tiles +//! around the player with the map item's height and water shading. +//! +//! Tiles are filled nearest first within a time budget and rescanned after +//! block changes; the image is recomposed only when the view moved or a tile +//! changed. +use crate::{ + blocks::{BlockFacts, Fluid, MAP_COLORS}, + chunk::{Chunk, MIN_Y, SECTIONS}, + fast_hash::FxHashMap, + world::World, +}; +use std::time::{Duration, Instant}; + +/// The image's side in texels. +pub const SIZE: usize = 128; +/// Marks a column the map cuts through (a wall at the player's height). +const WALL: u8 = 0x80; +/// Water's and lava's map colours (`MapColor.WATER`, `FIRE`). +const WATER: u8 = 12; +const LAVA: u8 = 4; +/// A tile whose chunk changed is rescanned at most this often. +const RESCAN: Duration = Duration::from_secs(1); + +/// What the map shows of each column. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layer { + /// The top block, as map items show it. + Surface, + /// Underground, in the Nether or under a roof: the floor below this + /// height (the player's head), and walls cut at it. + Below(i32), +} + +/// What the scan needs of each block state. +pub struct Palette { + /// Map colour id, 0 for none. + color: Vec, + /// 0 none, 1 water, 2 lava; | 4 for air; | 8 when sturdy on top. + flags: Vec, +} +const FLUID: u8 = 3; +const AIR: u8 = 4; +const STURDY_TOP: u8 = 8; +impl Palette { + pub fn new(facts: &BlockFacts) -> Self { + let mut color = Vec::with_capacity(facts.states.len()); + let mut flags = Vec::with_capacity(facts.states.len()); + for (i, f) in facts.states.iter().enumerate() { + color.push(f.map_color); + let mut b = match f.fluid { + Fluid::None => 0, + Fluid::Water => 1, + Fluid::Lava => 2, + }; + if facts.is_air(horizon_world::registry::BlockStateId(i as u32)) { + b |= AIR; + } + // isFaceSturdy(UP, FULL): Direction.UP's ordinal is 1. + if f.sturdy_full >> 1 & 1 != 0 { + b |= STURDY_TOP; + } + flags.push(b); + } + Self { color, flags } + } + /// A palette from (colour, flags) per state id (tests). + #[cfg(test)] + fn from_parts(parts: &[(u8, u8)]) -> Self { + Self { + color: parts.iter().map(|p| p.0).collect(), + flags: parts.iter().map(|p| p.1).collect(), + } + } + #[inline] + fn get(&self, id: u16) -> (u8, u8) { + let i = usize::from(id); + ( + self.color.get(i).copied().unwrap_or(0), + self.flags.get(i).copied().unwrap_or(AIR), + ) + } +} + +#[derive(Clone)] +struct Tile { + /// Map colour id per column (`z * 16 + x`), `| WALL` for cut walls. + color: [u8; 256], + height: [i16; 256], + /// Water depth below the surface, for the map's water shading. + depth: [u8; 256], + revision: u64, + layer: Layer, + scanned: Instant, +} +/// `MapItem.update` for one column: the first block with a map colour +/// going down, the fluid's colour over a fluid unless the block is sturdy on +/// top (`getCorrectStateForFluidBlock`), and the fluid's depth. +fn scan_column( + chunk: &Chunk, + palette: &Palette, + x: i32, + z: i32, + top: i32, + layer: Layer, +) -> (u8, i16, u8) { + let mut y = top; + if let Layer::Below(head) = layer { + let (color, flags) = palette.get(chunk.get(x, head, z)); + if flags & AIR == 0 && color != 0 && flags & FLUID == 0 { + return (color | WALL, head as i16, 0); + } + } + while y > MIN_Y { + let (mut color, flags) = palette.get(chunk.get(x, y, z)); + if color == 0 { + y -= 1; + continue; + } + let mut depth = 0u8; + let fluid = flags & FLUID; + if fluid != 0 { + let mut below = y - 1; + while below > MIN_Y && palette.get(chunk.get(x, below, z)).1 & FLUID != 0 { + depth = depth.saturating_add(1); + below -= 1; + } + depth = depth.saturating_add(1); + if flags & STURDY_TOP == 0 { + color = if fluid == 2 { LAVA } else { WATER }; + } + } + return (color, y as i16, depth); + } + (0, MIN_Y as i16, 0) +} +/// The highest block of a chunk worth scanning from. +fn top_of(chunk: &Chunk, air: u16, layer: Layer) -> i32 { + let surface = (0..SECTIONS) + .rev() + .find(|&s| { + chunk + .sections + .get(s) + .is_some_and(|sec| !sec.is_uniform(air)) + }) + .map_or(MIN_Y, |s| MIN_Y + s as i32 * 16 + 15); + match layer { + Layer::Surface => surface, + Layer::Below(head) => surface.min(head), + } +} +fn scan_tile(chunk: &Chunk, palette: &Palette, air: u16, layer: Layer, revision: u64) -> Tile { + let top = top_of(chunk, air, layer); + let mut tile = Tile { + color: [0; 256], + height: [MIN_Y as i16; 256], + depth: [0; 256], + revision, + layer, + scanned: Instant::now(), + }; + for z in 0..16 { + for x in 0..16 { + let (c, h, d) = scan_column(chunk, palette, x, z, top, layer); + let i = (z * 16 + x) as usize; + tile.color[i] = c; + tile.height[i] = h; + tile.depth[i] = d; + } + } + tile +} + +/// Where the map looks from and how. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct View { + pub x: f64, + pub z: f64, + /// The player's yaw in degrees (0 faces south). + pub yaw: f32, + /// The map turns with the player (forward is up), or north is up. + pub rotate: bool, + pub blocks_per_pixel: f32, + pub round: bool, +} +impl View { + /// Whether the image for `self` would look different from `other`'s. + fn differs(&self, other: &View) -> bool { + let moved = ((self.x - other.x).abs().max((self.z - other.z).abs()) as f32) + >= self.blocks_per_pixel / 4.0; + let turned = self.rotate && (self.yaw - other.yaw).abs() >= 0.5; + moved + || turned + || self.rotate != other.rotate + || self.round != other.round + || self.blocks_per_pixel != other.blocks_per_pixel + } + /// The world's right and forward directions as the map's x and up. + fn axes(&self) -> ([f64; 2], [f64; 2]) { + if !self.rotate { + return ([1.0, 0.0], [0.0, -1.0]); + } + let (s, c) = f64::from(self.yaw).to_radians().sin_cos(); + ([-c, -s], [-s, c]) + } + /// Where north is on the map's rim, as a unit direction (x right, y down). + pub fn north(&self) -> (f32, f32) { + let (r, f) = self.axes(); + // The direction (0, -1) in the map's (right, -forward) basis. + (-r[1] as f32, f[1] as f32) + } +} + +/// `MapColor.getColorFromPackedId` as RGBA. +fn packed_rgba(id: u8, brightness: u8) -> [u8; 4] { + let id = usize::from(id); + if id == 0 || id >= MAP_COLORS.len() { + return [0; 4]; + } + let modifier = [180u32, 220, 255, 135][usize::from(brightness & 3)]; + let col = MAP_COLORS[id]; + let ch = |s: u32| ((col >> s & 255) * modifier / 255) as u8; + [ch(16), ch(8), ch(0), 255] +} +/// The map item's shading at scale 1: brighter facing a lower north +/// neighbour, darker facing a higher one, dithered; water by depth. +fn brightness(color: u8, height: i16, north: Option, depth: u8, parity: i32) -> u8 { + if color & WALL != 0 { + return 3; + } + let parity = f64::from(parity & 1); + if color == WATER { + let diff = f64::from(depth) * 0.1 + parity * 0.2; + return if diff < 0.5 { + 2 + } else if diff > 0.9 { + 0 + } else { + 1 + }; + } + let north = north.unwrap_or(height); + let diff = f64::from(height - north) * 4.0 / 5.0 + (parity - 0.5) * 0.4; + if diff > 0.6 { + 2 + } else if diff < -0.6 { + 0 + } else { + 1 + } +} +const UNKNOWN: [u8; 4] = [20, 20, 20, 200]; +const BORDER: [u8; 4] = [10, 10, 10, 230]; + +#[derive(Default)] +pub struct Minimap { + tiles: FxHashMap<(i32, i32), Tile>, + palette: Option, + composed: Option, + /// Tiles changed since the image was composed. + changed: bool, + /// The composed image, `SIZE` x `SIZE` RGBA. + pub image: Vec, +} +impl Minimap { + /// Forget everything (a new world or dimension, or the minimap turned off). + pub fn clear(&mut self) { + let palette = self.palette.take(); + *self = Self { + palette, + ..Self::default() + }; + } + /// Fill and refresh tiles around chunk `center` within `radius` chunks, + /// nearest first, until `budget` is spent. Returns the tiles scanned. + pub fn update( + &mut self, + world: &World, + facts: &BlockFacts, + center: (i32, i32), + radius: i32, + layer: Layer, + budget: Duration, + ) -> usize { + let palette = self.palette.get_or_insert_with(|| Palette::new(facts)); + let started = Instant::now(); + let air = world.air.0 as u16; + // Tiles of unloaded or distant chunks go. + self.tiles.retain(|k, _| { + (k.0 - center.0).abs() <= radius + 2 + && (k.1 - center.1).abs() <= radius + 2 + && world.chunks.contains_key(k) + }); + let mut scanned = 0; + for ring in 0..=radius { + for (dx, dz) in ring_offsets(ring) { + let key = (center.0 + dx, center.1 + dz); + let Some(chunk) = world.chunks.get(&key) else { + continue; + }; + let stale = match self.tiles.get(&key) { + None => true, + Some(t) if t.layer != layer => true, + Some(t) => t.revision != world.revision && t.scanned.elapsed() >= RESCAN, + }; + if !stale { + continue; + } + let tile = scan_tile(chunk, palette, air, layer, world.revision); + if self.tiles.get(&key).is_none_or(|t| { + t.color != tile.color || t.height != tile.height || t.depth != tile.depth + }) { + self.changed = true; + } + self.tiles.insert(key, tile); + scanned += 1; + if started.elapsed() >= budget { + return scanned; + } + } + } + scanned + } + /// Recompose the image if the view or the tiles changed; true when it did. + pub fn compose(&mut self, view: View) -> bool { + if !self.changed + && self.composed.is_some_and(|c| !view.differs(&c)) + && !self.image.is_empty() + { + return false; + } + self.changed = false; + self.composed = Some(view); + self.image.resize(SIZE * SIZE * 4, 0); + let (r, f) = view.axes(); + let bpp = f64::from(view.blocks_per_pixel); + let half = SIZE as f64 / 2.0; + let mut cached: Option<((i32, i32), &Tile)> = None; + let mut column = |x: i32, z: i32| -> Option<(u8, i16, u8)> { + let key = (x >> 4, z >> 4); + let tile = match cached { + Some((k, t)) if k == key => t, + _ => { + let t = self.tiles.get(&key)?; + cached = Some((key, t)); + t + } + }; + let i = ((z & 15) * 16 + (x & 15)) as usize; + Some((tile.color[i], tile.height[i], tile.depth[i])) + }; + for j in 0..SIZE { + for i in 0..SIZE { + let (u, v) = (i as f64 + 0.5 - half, j as f64 + 0.5 - half); + let o = (j * SIZE + i) * 4; + let edge = if view.round { + let d = (u * u + v * v).sqrt(); + if d > half { + self.image[o..o + 4].copy_from_slice(&[0; 4]); + continue; + } + d > half - 1.5 + } else { + i == 0 || j == 0 || i == SIZE - 1 || j == SIZE - 1 + }; + if edge { + self.image[o..o + 4].copy_from_slice(&BORDER); + continue; + } + let wx = view.x + bpp * (u * r[0] - v * f[0]); + let wz = view.z + bpp * (u * r[1] - v * f[1]); + let (x, z) = (wx.floor() as i32, wz.floor() as i32); + let rgba = match column(x, z) { + Some((color, height, depth)) if color & !WALL != 0 => { + let north = column(x, z - 1).filter(|c| c.0 & !WALL != 0).map(|c| c.1); + let b = brightness(color, height, north, depth, x + z); + packed_rgba(color & !WALL, b) + } + _ => UNKNOWN, + }; + self.image[o..o + 4].copy_from_slice(&rgba); + } + } + true + } + pub fn tile_count(&self) -> usize { + self.tiles.len() + } +} +/// Chunk offsets at Chebyshev distance `ring`. +fn ring_offsets(ring: i32) -> impl Iterator { + (-ring..=ring).flat_map(move |dz| { + (-ring..=ring) + .filter(move |&dx| dx.abs() == ring || dz.abs() == ring) + .map(move |dx| (dx, dz)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + // States: 0 air, 1 grass (colour 1), 2 stone (11), 3 water, 4 glass (no + // colour), 5 waterlogged slab (sturdy on top? no), 6 lava. + fn palette() -> Palette { + Palette::from_parts(&[ + (0, AIR), + (1, STURDY_TOP), + (11, STURDY_TOP), + (WATER, 1), + (0, 0), + (11, 1), + (LAVA, 2), + ]) + } + fn chunk(columns: &[(i32, i32, &[(i32, u16)])]) -> Chunk { + let mut c = Chunk::empty(0, 0); + for &(x, z, blocks) in columns { + for &(y, id) in blocks { + c.set(x, y, z, id); + } + } + c + } + + #[test] + fn columns_take_the_first_coloured_block_and_fluids_over_it() { + let p = palette(); + let c = chunk(&[ + (0, 0, &[(60, 2), (61, 1)]), + // Glass has no map colour: the grass under it shows. + (1, 0, &[(61, 1), (62, 4)]), + // Three water over stone. + (2, 0, &[(60, 2), (61, 3), (62, 3), (63, 3)]), + (3, 0, &[(70, 6)]), + ]); + let top = top_of(&c, 0, Layer::Surface); + assert_eq!(top, 79); + assert_eq!(scan_column(&c, &p, 0, 0, top, Layer::Surface), (1, 61, 0)); + assert_eq!(scan_column(&c, &p, 1, 0, top, Layer::Surface), (1, 61, 0)); + assert_eq!( + scan_column(&c, &p, 2, 0, top, Layer::Surface), + (WATER, 63, 3) + ); + assert_eq!( + scan_column(&c, &p, 3, 0, top, Layer::Surface), + (LAVA, 70, 1) + ); + assert_eq!(scan_column(&c, &p, 4, 0, top, Layer::Surface).0, 0); + } + + #[test] + fn a_waterlogged_block_not_sturdy_on_top_shows_water() { + let p = palette(); + let c = chunk(&[(0, 0, &[(60, 2), (61, 5)])]); + assert_eq!( + scan_column(&c, &p, 0, 0, 70, Layer::Surface), + (WATER, 61, 1) + ); + } + + #[test] + fn below_a_height_shows_the_floor_and_cuts_walls() { + let p = palette(); + // A cave: stone everywhere from 0 to 20, air at 10 and 11 in column 0. + let mut blocks: Vec<(i32, u16)> = (0..=20).map(|y| (y, 2)).collect(); + let solid = blocks.clone(); + blocks.retain(|&(y, _)| y != 10 && y != 11); + let c = chunk(&[(0, 0, &blocks), (1, 0, &solid)]); + let layer = Layer::Below(11); + let top = top_of(&c, 0, layer); + assert_eq!(top, 11); + assert_eq!(scan_column(&c, &p, 0, 0, top, layer), (11, 9, 0)); + assert_eq!(scan_column(&c, &p, 1, 0, top, layer), (11 | WALL, 11, 0)); + // The surface view sees the roof. + assert_eq!(scan_column(&c, &p, 0, 0, 31, Layer::Surface), (11, 20, 0)); + } + + #[test] + fn shading_follows_the_map_item() { + // Higher than the north neighbour: bright; lower: dark; level: normal. + assert_eq!(brightness(1, 65, Some(64), 0, 0), 2); + assert_eq!(brightness(1, 63, Some(64), 0, 1), 0); + assert_eq!(brightness(1, 64, Some(64), 0, 0), 1); + assert_eq!(brightness(1, 64, Some(64), 0, 1), 1); + // Shallow water is bright, deep water dark. + assert_eq!(brightness(WATER, 62, None, 1, 0), 2); + assert_eq!(brightness(WATER, 62, None, 10, 0), 0); + assert_eq!(brightness(1 | WALL, 0, None, 0, 0), 3); + assert_eq!(packed_rgba(1, 2), [127, 178, 56, 255]); + assert_eq!(packed_rgba(0, 2), [0; 4]); + } + + fn world_with(chunks: Vec) -> World { + let mut w = World::new(horizon_world::registry::BlockStateId(0), 0); + for c in chunks { + w.chunks.insert((c.x, c.z), Arc::new(c)); + } + w + } + fn grass_chunk(x: i32, z: i32) -> Chunk { + let mut c = Chunk::empty(x, z); + for bz in 0..16 { + for bx in 0..16 { + c.set(bx, 64, bz, 1); + } + } + c + } + + #[test] + fn tiles_fill_nearest_first_and_follow_changes() { + let mut map = Minimap { + palette: Some(palette()), + ..Default::default() + }; + let facts = BlockFacts { + states: Vec::new(), + air: horizon_world::registry::BlockStateId(0), + }; + let mut world = world_with( + (-2..=2) + .flat_map(|x| (-2..=2).map(move |z| grass_chunk(x, z))) + .collect(), + ); + // A zero budget still scans one tile: the player's own chunk. + assert_eq!( + map.update(&world, &facts, (0, 0), 2, Layer::Surface, Duration::ZERO), + 1 + ); + assert!(map.tiles.contains_key(&(0, 0))); + let n = map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Surface, + Duration::from_secs(1), + ); + assert_eq!(n, 24); + assert_eq!(map.tile_count(), 25); + // Nothing changed: nothing to scan. + assert_eq!( + map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Surface, + Duration::from_secs(1) + ), + 0 + ); + // A changed world is rescanned once the tiles are old enough. + world + .set(0, 70, 0, horizon_world::registry::BlockStateId(2)) + .unwrap(); + assert_eq!( + map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Surface, + Duration::from_secs(1) + ), + 0 + ); + for t in map.tiles.values_mut() { + t.scanned -= RESCAN; + } + assert_eq!( + map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Surface, + Duration::from_secs(1) + ), + 25 + ); + assert_eq!(map.tiles[&(0, 0)].color[0], 11); + // A new layer rescans everything; unloaded chunks drop out. + world.chunks.remove(&(2, 2)); + let n = map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Below(70), + Duration::from_secs(1), + ); + assert_eq!(n, 24); + assert!(!map.tiles.contains_key(&(2, 2))); + } + + #[test] + fn the_image_is_north_up_or_turns_with_the_player() { + let mut map = Minimap { + palette: Some(palette()), + ..Default::default() + }; + let facts = BlockFacts { + states: Vec::new(), + air: horizon_world::registry::BlockStateId(0), + }; + // Grass everywhere, one stone block 10 blocks north of the player. + let mut world = world_with( + (-4..=4) + .flat_map(|x| (-4..=4).map(move |z| grass_chunk(x, z))) + .collect(), + ); + world + .set(0, 64, -10, horizon_world::registry::BlockStateId(2)) + .unwrap(); + map.update( + &world, + &facts, + (0, 0), + 4, + Layer::Surface, + Duration::from_secs(1), + ); + let pixel = |map: &Minimap, i: usize, j: usize| { + let o = (j * SIZE + i) * 4; + [map.image[o], map.image[o + 1], map.image[o + 2]] + }; + let stone = [96, 96, 96]; + let mut view = View { + x: 0.0, + z: 0.0, + yaw: 0.0, + rotate: false, + blocks_per_pixel: 1.0, + round: false, + }; + assert!(map.compose(view)); + assert!(!map.compose(view), "the same view is not recomposed"); + // North up: the stone is 10 pixels above the centre. + assert_eq!(pixel(&map, 64, 54), stone); + // Turning with the player facing east (yaw -90): north is to the left. + view.rotate = true; + view.yaw = -90.0; + assert!(map.compose(view)); + assert_eq!(pixel(&map, 54, 63), stone); + let (nx, ny) = view.north(); + assert!((nx + 1.0).abs() < 1e-5 && ny.abs() < 1e-5, "{nx} {ny}"); + // Facing north, north is up. + view.yaw = 180.0; + map.compose(view); + assert_eq!(pixel(&map, 64, 54), stone); + // Round maps are transparent in the corners, framed at the edge. + view.round = true; + map.compose(view); + assert_eq!(map.image[3], 0); + assert_eq!(&map.image[(64 * SIZE) * 4..(64 * SIZE) * 4 + 4], &BORDER); + // A small move recomposes only once it is visible. + view.x += 0.1; + assert!(!map.compose(view)); + view.x += 0.2; + assert!(map.compose(view)); + } + + #[test] + fn rings_cover_each_offset_once() { + let mut seen = std::collections::HashSet::new(); + for r in 0..=3 { + for o in ring_offsets(r) { + assert!(seen.insert(o)); + } + } + assert_eq!(seen.len(), 49); + } +} diff --git a/crates/horizon-client/src/mipmap.rs b/crates/horizon-client/src/mipmap.rs new file mode 100644 index 000000000..98911e54f --- /dev/null +++ b/crates/horizon-client/src/mipmap.rs @@ -0,0 +1,334 @@ +//! `MipmapGenerator`: the mip levels of a sprite. Cutout textures keep the +//! alpha-test coverage of their base level at every level +//! (`scaleAlphaToCoverage`), so thin cutout edges (cactus sides, leaves, +//! flowers) don't erode into gaps with distance; colours average in linear +//! light (`ARGB.meanLinear`). + +/// `MipmapStrategy`, from the texture's `.mcmeta` `texture` section. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Strategy { + #[default] + Auto, + Mean, + Cutout, + StrictCutout, + DarkCutout, +} +impl Strategy { + pub fn parse(name: &str) -> Option { + Some(match name { + "auto" => Self::Auto, + "mean" => Self::Mean, + "cutout" => Self::Cutout, + "strict_cutout" => Self::StrictCutout, + "dark_cutout" => Self::DarkCutout, + _ => return None, + }) + } +} + +/// How a sprite's mips are made: its `.mcmeta` `texture` section, whether +/// it has a fully transparent pixel and whether it is an `item/` sprite. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Settings { + pub strategy: Strategy, + pub alpha_cutoff_bias: f32, + pub has_transparent: bool, + pub item: bool, +} + +/// A square or rectangular RGBA8 image, rows top to bottom. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Image { + pub width: u32, + pub height: u32, + pub pixels: Vec<[u8; 4]>, +} +impl Image { + fn get(&self, x: u32, y: u32) -> [u8; 4] { + self.pixels[(x + y * self.width) as usize] + } + fn set(&mut self, x: u32, y: u32, p: [u8; 4]) { + self.pixels[(x + y * self.width) as usize] = p; + } +} + +/// `ARGB.SRGB_TO_LINEAR`: an sRGB channel in linear light, 0 to 1023. +fn srgb_to_linear() -> &'static [u16; 256] { + static TABLE: std::sync::OnceLock<[u16; 256]> = std::sync::OnceLock::new(); + TABLE.get_or_init(|| { + std::array::from_fn(|i| { + let x = i as f32 / 255.0; + let linear = if x >= 0.04045 { + ((f64::from(x) + 0.055) / 1.055).powf(2.4) as f32 + } else { + x / 12.92 + }; + java_round(linear * 1023.0) as u16 + }) + }) +} +/// `ARGB.LINEAR_TO_SRGB`: 1024 linear steps back to sRGB. +fn linear_to_srgb() -> &'static [u8; 1024] { + static TABLE: std::sync::OnceLock<[u8; 1024]> = std::sync::OnceLock::new(); + TABLE.get_or_init(|| { + std::array::from_fn(|i| { + let x = i as f32 / 1023.0; + let srgb = if x >= 0.003_130_8 { + (1.055 * f64::from(x).powf(0.416_666_666_666_666_7) - 0.055) as f32 + } else { + 12.92 * x + }; + java_round(srgb * 255.0) as u8 + }) + }) +} +/// `Math.round(float)`, bit for bit. +fn java_round(a: f32) -> i32 { + let bits = a.to_bits() as i32; + let biased_exp = (bits & 0x7F80_0000) >> 23; + let shift = (22 + 127) - biased_exp; + if shift & -32 == 0 { + let mut r = bits & 0x007F_FFFF | 0x0080_0000; + if bits < 0 { + r = -r; + } + ((r >> shift) + 1) >> 1 + } else { + a as i32 + } +} +/// `ARGB.alphaFloat`. +fn alpha_float(p: [u8; 4]) -> f32 { + f32::from(p[3]) / 255.0 +} + +/// `MipmapGenerator.alphaTestCoverage`: the share of the image (bilinearly +/// subsampled 4x4 per texel) whose scaled alpha passes `alpha_ref`. +fn alpha_test_coverage(image: &Image, alpha_ref: f32, alpha_scale: f32) -> f32 { + let (width, height) = (image.width as i32, image.height as i32); + let mut coverage = 0.0f32; + let a = + |x: i32, y: i32| (alpha_float(image.get(x as u32, y as u32)) * alpha_scale).clamp(0.0, 1.0); + for y in 0..height - 1 { + for x in 0..width - 1 { + let (a00, a10, a01, a11) = (a(x, y), a(x + 1, y), a(x, y + 1), a(x + 1, y + 1)); + let mut texel = 0.0f32; + for sy in 0..4 { + let fy = (sy as f32 + 0.5) / 4.0; + for sx in 0..4 { + let fx = (sx as f32 + 0.5) / 4.0; + let alpha = a00 * (1.0 - fx) * (1.0 - fy) + + a10 * fx * (1.0 - fy) + + a01 * (1.0 - fx) * fy + + a11 * fx * fy; + if alpha > alpha_ref { + texel += 1.0; + } + } + } + coverage += texel / 16.0; + } + } + coverage / ((width - 1) * (height - 1)) as f32 +} + +/// `MipmapGenerator.scaleAlphaToCoverage`: five bisection steps for the +/// alpha scale whose coverage is nearest `desired`, then every alpha scaled +/// and biased. +fn scale_alpha_to_coverage(image: &mut Image, desired: f32, alpha_ref: f32, bias: f32) { + let (mut min_scale, mut max_scale) = (0.0f32, 4.0f32); + let mut scale = 1.0f32; + let mut best_scale = 1.0f32; + let mut best_error = f32::MAX; + for _ in 0..5 { + let current = alpha_test_coverage(image, alpha_ref, scale); + let error = (current - desired).abs(); + if error < best_error { + best_error = error; + best_scale = scale; + } + if current < desired { + min_scale = scale; + } else if current > desired { + max_scale = scale; + } else { + break; + } + scale = (min_scale + max_scale) * 0.5; + } + for p in &mut image.pixels { + let alpha = (alpha_float(*p) * best_scale + bias + 0.025).clamp(0.0, 1.0); + p[3] = (alpha * 255.0).floor() as u8; + } +} + +/// `TextureUtil.solidify`: every transparent pixel takes the colour of the +/// nearest opaque one (breadth first, keeping its zero alpha). +fn solidify(image: &mut Image) { + let (width, height) = (image.width as i32, image.height as i32); + let n = image.pixels.len(); + let mut nearest = vec![[0u8; 4]; n]; + let mut distance = vec![i32::MAX; n]; + let mut queue = std::collections::VecDeque::new(); + for x in 0..width { + for y in 0..height { + let i = (x + y * width) as usize; + let p = image.pixels[i]; + if p[3] != 0 { + distance[i] = 0; + nearest[i] = p; + queue.push_back(i); + } + } + } + while let Some(i) = queue.pop_front() { + let (x, y) = (i as i32 % width, i as i32 / width); + for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { + let (nx, ny) = (x + dx, y + dy); + if nx >= 0 && ny >= 0 && nx < width && ny < height { + let j = (nx + ny * width) as usize; + if distance[j] > distance[i] + 1 { + distance[j] = distance[i] + 1; + nearest[j] = nearest[i]; + queue.push_back(j); + } + } + } + } + for (i, p) in image.pixels.iter_mut().enumerate() { + if p[3] == 0 { + let c = nearest[i]; + *p = [c[0], c[1], c[2], 0]; + } + } +} + +/// `TextureUtil.fillEmptyAreasWithDarkColor`: transparent pixels take three +/// quarters of the darkest visible colour. +fn fill_empty_dark(image: &mut Image) { + let mut darkest = [255u8; 4]; + let mut min = i32::MAX; + for x in 0..image.width { + for y in 0..image.height { + let p = image.get(x, y); + if p[3] != 0 { + let brightness = i32::from(p[0]) + i32::from(p[1]) + i32::from(p[2]); + if brightness < min { + min = brightness; + darkest = p; + } + } + } + } + let dark = |c: u8| (3 * i32::from(c) / 4) as u8; + let fill = [dark(darkest[0]), dark(darkest[1]), dark(darkest[2]), 0]; + for p in &mut image.pixels { + if p[3] == 0 { + *p = fill; + } + } +} + +/// `ARGB.meanLinear`. +fn mean_linear(c: [[u8; 4]; 4]) -> [u8; 4] { + let (to_linear, to_srgb) = (srgb_to_linear(), linear_to_srgb()); + let channel = |k: usize| { + let sum: u32 = c.iter().map(|p| u32::from(to_linear[p[k] as usize])).sum(); + to_srgb[(sum / 4) as usize] + }; + let alpha = c.iter().map(|p| u32::from(p[3])).sum::() / 4; + [channel(0), channel(1), channel(2), alpha as u8] +} + +/// `MipmapGenerator.darkenedAlphaBlend`: the visible pixels' mean in linear +/// light, transparent ones counting as black. +fn darkened_alpha_blend(c: [[u8; 4]; 4]) -> [u8; 4] { + let to_linear = srgb_to_linear(); + let linear = |v: u8| f32::from(to_linear[v as usize]) / 1023.0; + let mut total = [0.0f32; 4]; + for p in c.iter().filter(|p| p[3] != 0) { + total[3] += linear(p[3]); + for k in 0..3 { + total[k] += linear(p[k]); + } + } + let to_srgb = |v: f32| linear_to_srgb()[(v / 4.0 * 1023.0).floor() as usize]; + [ + to_srgb(total[0]), + to_srgb(total[1]), + to_srgb(total[2]), + to_srgb(total[3]), + ] +} + +/// `MipmapGenerator.generateMipLevels` from the base image (`levels` mips +/// below it): `has_transparent` is `Transparency.hasTransparent` (a pixel +/// with zero alpha), `item` whether the sprite is under `item/` (its base +/// is left as is). +pub fn generate( + mut base: Image, + levels: u32, + strategy: Strategy, + alpha_cutoff_bias: f32, + has_transparent: bool, + item: bool, +) -> Vec { + let strategy = match strategy { + Strategy::Auto if has_transparent => Strategy::Cutout, + Strategy::Auto => Strategy::Mean, + s => s, + }; + if !item { + match strategy { + Strategy::Cutout | Strategy::StrictCutout => solidify(&mut base), + Strategy::DarkCutout => fill_empty_dark(&mut base), + _ => {} + } + } + let cutout = matches!( + strategy, + Strategy::Cutout | Strategy::StrictCutout | Strategy::DarkCutout + ); + let alpha_ref = if strategy == Strategy::StrictCutout { + 0.3 + } else { + 0.5 + }; + let coverage = if cutout { + alpha_test_coverage(&base, alpha_ref, 1.0) + } else { + 0.0 + }; + let mut out = vec![base]; + for _ in 1..=levels { + let last = out.last().expect("the base level"); + let (width, height) = (last.width >> 1, last.height >> 1); + let mut data = Image { + width, + height, + pixels: vec![[0; 4]; (width * height) as usize], + }; + for x in 0..width { + for y in 0..height { + let c = [ + last.get(x * 2, y * 2), + last.get(x * 2 + 1, y * 2), + last.get(x * 2, y * 2 + 1), + last.get(x * 2 + 1, y * 2 + 1), + ]; + let p = if strategy == Strategy::DarkCutout { + darkened_alpha_blend(c) + } else { + mean_linear(c) + }; + data.set(x, y, p); + } + } + if cutout { + scale_alpha_to_coverage(&mut data, coverage, alpha_ref, alpha_cutoff_bias); + } + out.push(data); + } + out +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 496530903..b2b63626e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -46,6 +46,7 @@ pub mod nether; pub mod path; pub mod phantom; pub mod piglin; +pub mod rabbit; pub mod raider; pub mod ravager; pub mod render; @@ -826,6 +827,11 @@ pub struct Mob { /// Events a mob tick asks the game to act on. #[derive(Clone, Debug)] pub enum MobEvent { + /// Rabbit entity event 1, sent only when a ground jump actually happens. + RabbitHop { + mob: u32, + 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). @@ -1369,6 +1375,7 @@ pub struct MobWorld<'a> { pub world: &'a World, pub registry: &'a horizon_world::registry::BlockRegistry, pub facts: &'a BlockFacts, + pub movement: &'a horizon_world::movement_properties::BoundMovementProperties, pub collision: &'a BlockCollisionRegistry<'a>, pub data: &'a MobData, pub player: Option, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 43f2d3527..dbc3f54d1 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -172,7 +172,12 @@ pub fn register(m: &mut Mob) { Family::Undead => undead::register(m), Family::Hostile => hostile::register(m), Family::Aquatic => aquatic::register(m), - Family::Generic => generic(m), + Family::Generic => { + generic(m); + if m.species() == Species::Rabbit { + super::rabbit::register(m); + } + } Family::Inert => {} Family::Witch => super::witch::register(m), Family::Tame if m.species() == Species::Cat => super::tame::register_cat(m), @@ -272,8 +277,9 @@ fn generic(m: &mut Mob) { m.ai.targets.add(2, NearestTarget::player(true)); } else { g.add(0, Float); - g.add(1, Panic::new(1.25)); - g.add(5, Stroll::avoiding_water(1.0)); + 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()); } @@ -353,6 +359,9 @@ pub fn tick( } super::warden::pre_tick(m, w, events); base_tick(m, w, events); + if m.species() == Species::Rabbit { + super::rabbit::base_tick(m); + } if m.death_time >= super::creaking::death_limit(m) { // Creaking.tickDeath: a heart's creaking crumbles away. if super::creaking::is_creaking(m) && super::creaking::tearing_down(m) { @@ -363,6 +372,9 @@ pub fn tick( if !m.no_ai { ai_step(m, w, level_random, events); } + if m.species() == Species::Rabbit { + super::rabbit::post_tick(m); + } // Mob.tickHeadTurn -> BodyRotationControl.clientTick (a frozen // creaking's waits). if m.alive() && !(super::creaking::is_creaking(m) && !super::creaking::can_move(m)) { @@ -624,7 +636,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & m.ai.xxa = 0.0; m.ai.zza = 0.0; } - m.handle_jumping(); + m.handle_jumping(w); let input = Vec3::new( f64::from(m.ai.xxa), f64::from(m.ai.yya), @@ -871,6 +883,7 @@ fn server_ai_step( } fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { match m.species() { + Species::Rabbit => super::rabbit::server_ai_step(m), Species::Sheep => {} Species::Zombie | Species::Husk diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index e73e9d0ad..e562e9d1b 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -132,6 +132,9 @@ impl Mob { } /// MoveControl.tick (and the flying / smooth-swimming variants). pub fn move_control_tick(&mut self, w: &MobWorld, events: &mut Vec) { + if self.species() == super::Species::Rabbit { + return super::rabbit::move_control(self, w); + } let attr_speed = self.movement_speed(); match self.ai.mov.kind { MoveKind::Custom => super::ai::custom_move_control(self, w, events), @@ -376,6 +379,9 @@ impl Mob { } /// JumpControl.tick. pub fn jump_control_tick(&mut self) { + if self.species() == super::Species::Rabbit { + return super::rabbit::jump_control(self); + } self.ai.jumping = self.ai.jump; self.ai.jump = false; } diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index 403eaa3c7..0d3feaa6c 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -142,6 +142,19 @@ impl Goal for Swell { m.extra.counter = dir; } } +/// Creeper.tick on a client of a server: the synced fuse direction +/// (DATA_SWELL_DIR, DATA_IS_IGNITED) swells the creeper the renderer draws; +/// the server explodes it. +pub fn creeper_client_tick(m: &mut Mob) { + if !m.alive() { + return; + } + m.previous_swell = m.swell; + if m.extra.flag { + m.extra.counter = 1; + } + m.swell = (m.swell + m.extra.counter).clamp(0, 30); +} /// Creeper.tick: advance the fuse and explode at 30. pub fn creeper_tick(m: &mut Mob, events: &mut Vec) { if !m.alive() { diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 15be02a1d..45ef076d3 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -541,7 +541,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) { start, Some(Who::Mob(m.id)), ); - p.bonus = super::gear::arrow_bonus(m); + p.set_bonus(super::gear::arrow_bonus(m)); // rangedAttackUncertainty at normal difficulty: 14 - 2 * 4. p.shoot( &mut crate::projectiles::own_random(m), diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 22b8f2a29..4cd6d5dc9 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -723,7 +723,7 @@ impl Mob { } } /// The jump part of LivingEntity.aiStep. - pub fn handle_jumping(&mut self) { + pub fn handle_jumping(&mut self, w: &MobWorld) { if self.ai.jumping && self.affected_by_fluids() { let (fluid_height, in_water_with_height) = if self.fluids.in_lava { (self.fluids.lava, false) @@ -739,7 +739,7 @@ impl Mob { if (self.on_ground || in_water_with_height && fluid_height <= threshold) && self.ai.no_jump_delay == 0 { - self.jump_from_ground(); + self.jump_from_ground(w); self.ai.no_jump_delay = 10; } } else { @@ -756,7 +756,11 @@ impl Mob { fn jump_in_liquid(&mut self) { self.velocity.y += if self.ai.nav.can_float { 0.04 } else { 0.3 }; } - pub fn jump_from_ground(&mut self) { + pub fn jump_from_ground(&mut self, w: &MobWorld) { + if self.species() == super::Species::Rabbit { + super::rabbit::jump(self, w); + return; + } if matches!( self.species(), super::Species::Slime | super::Species::MagmaCube | super::Species::SulfurCube diff --git a/crates/horizon-client/src/mobs/rabbit.rs b/crates/horizon-client/src/mobs/rabbit.rs new file mode 100644 index 000000000..05ab0e390 --- /dev/null +++ b/crates/horizon-client/src/mobs/rabbit.rs @@ -0,0 +1,486 @@ +//! Rabbit hopping controls and the clocks consumed by `RabbitModel`. +use super::{Mob, MobEvent, MobWorld, control::Operation}; +use horizon_core::{ + geometry::{Vec3, trig}, + random::RandomSource, +}; + +// Rabbit's transient state in Extra (none of these clocks are saved). +const JUMP_TICKS: usize = 0; +const JUMP_DURATION: usize = 1; +const MOVE_DELAY: usize = 2; +const IDLE_TIMEOUT: usize = 3; +// Client counters start only when the actual ground jump emits entity event 1. +const CLIENT_JUMP_TICKS: usize = 4; +const CLIENT_JUMP_DURATION: usize = 5; + +pub fn register(m: &mut Mob) { + m.ai.mov.kind = super::control::MoveKind::Custom; + m.ai.nav.can_float = true; + m.extra.ints[IDLE_TIMEOUT] = m.random.next_int_bound(40).unwrap_or(0) + 180; +} + +/// Rabbit.baseTick: the idle timeout branch precedes the hop clock branch. +pub fn base_tick(m: &mut Mob) { + let age = m.age as f32; + let leashed = m.extra.leash.is_some(); + if m.extra.ints[IDLE_TIMEOUT] <= 0 && !leashed && !m.no_ai { + m.extra.ints[IDLE_TIMEOUT] = m.random.next_int_bound(40).unwrap_or(0) + 180; + m.anim.states[1].start(age); + } else if m.extra.ints[CLIENT_JUMP_TICKS] > 0 { + m.anim.states[0].start_if_stopped(age); + m.anim.states[1].stop(); + } else { + m.extra.ints[IDLE_TIMEOUT] -= 1; + m.anim.states[0].stop(); + } + if leashed { + m.anim.states[1].stop(); + } +} + +fn start_jumping(m: &mut Mob) { + m.ai.jumping = true; + m.extra.ints[JUMP_DURATION] = 15; + m.extra.ints[JUMP_TICKS] = 0; + let pitch = ((m.random.next_float() - m.random.next_float()) * 0.2 + 1.0) * 0.8; + if !m.silent { + m.outbox.push(MobEvent::Sound( + "entity.rabbit.jump", + [m.position.x, m.position.y, m.position.z], + 1.0, + pitch, + )); + } +} + +/// Rabbit.customServerAiStep: start a hop toward the current path waypoint. +pub fn server_ai_step(m: &mut Mob) { + // RabbitMoveControl.setWantedPosition applies the water override before landing checks. + if m.fluids.in_water && m.ai.mov.speed_modifier > 0.0 { + m.ai.mov.speed_modifier = 1.5; + } + if m.extra.ints[MOVE_DELAY] > 0 { + m.extra.ints[MOVE_DELAY] -= 1; + } + if m.on_ground { + if !m.extra.flag { + m.ai.jumping = false; + m.extra.ints[MOVE_DELAY] = if m.ai.mov.speed_modifier < 2.2 { 10 } else { 3 }; + } + if !m.ai.jump && m.ai.mov.has_wanted() && m.extra.ints[MOVE_DELAY] == 0 { + let mut at = m.ai.mov.wanted; + if let Some(path) = m.ai.nav.path.as_ref().filter(|p| !p.is_done()) { + let p = path.entity_pos_at(path.next, m.width()); + at = [p.x, p.y, p.z]; + } + m.yaw = trig::atan2_degrees(at[2] - m.position.z, at[0] - m.position.x) - 90.0; + start_jumping(m); + } + } + m.extra.flag = m.on_ground; +} + +/// RabbitMoveControl.tick: wait on the ground and restore the last wanted speed in flight. +pub fn move_control(m: &mut Mob, w: &MobWorld) { + prepare_move(m); + m.ground_move_tick(w, m.movement_speed()); +} +fn prepare_move(m: &mut Mob) { + if m.ai.mov.speed_modifier > 0.0 { + m.extra.vector[0] = if m.fluids.in_water { + 1.5 + } else { + m.ai.mov.speed_modifier + }; + } + if m.on_ground && !m.ai.jumping && !m.ai.jump { + m.ai.mov.speed_modifier = 0.0; + m.set_speed(0.0); + } else if m.ai.mov.has_wanted() || m.ai.mov.operation == Operation::Jumping { + m.ai.mov.speed_modifier = if m.fluids.in_water { + 1.5 + } else { + m.extra.vector[0] + }; + } +} + +/// RabbitJumpControl.tick: explicit jump requests do not wait for the landing cooldown. +pub fn jump_control(m: &mut Mob) { + if m.ai.jump { + start_jumping(m); + m.ai.jump = false; + } +} + +/// Rabbit.aiStep runs after the living physics; the fifteenth tick still renders the hop. +pub fn post_tick(m: &mut Mob) { + for (ticks, duration) in [ + (JUMP_TICKS, JUMP_DURATION), + (CLIENT_JUMP_TICKS, CLIENT_JUMP_DURATION), + ] { + if m.extra.ints[ticks] != m.extra.ints[duration] { + m.extra.ints[ticks] += 1; + } else if m.extra.ints[duration] != 0 { + m.extra.ints[ticks] = 0; + m.extra.ints[duration] = 0; + if ticks == JUMP_TICKS { + m.ai.jumping = false; + } + } + } +} + +fn jump_scale(m: &Mob) -> f32 { + let step = + m.ai.nav + .path + .as_ref() + .filter(|p| !p.is_done()) + .is_some_and(|p| f64::from(p.next_node().y) > m.position.y + 0.5); + let high = + m.horizontal_collision || step || m.ai.jumping && m.ai.mov.wanted[1] > m.position.y + 0.5; + let base = if high { + 0.5 + } else if m.ai.mov.speed_modifier <= 0.6 { + 0.2 + } else { + 0.3 + }; + base / 0.42 +} + +/// Rabbit.jumpFromGround: ordinary small hops, larger hops toward raised terrain. +pub fn jump(m: &mut Mob, w: &MobWorld) { + let power = jump_power(m, block_jump_factor(m, w)); + apply_jump(m, power); +} +fn jump_power(m: &Mob, block_factor: f32) -> f32 { + let boost = m + .extra + .effects + .iter() + .find(|e| e.0 == "minecraft:jump_boost") + .map_or(0.0, |e| 0.1 * (e.2 + 1) as f32); + m.attrs.jump_strength as f32 * jump_scale(m) * block_factor + boost +} +fn apply_jump(m: &mut Mob, power: f32) { + if power > 1.0e-5 { + m.velocity.y = f64::from(power).max(m.velocity.y); + } + if m.ai.mov.speed_modifier > 0.0 + && m.velocity.x * m.velocity.x + m.velocity.z * m.velocity.z < 0.01 + { + m.move_relative( + 0.1, + Vec3::new(0.0, if m.is_baby() { 0.5 } else { 1.5 }, 1.0), + ); + } + hop_event(m); + m.outbox.push(MobEvent::RabbitHop { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + }); +} + +/// Rabbit.handleEntityEvent(1): reset the counter without starting the clock early. +pub fn hop_event(m: &mut Mob) { + m.extra.ints[CLIENT_JUMP_DURATION] = 15; + m.extra.ints[CLIENT_JUMP_TICKS] = 0; +} + +fn block_jump_factor(m: &Mob, w: &MobWorld) -> f32 { + let properties = w.movement; + let current = w.world.block( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let below = m.on_pos(0.500_001); + // shortcut: use mobs' existing on_pos until they track supporting blocks like the player. + let lower = w.world.block(below[0], below[1], below[2]); + let current = properties + .get(current) + .expect("validated movement registry") + .coefficients + .jump_factor; + let lower = properties + .get(lower) + .expect("validated movement registry") + .coefficients + .jump_factor; + if current == 1.0 { lower } else { current } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mobs::{ + Anim, Brain, Flags, MobType, Part, Species, + anim::{self, Poses}, + body_anim, + keyframes::Animation, + }; + use serde_json::json; + use std::{collections::HashMap, sync::Arc}; + + fn rabbit() -> Mob { + let model = Arc::new(Part::parse( + "root", + &json!({"children": {"head": {}, "left_hind_foot": {}}}), + )); + let kind = Arc::new(MobType { + id: "minecraft:rabbit".into(), + species: Species::Rabbit, + width: 0.4, + height: 0.5, + eye_height: 0.4, + category: "creature".into(), + max_health: 3.0, + speed: 0.3, + flying_speed: 0.4, + attack_damage: 0.0, + attack_knockback: 0.0, + follow_range: 16.0, + step_height: 0.6, + armor: 0.0, + armor_toughness: 0.0, + knockback_resistance: 0.0, + jump_strength: 0.42, + attributes: Arc::default(), + gravity: 0.08, + safe_fall_distance: 3.0, + fall_damage_multiplier: 1.0, + water_efficiency: 0.0, + water_slowdown: 0.8, + air_speed: 0.02, + baby_scale: 0.5, + head_rot_speed: 10.0, + max_head_x_rot: 40.0, + max_head_y_rot: 75.0, + ambient_interval: 120, + flags: Flags { + animal: true, + ..Default::default() + }, + model, + layers: HashMap::new(), + texture: String::new(), + brain: Brain::Passive, + anim: Anim::Rabbit, + sounds: [""; 3], + step_sound: None, + food: Arc::default(), + tempt: Arc::default(), + }); + Mob::new(1, kind, Vec3::ZERO, 0.0) + } + fn near(a: f64, b: f64) { + assert!((a - b).abs() < 1.0e-6, "{a} != {b}"); + } + + #[test] + fn summoned_age_selects_the_baby_model_and_texture() { + let mut template = rabbit(); + let kind = Arc::make_mut(&mut template.kind); + kind.texture = "entity/rabbit/rabbit_brown".into(); + kind.layers + .insert("rabbit_baby#main".into(), kind.model.clone()); + let types = HashMap::from([(kind.id.clone(), template.kind.clone())]); + for (age, baby) in [(-24000, true), (-1, true), (0, false), (6000, false)] { + let (tag, _) = horizon_world::nbt::parse_snbt(&format!( + "{{id:\"minecraft:rabbit\",Pos:[0.0d,0.0d,0.0d],Age:{age}}}" + )) + .unwrap(); + let m = crate::entity_nbt::mob_from_nbt(&tag, &types, 2).unwrap(); + assert_eq!(m.extra.age, age); + assert_eq!(m.is_baby(), baby); + assert_eq!( + crate::mobs::render::body(&m), + if baby { + ( + "rabbit_baby#main".into(), + "entity/rabbit/rabbit_brown_baby".into(), + ) + } else { + ("rabbit#main".into(), "entity/rabbit/rabbit_brown".into()) + } + ); + } + } + + #[test] + fn landing_waits_then_real_hop_clock_moves_the_model() { + let mut m = rabbit(); + m.on_ground = true; + m.ai.mov.set_wanted(0.0, 0.0, 5.0, 0.6); + server_ai_step(&mut m); + assert_eq!(m.extra.ints[MOVE_DELAY], 10); + assert!(!m.ai.jumping); + for _ in 0..9 { + server_ai_step(&mut m); + } + assert!(!m.ai.jumping); + server_ai_step(&mut m); + assert!(m.ai.jumping); + assert_eq!(m.extra.ints[JUMP_DURATION], 15); + assert_eq!(m.anim.states[0].started, None); + apply_jump(&mut m, 0.2); + post_tick(&mut m); + m.age = 1; + base_tick(&mut m); + assert_eq!(m.anim.states[0].started, Some(1.0)); + let curve = Animation::parse(&json!({"length": 0.75, "looping": true, + "bones": {"left_hind_foot": [{"target": "rotation", "keyframes": [[0,[0,0,0],[0,0,0],"linear"],[0.75,[1,0,0],[1,0,0],"linear"]]}]}})); + let animations = HashMap::from([("RabbitAnimation.HOP".into(), curve)]); + let mut poses = Poses::new(&m.kind.model); + let state = anim::state(&m, 0.5); + body_anim::rabbit( + &mut poses, + &state, + &m.anim.states[0], + &m.anim.states[1], + &animations, + ); + assert!(poses.get("left_hind_foot")[3] > 0.0); + for _ in 1..15 { + post_tick(&mut m); + } + assert_eq!(m.extra.ints[JUMP_TICKS], 15); + assert!(m.ai.jumping); + post_tick(&mut m); + base_tick(&mut m); + assert!(!m.ai.jumping); + assert_eq!(m.anim.states[0].started, None); + } + + #[test] + fn panic_and_explicit_requests_use_their_own_hop_timing() { + let mut m = rabbit(); + m.on_ground = true; + m.ai.mov.set_wanted(0.0, 0.0, 5.0, 2.2); + server_ai_step(&mut m); + assert_eq!(m.extra.ints[MOVE_DELAY], 3); + m.ai.jump = true; + m.jump_control_tick(); + assert!(m.ai.jumping); + assert!(!m.ai.jump); + assert_eq!(m.extra.ints[MOVE_DELAY], 3); + m.jump_control_tick(); + assert!(m.ai.jumping); + } + + #[test] + fn a_new_hop_preserves_a_running_clock_until_the_counter_finishes() { + let mut m = rabbit(); + m.anim.states[0].start(4.0); + m.extra.ints[CLIENT_JUMP_TICKS] = 8; + hop_event(&mut m); + assert_eq!(m.anim.states[0].started, Some(4.0)); + assert_eq!(m.extra.ints[CLIENT_JUMP_TICKS], 0); + assert_eq!(m.extra.ints[CLIENT_JUMP_DURATION], 15); + post_tick(&mut m); + m.age = 12; + base_tick(&mut m); + assert_eq!(m.anim.states[0].started, Some(4.0)); + assert!(m.outbox.is_empty()); + } + + #[test] + fn deep_water_jump_requests_do_not_start_a_client_hop() { + let mut m = rabbit(); + m.fluids.in_water = true; + m.fluids.water = 1.0; + m.ai.jump = true; + jump_control(&mut m); + assert!(m.ai.jumping); + assert_eq!(m.extra.ints[JUMP_DURATION], 15); + post_tick(&mut m); + base_tick(&mut m); + assert_eq!(m.extra.ints[JUMP_TICKS], 1); + assert_eq!(m.extra.ints[CLIENT_JUMP_DURATION], 0); + assert!(m.anim.states[0].started.is_none()); + assert!( + !m.outbox + .iter() + .any(|e| matches!(e, MobEvent::RabbitHop { .. })) + ); + hop_event(&mut m); + post_tick(&mut m); + base_tick(&mut m); + assert!(m.anim.states[0].started.is_some()); + } + + #[test] + fn grounded_movement_waits_and_water_uses_its_hop_speed() { + let mut m = rabbit(); + m.on_ground = true; + m.ai.mov.set_wanted(0.0, 0.0, 5.0, 0.6); + prepare_move(&mut m); + assert_eq!(m.ai.mov.speed_modifier, 0.0); + assert_eq!(m.ai.zza, 0.0); + m.ai.jumping = true; + prepare_move(&mut m); + assert_eq!(m.ai.mov.speed_modifier, 0.6); + m.fluids.in_water = true; + prepare_move(&mut m); + assert_eq!(m.ai.mov.speed_modifier, 1.5); + assert_eq!(m.extra.vector[0], 1.5); + assert!(m.ai.nav.can_float); + m.extra.flag = false; + m.ai.mov.set_wanted(0.0, 0.0, 5.0, 2.2); + server_ai_step(&mut m); + assert_eq!(m.ai.mov.speed_modifier, 1.5); + assert_eq!(m.extra.ints[MOVE_DELAY], 10); + } + + #[test] + fn jump_impulse_scales_strength_terrain_boost_and_baby_kick() { + let mut m = rabbit(); + m.ai.mov.speed_modifier = 0.6; + near(f64::from(jump_power(&m, 1.0)), 0.2); + m.ai.mov.speed_modifier = 2.2; + near(f64::from(jump_power(&m, 1.0)), 0.3); + m.horizontal_collision = true; + near(f64::from(jump_power(&m, 1.0)), 0.5); + m.attrs.jump_strength = 0.84; + m.extra.effects.push(("minecraft:jump_boost", 100, 1)); + near(f64::from(jump_power(&m, 0.5)), 0.7); + apply_jump(&mut m, 0.2); + near(m.velocity.z, 0.1 / 3.25_f64.sqrt()); + near(m.velocity.y, 0.2 + 0.15 / 3.25_f64.sqrt()); + m.extra.age = -100; + m.velocity = Vec3::ZERO; + apply_jump(&mut m, 0.2); + near(m.velocity.z, 0.1 / 1.25_f64.sqrt()); + near(m.velocity.y, 0.2 + 0.05 / 1.25_f64.sqrt()); + assert_eq!(m.extra.ints[CLIENT_JUMP_DURATION], 15); + } + + #[test] + fn idle_timeout_hop_priority_no_ai_and_leash_follow_tick_order() { + let mut m = rabbit(); + m.age = 7; + m.extra.ints[IDLE_TIMEOUT] = 0; + m.extra.ints[CLIENT_JUMP_TICKS] = 2; + base_tick(&mut m); + assert_eq!(m.anim.states[1].started, Some(7.0)); + assert!(m.anim.states[0].started.is_none()); + base_tick(&mut m); + assert_eq!(m.anim.states[0].started, Some(7.0)); + assert!(m.anim.states[1].started.is_none()); + m.extra.ints[CLIENT_JUMP_TICKS] = 0; + m.extra.ints[IDLE_TIMEOUT] = 0; + m.no_ai = true; + base_tick(&mut m); + assert_eq!(m.extra.ints[IDLE_TIMEOUT], -1); + assert!(m.anim.states[1].started.is_none()); + m.no_ai = false; + base_tick(&mut m); + assert!(m.anim.states[1].started.is_some()); + m.extra.leash = Some(super::super::leash::Holder::Knot([0, 0, 0])); + base_tick(&mut m); + assert!(m.anim.states[1].started.is_none()); + } +} diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index c886f26f3..01d842541 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -169,6 +169,10 @@ pub fn body(m: &Mob) -> (String, String) { "frog#main".into(), format!("entity/frog/frog_{}", climate(m)), ), + S::Rabbit => ( + baby_or(m, "rabbit#main", "rabbit_baby#main"), + b(&m.kind.texture), + ), S::Pig => { let model = if baby { "pig_baby#main".into() diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index b6986f6d1..197321dea 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -755,7 +755,7 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) { start, Some(Who::Mob(m.id)), ); - p.bonus = super::gear::arrow_bonus(m); + p.set_bonus(super::gear::arrow_bonus(m)); p.shoot( &mut arrow_random, [xd, yd + dist * 0.2, zd], diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index 6ae547aa8..f8afca24e 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -54,11 +54,23 @@ impl FluidResources { pub fn fluid(&self, state: BlockStateId) -> FluidState { self.states.get(state).unwrap_or(FluidState::EMPTY) } - fn sturdy(&self, state: BlockStateId, d: Direction) -> bool { + /// `BlockState.isFaceSturdy(FULL)` on that face. + pub fn sturdy(&self, state: BlockStateId, d: Direction) -> bool { self.sturdy .get(state.0 as usize) .is_some_and(|s| s & 1 << d as u8 != 0) } + /// `#minecraft:blocks_fluid_flow` membership. + pub fn blocks_flow(&self, state: BlockStateId) -> bool { + self.blocks_flow + .get(state.0 as usize) + .copied() + .unwrap_or(false) + } + /// `IceBlock` or one of its subclasses. + pub fn ice(&self, state: BlockStateId) -> bool { + self.ice.get(state.0 as usize).copied().unwrap_or(false) + } } /// The player's `EntityFluidInteraction` and the water flags around it. pub struct PlayerFluids { @@ -279,20 +291,10 @@ impl FluidFlowWorld for MotionWorld<'_, '_, '_> { Ok(MotionWorld::block(self, p)) } fn blocks_fluid_flow(&self, s: BlockStateId) -> bool { - self.resources - .fluids - .blocks_flow - .get(s.0 as usize) - .copied() - .unwrap_or(false) + self.resources.fluids.blocks_flow(s) } fn is_ice_class(&self, s: BlockStateId) -> bool { - self.resources - .fluids - .ice - .get(s.0 as usize) - .copied() - .unwrap_or(false) + self.resources.fluids.ice(s) } fn is_face_sturdy(&mut self, s: BlockStateId, _: BlockPos, d: Direction) -> Result { Ok(self.resources.fluids.sturdy(s, d)) diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 6b3646cb9..be1ddf2b2 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -47,6 +47,8 @@ pub enum Screen { }, Disconnected { reason: String, + /// Auto-reconnect's next attempt, until it is cancelled. + retry: Option, }, } /// What a click asks the title screen to do. @@ -205,14 +207,27 @@ impl Screen { 53, ), ], - Self::Disconnected { .. } => vec![b( - w / 2.0 - 100.0, - h / 2.0 + 30.0, - 200.0, - "Back to Server List", - true, - 54, - )], + Self::Disconnected { retry, .. } => { + let mut v = vec![b( + w / 2.0 - 100.0, + h / 2.0 + 30.0, + 200.0, + "Back to Server List", + true, + 54, + )]; + if retry.is_some() { + v.push(b( + w / 2.0 - 100.0, + h / 2.0 + 54.0, + 200.0, + "Cancel Reconnecting", + true, + 55, + )); + } + v + } } } fn field( @@ -427,7 +442,7 @@ impl Screen { blink, ); } - Self::Disconnected { reason } => { + Self::Disconnected { reason, retry } => { centered( batch, "Connection Lost", @@ -437,6 +452,10 @@ impl Screen { for (i, line) in wrap(reason, 300.0, atlas).iter().enumerate() { centered(batch, line, h / 2.0 - 16.0 + i as f32 * 9.0, u32::MAX); } + if let Some(r) = retry { + let text = r.text(std::time::Instant::now()); + centered(batch, &text, h / 2.0 + 16.0, rgba(170, 170, 170, 255)); + } } } } @@ -552,6 +571,7 @@ impl Screen { Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. }, Some(51 | 53 | 54), ) => *self = Self::list(saves), + (Self::Disconnected { retry, .. }, Some(55)) => *retry = None, (Self::Direct { address }, Some(52)) => { return Outcome::Connect(address.trim().to_owned()); } @@ -578,6 +598,16 @@ impl Screen { _ => None, } } + /// Auto-reconnect's attempt, once its countdown is over. + pub fn due_retry(&mut self) -> Option { + let Self::Disconnected { retry, .. } = self else { + return None; + }; + if !retry.as_ref()?.due(std::time::Instant::now()) { + return None; + } + retry.take() + } /// The focused text field, its id and maximum length (copy and paste). pub fn focused_text(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> { let id = match self { diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 2e733c9ba..ef1938ead 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -40,7 +40,13 @@ pub enum Event { DecodeError(String), /// The server sent us back to configuration and finished it again. Reconfigured(Arc), - Disconnected(String), + /// The connection ended. `from_server`: the server gave the reason (or + /// the connection was refused for good), rather than the connection + /// failing (auto-reconnect retries only failures and shutdowns). + Disconnected { + reason: String, + from_server: bool, + }, } pub struct Session { @@ -70,7 +76,7 @@ impl Session { let thread = std::thread::Builder::new() .name("horizon-net".into()) .spawn(move || { - let reason = match run( + let result = run( &address_owned, &name_owned, auth.as_deref(), @@ -79,14 +85,16 @@ impl Session { &send, &thread_writer, &thread_counters, - ) { - Ok(reason) => reason, - Err(e) => e, - }; + ); + let from_server = result.is_ok(); + let reason = result.unwrap_or_else(|e| e); if let Some(w) = thread_writer.lock().unwrap().take() { w.shutdown(); } - let _ = send.send(Event::Disconnected(reason)); + let _ = send.send(Event::Disconnected { + reason, + from_server, + }); }) .ok(); let debug = std::env::var_os("HORIZON_NET_DEBUG").is_some(); @@ -149,7 +157,8 @@ fn tr(lang: &Language, key: &str) -> String { lang.get(key).cloned().unwrap_or_else(|| key.to_owned()) } -/// The whole connection; returns the disconnect reason. +/// The whole connection. Ok: why it ended for good (the server's reason, or +/// a refusal no retry fixes); Err: the connection failed. fn run( address: &str, name: &str, @@ -160,8 +169,9 @@ fn run( shared_writer: &Mutex>, shared_counters: &Mutex>>, ) -> Result { - let (host, port) = - parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?; + let Some((host, port)) = parse_address(address) else { + return Ok(format!("Invalid server address: {address}")); + }; status(send, "Connecting to the server..."); let mut c = Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; @@ -200,7 +210,7 @@ fn run( let reason = serde_json::from_str::(&p.reason_json) .map(|v| json_text(&v, lang)) .unwrap_or(p.reason_json); - return Err(reason); + return Ok(reason); } login::Clientbound::Hello(hello) => { status(send, &tr(lang, "connect.authorizing")); diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index ac731fb4c..e97107587 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -10,15 +10,13 @@ //! of control belong in `ui_theme` so the launcher-matching look stays in one //! place. Everything else (sliders dragging, scrolling, Done) is handled here. use crate::{ + extras, graphics_style::Cost, graphics_ui::{self, Item, Level}, hud::{HudAtlas, HudBatch}, options_ui::{Event, Kind, Opt, OptionsUi, Page, apply_preset}, settings::{SOUND_SOURCES, Settings}, - ui_theme::{ - self as t, CONTROL, Face, Kind as Button, MenuStyle, ROW_LABEL, SIDEBAR, SMALL, Ui, color, - id, - }, + ui_theme::{self as t, CONTROL, Kind as Button, MenuStyle, ROW_LABEL, SIDEBAR, Ui, color, id}, }; /// One row of a section. @@ -34,6 +32,8 @@ pub enum HRow { Level, /// A graphics setting with its frame-time cost and description. Graphics(Item, Cost, &'static str), + /// One of Horizon's extras (`extras`), off by default. + Extra(extras::Item), } /// A sidebar section: name, description, rows. pub struct Section { @@ -172,6 +172,16 @@ pub const SECTIONS: &[Section] = &[ ] }, }, + Section { + name: "Extras", + blurb: "Optional additions, all off by default: the game stays vanilla until you turn one on.", + rows: |_| { + extras::rows() + .into_iter() + .map(|r| r.map_or_else(HRow::Header, HRow::Extra)) + .collect() + }, + }, ]; const NAV: u64 = id("options.nav", 0); @@ -245,28 +255,18 @@ impl OptionsUi { ) -> Vec<(Item, f32, f32)> { let (w, h) = (ui.w, ui.h); if self.in_world { - ui.atmosphere(0.45, 1.0); + ui.atmosphere(horizon_theme::VEIL, 1.0); } else { if backdrop < 1.0 { ui.cold_background(1.0 - backdrop); } - ui.atmosphere(0.66, 1.0); + ui.atmosphere(horizon_theme::VEIL, 1.0); } let section = self.section.min(SECTIONS.len() - 1); // The sidebar. - ui.fill(0.0, 0.0, SIDEBAR, h, color::with_alpha(color::SIDEBAR, 0.8)); - ui.vline(SIDEBAR - 1.0, 0.0, h, color::BORDER); - ui.text_line( - Face::Display, - 22.0, - 30.0, - 22.0, - 16.0, - color::TEXT, - "Options", - ); + ui.sidebar_frame("Options"); let names: Vec<&str> = SECTIONS.iter().map(|s| s.name).collect(); - ui.sidebar_list(NAV, 12.0, 66.0, SIDEBAR - 24.0, &names, section); + ui.sidebar_list(NAV, 12.0, 72.0, SIDEBAR - 24.0, &names, section); let dy = h - 12.0 - CONTROL; ui.button( DONE, @@ -312,7 +312,7 @@ impl OptionsUi { for (i, row) in rows.iter().enumerate() { match *row { HRow::Header(label) => { - ui.text(Face::Medium, SMALL, x, y + 18.0, color::FAINT, label); + ui.caps(x, y + 20.0, color::FAINT, label); y += HEADER_H; ui.divider(x, y, cw); continue; @@ -402,6 +402,43 @@ impl OptionsUi { ); } } + HRow::Extra(item) => { + let cy = y + ROW_H / 2.0; + let id = ROW + i as u64; + let mut cost = item.cost().map_or((0, ""), |c| (c as u8, c.label())); + let (caption, mut text) = (item.caption(), item.description().to_owned()); + // A vanilla mapping on the same key: both act on it, like + // the binds list's duplicates; say which. + let conflicts = extras::zoom_key_conflicts(&s.extras, &s.keys); + if item == extras::Item::ZoomKey && !conflicts.is_empty() { + let names: Vec = + conflicts.iter().map(|c| crate::lang::get(c)).collect(); + cost = (3, "Also bound"); + text = format!("{} uses this key too; both act on it.", names.join(", ")); + } + let text = text.as_str(); + if let Some(on) = item.switch(&s.extras) { + ui.described_row(x, y, caption, "", 0.0, cost, text, cw - 60.0); + ui.switch(id, control_x, cy, on); + } else { + let value = if item == extras::Item::ZoomKey + && self.selected_key == Some(extras::ZOOM_KEY) + { + "Press a key".to_owned() + } else { + item.value(&s.extras) + }; + let bw = ui.button_width(&value, false).max(96.0); + ui.described_row(x, y, caption, "", 0.0, cost, text, cw - bw - 24.0); + ui.button( + id, + [control_x - bw, y + 12.0, bw, CONTROL], + &value, + Button::Secondary, + true, + ); + } + } HRow::Style => { ui.row(x, y, "Menu style", "", 0.0); let labels = ["Horizon", "Classic"]; @@ -497,6 +534,7 @@ impl OptionsUi { atlas: &HudAtlas, x: f32, y: f32, + framebuffer: [i32; 2], drag: bool, right: bool, ) -> Vec { @@ -513,6 +551,10 @@ impl OptionsUi { } return events; } + // A click anywhere stops waiting for the zoom key. + if self.selected_key == Some(extras::ZOOM_KEY) { + self.selected_key = None; + } match self.horizon_target(s, atlas, x, y) { Some(Target::Nav(i)) => { self.section = i; @@ -543,17 +585,24 @@ impl OptionsUi { let section = self.section.min(SECTIONS.len() - 1); match (SECTIONS[section].rows)(s).get(i) { Some(HRow::Opt(opt)) => { - opt.cycle(s, right); + opt.cycle(s, right, framebuffer); if *opt == Opt::Preset { apply_preset(s); } events.push(Event::Changed); } Some(HRow::Graphics(item, ..)) => { - item.cycle(s, right); + item.cycle(s, right, framebuffer); events.push(Event::Changed); } Some(HRow::Page(_, _, page)) => self.open_page(*page), + Some(HRow::Extra(extras::Item::ZoomKey)) => { + self.selected_key = Some(extras::ZOOM_KEY); + } + Some(HRow::Extra(item)) => { + item.cycle(&mut s.extras, right); + events.push(Event::Changed); + } _ => {} } } diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 88196f453..19443d7f4 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -189,7 +189,6 @@ impl Opt { } else { s.volumes[i] }), - Opt::GuiScale => unit(s.gui_scale as f32, 0.0, 6.0), Opt::Gamma => Kind::Slider(s.gamma), Opt::MaxFps => unit(s.max_fps as f32, 10.0, 260.0), Opt::CloudRange => unit(s.cloud_range as f32, 2.0, 128.0), @@ -261,11 +260,12 @@ impl Opt { } } Opt::GuiScale => { - if s.gui_scale == 0 { + let value = if s.gui_scale == 0 { tr("options.guiScale.auto") } else { Text::literal(s.gui_scale.to_string()) - } + }; + generic(c, value) } Opt::Gamma => match (f64::from(s.gamma) * 100.0) as i32 { 0 => generic(c, tr("options.gamma.min")), @@ -446,7 +446,6 @@ impl Opt { Opt::WheelSensitivity => s.mouse_wheel_sensitivity = 0.01 + v * 9.99, Opt::Volume(0) => s.master_volume = v, Opt::Volume(i) => s.volumes[i] = v, - Opt::GuiScale => s.gui_scale = step(0.0, 6.0) as u32, Opt::Gamma => s.gamma = v, Opt::MaxFps => s.max_fps = (step(1.0, 26.0) as u32) * 10, Opt::CloudRange => s.cloud_range = step(2.0, 128.0) as i32, @@ -494,7 +493,7 @@ impl Opt { ) } /// Advance a cycle button (CycleButton.cycleValue). - pub fn cycle(self, s: &mut Settings, back: bool) { + pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) { let next = |n: u8, count: u8| { if back { (n + count - 1) % count @@ -503,6 +502,17 @@ impl Opt { } }; match self { + Opt::GuiScale => { + let max = crate::window::calculate_scale(framebuffer, 0, s.force_unicode) as u32; + let value = s.gui_scale.min(max); + s.gui_scale = if back { + if value == 0 { max } else { value - 1 } + } else if value == max { + 0 + } else { + value + 1 + }; + } Opt::InvertY => s.invert_y = !s.invert_y, Opt::DiscreteScroll => s.discrete_scroll = !s.discrete_scroll, Opt::ViewBobbing => s.view_bobbing = !s.view_bobbing, @@ -665,6 +675,8 @@ struct Widget { /// What the game must do after an interaction. #[derive(Clone, Debug, PartialEq)] pub enum Event { + /// An accepted button press or the release of a slider. + ButtonClick, /// Close the options screens (back to the pause menu or title). Close, /// Settings changed: apply them. @@ -1607,17 +1619,22 @@ impl OptionsUi { x: f32, y: f32, size: (f32, f32), + framebuffer: [i32; 2], drag: bool, right: bool, ) -> Vec { if crate::ui_theme::horizon() && self.page() == Page::Main { - return self.click_horizon(s, atlas, x, y, drag, right); + return self.click_horizon(s, atlas, x, y, framebuffer, drag, right); } if let Some(level) = Self::graphics_level(self.page()) { use crate::graphics_ui::Action; let mut events = Vec::new(); - for action in self.graphics.click(level, s, (x, y), size, drag, right) { + for action in self + .graphics + .click(level, s, (x, y), size, framebuffer, drag, right) + { match action { + Action::ButtonClick => events.push(Event::ButtonClick), Action::Changed => events.push(Event::Changed), Action::OpenAdvanced => self.push(Page::GraphicsAdvanced), Action::OpenSimple => { @@ -1642,6 +1659,9 @@ impl OptionsUi { } let m = crate::screen_draw::Measure(&atlas.font); let p = self.packs(atlas, size); + if p.button_at(&m, x as f64, y as f64) { + events.push(Event::ButtonClick); + } let before = p.search_focused(); let action = p.click(&m, x as f64, y as f64); if !before && p.search_focused() { @@ -1682,6 +1702,11 @@ impl OptionsUi { events.push(Event::Changed); return events; } + // AbstractWidget accepts only the primary button. Rebinding above + // accepts other mouse buttons, but is not a widget activation. + if right { + return events; + } for wd in widgets { if !ui::hovered((x, y), wd.x, wd.y, wd.w, wd.h) { continue; @@ -1692,43 +1717,46 @@ impl OptionsUi { match wd.kind { WKind::Button { active: true, act, .. - } => match act { - Act::Push(p) => self.push(p), - Act::Done => events.extend(self.back(s)), - Act::Cycle(opt) => { - opt.cycle(s, right); - if opt == Opt::Preset { - apply_preset(s); + } => { + events.push(Event::ButtonClick); + match act { + Act::Push(p) => self.push(p), + Act::Done => events.extend(self.back(s)), + Act::Cycle(opt) => { + opt.cycle(s, right, framebuffer); + if opt == Opt::Preset { + apply_preset(s); + } + events.push(Event::Changed); } - events.push(Event::Changed); - } - Act::Key(name) => self.selected_key = Some(name), - Act::ResetKey(name) => { - s.keys.set(name, KeyBinds::default_of(name)); - events.push(Event::Changed); - } - Act::ResetKeys => { - s.keys.reset_all(); - events.push(Event::Changed); - } - Act::PadKey(action) => self.selected_pad_action = Some(action), - Act::ResetPadKey(action) => { - s.controller - .bind(action, gamepad::PadSettings::default_of(action)); - events.push(Event::Changed); - } - Act::ResetPadKeys => { - s.controller.reset_bindings(); - events.push(Event::Changed); - } - Act::HorizonMenus => { - self.horizon_menus(); - if let Ok(dir) = std::env::current_dir() { - crate::ui_theme::save_preferences(&dir); + Act::Key(name) => self.selected_key = Some(name), + Act::ResetKey(name) => { + s.keys.set(name, KeyBinds::default_of(name)); + events.push(Event::Changed); } + Act::ResetKeys => { + s.keys.reset_all(); + events.push(Event::Changed); + } + Act::PadKey(action) => self.selected_pad_action = Some(action), + Act::ResetPadKey(action) => { + s.controller + .bind(action, gamepad::PadSettings::default_of(action)); + events.push(Event::Changed); + } + Act::ResetPadKeys => { + s.controller.reset_bindings(); + events.push(Event::Changed); + } + Act::HorizonMenus => { + self.horizon_menus(); + if let Ok(dir) = std::env::current_dir() { + crate::ui_theme::save_preferences(&dir); + } + } + Act::None => {} } - Act::None => {} - }, + } WKind::Slider { opt, .. } => { self.dragging = Some(opt); opt.set_slider(s, ui::slider_value(wd.x, wd.w, x)); @@ -1763,10 +1791,17 @@ impl OptionsUi { self.section_shown = None; self.hscroll = 0.0; } - pub fn release(&mut self) { - self.dragging = None; + pub fn release(&mut self) -> Vec { + // AbstractSliderButton suppresses the press sound and plays once on + // release, even if the pointer has left the widget or its value stayed. + let slider = self.dragging.take().is_some(); self.hdragging = None; - self.graphics.release(); + let graphics_slider = self.graphics.release(); + if slider || graphics_slider { + vec![Event::ButtonClick] + } else { + Vec::new() + } } pub fn scroll(&mut self, s: &Settings, size: (f32, f32), amount: f32) { let (_, top, bottom, content) = self.layout(s, size.0, size.1); @@ -1930,7 +1965,11 @@ impl OptionsUi { .unwrap_or("key.keyboard.unknown") .to_owned() }; - s.keys.set(name, &value); + if name == crate::extras::ZOOM_KEY { + s.extras.zoom_key = value; + } else { + s.keys.set(name, &value); + } return vec![Event::Changed]; } if key == K::Escape { @@ -1956,6 +1995,241 @@ mod tests { use super::*; use crate::ui_theme::{MenuStyle, set_style, style}; + fn atlas() -> HudAtlas { + HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap() + } + + #[test] + fn classic_video_gui_scale_cycles_on_press_without_dragging() { + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + ui.show(Page::Video); + let size = (480.0, 480.0); + let (widgets, _, _, _) = ui.layout(&s, size.0, size.1); + let button = widgets + .iter() + .find(|wd| { + matches!( + wd.kind, + WKind::Button { + active: true, + act: Act::Cycle(Opt::GuiScale), + .. + } + ) + }) + .expect("GUI Scale must be a cycle button in classic Video Settings"); + let (x, y) = (button.x + 1.0, button.y + 1.0); + assert!(Opt::GuiScale.slider_position(&s).is_none()); + assert!( + ui.click(&mut s, &atlas, x, y, size, [854, 480], false, true) + .is_empty() + ); + assert_eq!(s.gui_scale, 0); + for expected in [1, 2, 0] { + assert_eq!( + ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false), + vec![Event::ButtonClick, Event::Changed] + ); + assert_eq!(s.gui_scale, expected); + assert!( + ui.click(&mut s, &atlas, x + 100.0, y, size, [854, 480], true, false) + .is_empty() + ); + assert_eq!(s.gui_scale, expected); + assert!(ui.release().is_empty()); + } + } + + #[test] + fn gui_scale_cycle_handles_reverse_and_out_of_range_saved_values() { + for (framebuffer, force_unicode, max) in [ + ([854, 480], false, 2), + ([1920, 1080], false, 4), + ([1280, 720], true, 4), + ([3840, 2160], false, 9), + ([320, 240], false, 1), + ] { + let mut s = Settings { + force_unicode, + ..Settings::default() + }; + for expected in (0..=max).rev() { + Opt::GuiScale.cycle(&mut s, true, framebuffer); + assert_eq!(s.gui_scale, expected); + } + for expected in (1..=max).chain([0]) { + Opt::GuiScale.cycle(&mut s, false, framebuffer); + assert_eq!(s.gui_scale, expected); + } + s.gui_scale = u32::MAX; + s.clamp_gui_scale(framebuffer); + assert_eq!(s.gui_scale, max); + s.gui_scale = u32::MAX; + Opt::GuiScale.cycle(&mut s, false, framebuffer); + assert_eq!(s.gui_scale, 0); + s.gui_scale = u32::MAX; + Opt::GuiScale.cycle(&mut s, true, framebuffer); + assert_eq!(s.gui_scale, max - 1); + } + let mut s = Settings { + gui_scale: 4, + ..Settings::default() + }; + // A resized window supplies a new maximum on the next interaction. + Opt::GuiScale.cycle(&mut s, true, [854, 480]); + assert_eq!(s.gui_scale, 1); + } + + #[test] + fn classic_buttons_sound_but_disabled_and_nonprimary_clicks_are_silent() { + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + ui.show(Page::Mouse); + let size = (480.0, 320.0); + let (widgets, _, _, _) = ui.layout(&s, size.0, size.1); + let button = widgets + .iter() + .find(|wd| { + matches!( + wd.kind, + WKind::Button { + active: true, + act: Act::Cycle(_), + .. + } + ) + }) + .unwrap(); + let (x, y) = (button.x + 1.0, button.y + 1.0); + assert!( + ui.click(&mut s, &atlas, x, y, size, [854, 480], false, true) + .is_empty() + ); + assert_eq!( + ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false), + vec![Event::ButtonClick, Event::Changed] + ); + assert!(ui.release().is_empty()); + assert!( + ui.click(&mut s, &atlas, 0.0, 0.0, size, [854, 480], false, false) + .is_empty() + ); + ui.show(Page::KeyBinds); + let (widgets, _, _, _) = ui.layout(&s, size.0, size.1); + let disabled = widgets + .iter() + .find(|wd| matches!(wd.kind, WKind::Button { active: false, .. })) + .unwrap(); + assert!( + ui.click( + &mut s, + &atlas, + disabled.x + 1.0, + disabled.y + 1.0, + size, + [854, 480], + false, + false + ) + .is_empty() + ); + } + + #[test] + fn classic_sliders_sound_once_on_release_including_unchanged_values() { + let atlas = atlas(); + let size = (480.0, 320.0); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + ui.show(Page::Sound); + let (widgets, _, _, _) = ui.layout(&s, size.0, size.1); + let slider = widgets + .iter() + .find(|wd| { + matches!( + wd.kind, + WKind::Slider { + opt: Opt::Volume(0), + .. + } + ) + }) + .unwrap(); + let (x, y) = (slider.x + slider.w - 1.0, slider.y + 1.0); + assert_eq!( + ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false), + vec![Event::Changed] + ); + assert_eq!(s.master_volume, 1.0); + assert_eq!(ui.release(), vec![Event::ButtonClick]); + assert!(ui.release().is_empty()); + assert_eq!( + ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false), + vec![Event::Changed] + ); + for cx in [-100.0, 250.0, 1000.0] { + assert_eq!( + ui.click(&mut s, &atlas, cx, -100.0, size, [854, 480], true, false), + vec![Event::Changed] + ); + } + assert_eq!(ui.release(), vec![Event::ButtonClick]); + assert!( + ui.click(&mut s, &atlas, x, y, size, [854, 480], true, false) + .is_empty() + ); + } + + #[test] + fn classic_language_rows_and_text_fields_are_silent() { + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi { + languages: languages(), + ..Default::default() + }; + ui.show(Page::Language); + let size = (480.0, 320.0); + let (widgets, top, bottom, _) = ui.layout(&s, size.0, size.1); + let row = widgets + .iter() + .find(|wd| { + matches!(wd.kind, WKind::LanguageRow { .. }) && wd.y >= top && wd.y + wd.h <= bottom + }) + .unwrap(); + assert!( + ui.click( + &mut s, + &atlas, + row.x + 1.0, + row.y + 1.0, + size, + [854, 480], + false, + false + ) + .is_empty() + ); + assert!(ui.release().is_empty()); + let search = ui.language_search.clone(); + assert!( + ui.click( + &mut s, + &atlas, + search.x + 1.0, + search.y + 1.0, + size, + [854, 480], + false, + false + ) + .is_empty() + ); + } + fn languages() -> Vec { (0..30) .map(|i| LanguageInfo { diff --git a/crates/horizon-client/src/pack_screen.rs b/crates/horizon-client/src/pack_screen.rs index 628bbbe67..a96ea3072 100644 --- a/crates/horizon-client/src/pack_screen.rs +++ b/crates/horizon-client/src/pack_screen.rs @@ -19,6 +19,7 @@ pub enum Compat { TooNew, Unknown, } + impl Compat { fn key(self) -> &'static str { match self { @@ -457,6 +458,18 @@ impl PackScreen { self.info(id).is_none_or(|p| !p.fixed || !p.required) } + /// Whether a left click activates a footer or confirmation button. + /// Pack entries and the search field do not play widget click sounds. + pub fn button_at(&self, m: &Measure, x: f64, y: f64) -> bool { + let buttons = if let Some(c) = &self.confirm { + self.confirm_layout(m, c).2 + } else { + self.footer() + }; + buttons.into_iter().any(|(bx, by)| { + x >= bx as f64 && y >= by as f64 && x < (bx + 150) as f64 && y < (by + 20) as f64 + }) + } /// A left click (`Screen.mouseClicked`). pub fn click(&mut self, m: &Measure, x: f64, y: f64) -> Action { if self.confirm.is_some() { @@ -928,3 +941,58 @@ impl PackScreen { } } } + +#[cfg(test)] +mod click_sound_tests { + use super::*; + + #[test] + fn only_footer_and_confirmation_buttons_request_a_click_sound() { + let atlas = + crate::hud::HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")) + .unwrap(); + let m = Measure(&atlas.font); + let mut screen = PackScreen::new(&m, 480, 320, false, Vec::new(), &[]); + assert!(!screen.button_at(&m, 0.0, 0.0)); + assert!(!screen.button_at( + &m, + screen.search.x as f64 + 1.0, + screen.search.y as f64 + 1.0 + )); + let buttons = screen.footer(); + for (i, (x, y)) in buttons.into_iter().enumerate() { + assert!(screen.button_at(&m, x as f64 + 1.0, y as f64 + 1.0)); + assert!(!screen.button_at(&m, (x + 150) as f64, (y + 20) as f64)); + assert_eq!( + screen.click(&m, x as f64 + 1.0, y as f64 + 1.0), + if i == 0 { + Action::OpenFolder + } else { + Action::Done + } + ); + } + screen.confirm = Some(Confirm { + id: "incompatible".into(), + title: Text::literal("Confirm"), + message: Text::literal("Use this pack?"), + }); + let buttons = screen + .confirm_layout(&m, screen.confirm.as_ref().unwrap()) + .2; + for (x, y) in buttons { + assert!(screen.button_at(&m, x as f64 + 1.0, y as f64 + 1.0)); + } + assert!(!screen.button_at( + &m, + screen.footer()[0].0 as f64 + 1.0, + screen.footer()[0].1 as f64 + 1.0 + )); + let (x, y) = buttons[1]; + assert_eq!( + screen.click(&m, x as f64 + 1.0, y as f64 + 1.0), + Action::None + ); + assert!(!screen.confirming()); + } +} diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 5ef835ba1..57d9e60d7 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1264,6 +1264,36 @@ impl ParticleEngine { } self.create(options, p, v); } + /// `LevelEventHandler.singleBlockTeleportationParticles` (event 2015). + pub fn block_teleportation(&mut self, from: [i32; 3], data: i32, particle_level: u8) { + let to = [ + from[0].wrapping_add(((data >> 16) & 255) - 16), + from[1].wrapping_add(((data >> 8) & 255) - 8), + from[2].wrapping_add((data & 255) - 16), + ] + .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)); + let position = [ + to[0] + t * (from[0] - to[0]) + (r.next_double() - 0.5) + 0.5, + 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, + ]; + // 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, + 2 => true, + _ => false, + }; + if !limited { + self.add(&options, position, velocity); + } + } + } /// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the /// explosion particle (emitter for radius >= 2) and up to 512 poof/smoke /// particles thrown from air inside the radius. @@ -3762,6 +3792,52 @@ fn lifetime_alpha(a: [f32; 4], age: i32, lifetime: i32, partial: f32) -> f32 { #[cfg(test)] mod tests { use super::*; + + #[test] + fn egg_teleport_unpacks_offsets_and_preserves_seeded_draw_order() { + let mut engine = ParticleEngine::new(Path::new(""), &HashMap::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, 0); + assert_eq!(engine.pending.len(), 128); + assert!(engine.pending.iter().all(|p| p.ty == ParticleType::Portal)); + let first = &engine.pending[0]; + assert_eq!( + first.position.map(f64::to_bits), + [0x3fd18220c05a530a, 0x402b001e6be383c1, 0xbfc76bf5c46dbe5c] + ); + assert_eq!( + first.velocity.map(f64::to_bits), + [0xbfaa91aee0000000, 0x3f95c78ce0000000, 0x3f9c24a0e0000000] + ); + assert_eq!( + engine.pending[127].position.map(f64::to_bits), + [0xbfd728b135cb9ef6, 0x402ddd72dc6d0019, 0x3fe0b5775a29f186] + ); + assert_eq!(engine.level_random.state(), 99_413_408_083_437); + assert!(engine.sounds.is_empty()); + } + + #[test] + fn egg_teleport_options_roll_before_distance_rejection() { + for (option, count, state) in [ + (0, 128, 99_413_408_083_437), + (1, 89, 244_221_347_771_501), + (2, 0, 99_413_408_083_437), + ] { + for distant in [false, true] { + let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new()); + engine.seed_randoms(0, 0, 0); + if distant { + engine.camera = [1000.0; 3]; + } + engine.block_teleportation([4, 12, -5], 0x010f1f, option); + assert_eq!(engine.pending.len(), if distant { 0 } else { count }); + assert_eq!(engine.level_random.state(), state); + } + } + } + #[test] fn mining_particles_follow_slab_and_trapdoor_height() { for height in [0.5, 3.0 / 16.0] { diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index e66f41819..bfd0e8a97 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -76,6 +76,8 @@ pub struct Projectile { pub left_owner: bool, /// The shooter's bow enchantments (Power, Punch, Flame, Piercing). pub bonus: crate::mobs::gear::ArrowBonus, + /// Arrows' `AbstractArrow` state (ticked by `arrows::tick`). + pub arrow: Option>, } /// What a projectile struck this tick. #[derive(Clone, Copy, Debug, PartialEq)] @@ -124,6 +126,7 @@ fn axis_of(d: u8) -> u8 { } impl Projectile { pub fn new(kind: ProjectileKind, position: Vec3, owner: Option) -> Self { + let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. }); Self { kind, owner, @@ -136,6 +139,40 @@ impl Projectile { stuck: false, left_owner: false, bonus: Default::default(), + arrow: kind_is_arrow.then(|| { + // Entity.random: seeded unpredictably, the position stands in. + Box::new(crate::arrows::ArrowState::new( + horizon_core::random::LegacyRandom::new( + position.x.to_bits() as i64 ^ position.z.to_bits().rotate_left(17) as i64, + ), + )) + }), + } + } + /// The arrow's own random from now on (`Entity.random`). + pub fn with_arrow_random(mut self, random: horizon_core::random::LegacyRandom) -> Self { + if let Some(a) = self.arrow.as_mut() { + a.random = random; + } + self + } + /// The shooter's bow enchantments; Flame spawns the arrow burning for 100 + /// seconds (`projectile_spawned` ignite). + pub fn set_bonus(&mut self, bonus: crate::mobs::gear::ArrowBonus) { + if bonus.flame + && let Some(a) = self.arrow.as_mut() + { + a.ignite_for_seconds(100.0); + } + self.bonus = bonus; + } + /// `AbstractArrow.isCritArrow`. + pub fn critical(&self) -> bool { + matches!(self.kind, ProjectileKind::Arrow { critical: true, .. }) + } + pub fn set_critical(&mut self, value: bool) { + if let ProjectileKind::Arrow { critical, .. } = &mut self.kind { + *critical = value; } } /// `AbstractArrow.tick`: critical streaks and submerged bubble trails. @@ -513,10 +550,6 @@ impl Projectile { if matches!(self.kind, ProjectileKind::ShulkerBullet { .. }) { return self.tick_bullet(w); } - if self.stuck { - // AbstractArrow despawns 1200 ticks after sticking. - return (self.age < 1200, Hit::None); - } let water = w.in_water(self.position); match self.kind { ProjectileKind::SmallFireball @@ -536,6 +569,7 @@ impl Projectile { (v.z + v.z / len * 0.1) * inertia, ); } + // Arrows tick with `arrows::tick`. ProjectileKind::Arrow { .. } => {} ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => {} // LlamaSpit.tick: gone in water; drag and gravity follow the move. @@ -593,19 +627,6 @@ impl Projectile { } if let Some((at, pos, face)) = block { self.position = at; - if self.is_arrow() { - // AbstractArrow.onHitBlock: stick, nudged back out of the face. - let v = self.velocity; - let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9); - self.position = Vec3::new( - at.x - v.x / len * 0.05, - at.y - v.y / len * 0.05, - at.z - v.z / len * 0.05, - ); - self.stuck = true; - self.age = 0; - return (true, Hit::Block { pos, at, face }); - } return (false, Hit::Block { pos, at, face }); } if self.kind == ProjectileKind::LlamaSpit { @@ -635,16 +656,7 @@ impl Projectile { return (self.position.y > -128.0 && self.age < 6000, Hit::None); } self.position = to; - if self.is_arrow() { - // AbstractArrow.tick: inertia 0.99 (0.6 in water) after moving, then gravity. - let inertia = if water { 0.6 } else { 0.99 }; - self.velocity = Vec3::new( - self.velocity.x * inertia, - self.velocity.y * inertia - self.gravity(), - self.velocity.z * inertia, - ); - self.update_rotation(); - } else if !self.is_fireball() { + if !self.is_fireball() { self.update_rotation(); } let alive = @@ -737,7 +749,7 @@ mod tests { assert!((p.velocity.y + 0.06).abs() < 1e-9); } #[test] - fn arrow_applies_drag_then_gravity_after_moving() { + fn arrow_damage_is_speed_times_base() { let mut p = Projectile::new( ProjectileKind::Arrow { base_damage: 2.0, @@ -748,35 +760,6 @@ mod tests { None, ); p.velocity = Vec3::new(3.0, 0.0, 0.0); - let w = Empty(vec![]); - p.tick(&w); - assert!((p.position.x - 3.0).abs() < 1e-9); - assert!((p.velocity.x - 2.97).abs() < 1e-9); - assert!((p.velocity.y + 0.05).abs() < 1e-9); - } - #[test] - fn arrow_hits_entity_box_inflated_by_margin() { - let target = Aabb::new(Vec3::new(2.0, 99.0, -0.3), Vec3::new(2.6, 100.8, 0.3)); - let mut p = Projectile::new( - ProjectileKind::Arrow { - base_damage: 2.0, - critical: false, - effect: None, - }, - Vec3::new(0.0, 100.0, 0.0), - None, - ); - p.velocity = Vec3::new(3.0, 0.0, 0.0); - let w = Empty(vec![(Who::Mob(7), target)]); - let (keep, hit) = p.tick(&w); - assert!(!keep); - assert!(matches!( - hit, - Hit::Entity { - who: Who::Mob(7), - .. - } - )); let mut r = LegacyRandom::new(1); // ceil(3 * 2) = 6 for a non-critical arrow. assert_eq!(p.arrow_damage(&mut r), 6.0); diff --git a/crates/horizon-client/src/reconnect.rs b/crates/horizon-client/src/reconnect.rs new file mode 100644 index 000000000..c5184d7ad --- /dev/null +++ b/crates/horizon-client/src/reconnect.rs @@ -0,0 +1,287 @@ +//! The auto-reconnect extra (`docs/extras.md`): whether a lost multiplayer +//! connection may be retried, and when. Only lost connections and the +//! server's own shutdown or restart are retried, never kicks, bans or +//! refusals; attempts back off and stop after a few. +use std::time::{Duration, Instant}; + +/// Seconds before each attempt; there are no more after the last. +pub const DELAYS: [u64; 5] = [5, 10, 20, 40, 60]; +/// Staying connected this long counts the next drop as a fresh one. +pub const STABLE: Duration = Duration::from_secs(60); + +/// Whether a disconnect may be retried. `from_server`: the server (or a +/// permanent refusal) gave `reason`, rather than the connection failing. +pub fn allowed(reason: &str, from_server: bool) -> bool { + let r = reason.to_lowercase(); + // Kicks, bans, whitelists, version refusals and the account's session + // refusals (`disconnect.loginFailedInfo.*` but the unreachable session + // servers, the server's failed username check, joining an online-mode + // server without an account): never. + const NEVER: [&str; 13] = [ + "ban", + "kick", + "white-list", + "whitelist", + "incompatible", + "outdated", + "another location", + "online mode", + "invalid server address", + "invalid session", + "multiplayer is disabled", + "failed to verify username", + "microsoft account", + ]; + if NEVER.iter().any(|w| r.contains(w)) { + return false; + } + if !from_server { + return true; + } + // The server going away for a while: vanilla's shutdown and time-out + // reasons, a full server, a slow login, the server's own session + // servers being down, and restart messages. + const RETRY: [&str; 6] = [ + "server closed", + "timed out", + "the server is full", + "took too long to log in", + "authentication servers", + "restart", + ]; + RETRY.iter().any(|w| r.contains(w)) +} + +/// Attempts at one address. +#[derive(Debug, Default)] +pub struct Tracker { + address: Option, + /// The player name the connection used. + name: String, + /// Attempts already made since the last stable connection. + attempts: usize, + joined: Option, +} +/// A planned attempt. +#[derive(Clone, Debug, PartialEq)] +pub struct Retry { + pub address: String, + pub name: String, + pub at: Instant, + /// 1-based, of `DELAYS.len()`. + pub attempt: usize, +} +impl Retry { + /// Whole seconds left, rounded up. + pub fn seconds_left(&self, now: Instant) -> u64 { + let left = self.at.saturating_duration_since(now); + left.as_secs() + u64::from(left.subsec_nanos() > 0) + } + pub fn due(&self, now: Instant) -> bool { + now >= self.at + } + pub fn text(&self, now: Instant) -> String { + format!( + "Reconnecting in {} s (attempt {} of {})", + self.seconds_left(now), + self.attempt, + DELAYS.len() + ) + } +} +impl Tracker { + /// A connection to `address` as `name` starts: a new address starts + /// counting anew. + pub fn connecting(&mut self, address: &str, name: &str) { + if self.address.as_deref() != Some(address) { + self.address = Some(address.to_owned()); + self.attempts = 0; + } + self.name = name.to_owned(); + self.joined = None; + } + /// The server let the player in. + pub fn joined(&mut self, now: Instant) { + self.joined = Some(now); + } + /// The player left on purpose, or cancelled: nothing to retry. + pub fn reset(&mut self) { + *self = Self::default(); + } + /// The connection ended: the next attempt, or None (not allowed, or + /// out of attempts). + pub fn ended(&mut self, reason: &str, from_server: bool, now: Instant) -> Option { + if self + .joined + .take() + .is_some_and(|t| now.saturating_duration_since(t) >= STABLE) + { + self.attempts = 0; + } + let address = self.address.clone()?; + if !allowed(reason, from_server) || self.attempts >= DELAYS.len() { + self.reset(); + return None; + } + let delay = Duration::from_secs(DELAYS[self.attempts]); + self.attempts += 1; + Some(Retry { + address, + name: self.name.clone(), + at: now + delay, + attempt: self.attempts, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_lost_connections_and_shutdowns_are_retried() { + assert!(allowed("Connection reset by peer (os error 104)", false)); + assert!(allowed("Connection refused (os error 111)", false)); + assert!(allowed("Server closed", true)); + assert!(allowed("Timed out", true)); + assert!(allowed("The server is full!", true)); + assert!(allowed("Server is restarting, back soon", true)); + assert!(!allowed("Kicked by an operator", true)); + assert!(!allowed( + "You are banned from this server.\nReason: griefing", + true + )); + assert!(!allowed("You are not white-listed on this server!", true)); + assert!(!allowed("You logged in from another location", true)); + assert!(!allowed("Incompatible client! Please use 26.3", true)); + assert!(!allowed("You have been idle for too long!", true)); + assert!( + !allowed("Go away", true), + "unknown server reasons are not retried" + ); + assert!(!allowed( + "This server is in online mode. Horizon only joins offline-mode servers.", + true + )); + assert!(!allowed("Kicked for spamming", false)); + } + + #[test] + fn online_mode_login_failures() { + // The client's join with the session service (net.rs: Err, with + // vanilla's disconnect.loginFailedInfo texts). + let failed = |why: &str| format!("Failed to log in: {why}"); + assert!(!allowed( + &failed("Invalid session (Try restarting your game and the launcher)"), + false + )); + assert!(!allowed( + &failed("You are banned from playing online"), + false + )); + assert!(!allowed( + &failed("Multiplayer is disabled. Please check your Microsoft account settings."), + false + )); + assert!(!allowed(crate::net::NOT_SIGNED_IN, false)); + // Unreachable session servers are worth another try. + assert!(allowed( + &failed("The authentication servers are currently not reachable. Please try again."), + false + )); + assert!(allowed(&failed("Connection timed out"), false)); + // The server's side: its username check failed, or its session + // servers are down. + assert!(!allowed("Failed to verify username!", true)); + assert!(allowed( + "Authentication servers are down. Please try again later. Sorry!", + true + )); + } + + #[test] + fn attempts_back_off_and_stop() { + let mut t = Tracker::default(); + let now = Instant::now(); + t.connecting("localhost:25565", "Tester"); + let mut delays = Vec::new(); + while let Some(r) = t.ended("Connection refused", false, now) { + assert_eq!( + (r.address.as_str(), r.name.as_str()), + ("localhost:25565", "Tester") + ); + assert_eq!(r.attempt, delays.len() + 1); + delays.push(r.at.duration_since(now).as_secs()); + t.connecting(&r.address, &r.name); + } + assert_eq!(delays, DELAYS); + // Out of attempts, the tracker forgets the address. + assert_eq!(t.ended("Connection refused", false, now), None); + } + + #[test] + fn a_short_stay_does_not_reset_the_count() { + let mut t = Tracker::default(); + let now = Instant::now(); + t.connecting("a", "P"); + for _ in 0..DELAYS.len() { + t.connecting("a", "P"); + t.joined(now); + assert!( + t.ended("Server closed", true, now + Duration::from_secs(5)) + .is_some() + ); + } + t.connecting("a", "P"); + t.joined(now); + assert_eq!( + t.ended("Server closed", true, now + Duration::from_secs(5)), + None + ); + // A minute connected starts over. + t.connecting("a", "P"); + for _ in 0..3 { + t.ended("Timed out", true, now); + t.connecting("a", "P"); + } + t.joined(now); + let r = t.ended("Timed out", true, now + STABLE).unwrap(); + assert_eq!(r.attempt, 1); + } + + #[test] + fn kicks_and_leaving_reset_and_new_addresses_start_over() { + let mut t = Tracker::default(); + let now = Instant::now(); + t.connecting("a", "P"); + assert!(t.ended("Server closed", true, now).is_some()); + assert_eq!(t.ended("Kicked by an operator", true, now), None); + assert_eq!( + t.ended("Server closed", true, now), + None, + "forgotten after a kick" + ); + t.connecting("a", "P"); + t.ended("Server closed", true, now); + t.connecting("b", "P"); + assert_eq!(t.ended("Server closed", true, now).unwrap().attempt, 1); + let mut t = Tracker::default(); + assert_eq!(t.ended("Server closed", true, now), None, "never connected"); + } + + #[test] + fn the_countdown_rounds_up() { + let now = Instant::now(); + let r = Retry { + address: "a".into(), + name: "P".into(), + at: now + Duration::from_millis(4200), + attempt: 2, + }; + assert_eq!(r.seconds_left(now), 5); + assert_eq!(r.text(now), "Reconnecting in 5 s (attempt 2 of 5)"); + assert!(!r.due(now)); + assert!(r.due(now + Duration::from_secs(5))); + assert_eq!(r.seconds_left(now + Duration::from_secs(9)), 0); + } +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 7a90871c2..cce33949f 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -233,6 +233,9 @@ pub struct ChunkExtras { /// 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. @@ -532,7 +535,12 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain }; return Some((pos, BlockEntity::Beacon(Box::new(beacon)))); } - let mut entity = BlockEntity::for_block(&id)?; + // A spawner's block entity id is not its block's name. + let block = match id.as_str() { + "minecraft:mob_spawner" => "minecraft:spawner", + other => other, + }; + let mut entity = BlockEntity::for_block(block)?; match &mut entity { BlockEntity::Chest(items) => *items = decode_items(tag.get("Items"), items.len()), BlockEntity::Furnace(f) => { @@ -1030,6 +1038,10 @@ pub fn decode_with( }; if let Some(Tag::List(entities)) = tag.get("block_entities") { for e in entities { + let int = |k: &str| number(e.get(k)).map(|v| v as i32); + if let (Some(x), Some(y), Some(z)) = (int("x"), int("y"), int("z")) { + extras.block_entity_order.push((x, y, z)); + } match decode_block_entity(e) { Some(be) => { if let Some(name) = text(e.get("CustomName")) { @@ -2546,6 +2558,28 @@ mod tests { assert_eq!(back.redstone_signal(), 2); } #[test] + fn spawner_block_entity_round_trips() { + // A dungeon spawner as vanilla saves it (`id` is mob_spawner, not the block). + let saved = horizon_world::nbt::parse_snbt( + r#"{id:"minecraft:mob_spawner",x:67,y:-52,z:-64,Delay:20s,SpawnData:{entity:{id:"minecraft:zombie"}},SpawnPotentials:[]}"#, + ) + .unwrap() + .0; + let (pos, back) = decode_block_entity(&saved).expect("spawner"); + assert_eq!(pos, (67, -52, -64)); + let crate::containers::BlockEntity::Spawner(spawner) = &back else { + panic!("not a spawner"); + }; + let next = spawner.next_data().and_then(|d| d.id()); + assert_eq!(next.as_deref(), Some("minecraft:zombie")); + let tag = encode_block_entity(pos, &back, "minecraft:spawner"); + let (_, again) = decode_block_entity(&tag).expect("spawner again"); + let crate::containers::BlockEntity::Spawner(again) = again else { + panic!("not a spawner"); + }; + assert_eq!(again.update_tag(), spawner.update_tag()); + } + #[test] fn banner_block_entity_round_trips() { let banner = crate::containers::Banner { layers: vec![crate::banner::BannerLayer::new("minecraft:creeper", "lime")], diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client/src/scoreboard.rs index 6afba19ad..e063c6f09 100644 --- a/crates/horizon-client/src/scoreboard.rs +++ b/crates/horizon-client/src/scoreboard.rs @@ -533,7 +533,7 @@ impl Team { /// `PlayerTeam.getFormattedDisplayName`. pub fn formatted_display_name(&self) -> Text { let inner = hover_name(comp_text(&self.display_name), &self.name).with_style(&Style { - suggest: None, + click: None, ..Style::default() }); self.apply_color(bracketed(inner)) diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 9a3c5fa45..d232b8dd2 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -179,6 +179,8 @@ pub struct Settings { pub horizon: crate::graphics::Graphics, /// Controller settings (`horizon-controller.txt`, Horizon's own). pub controller: crate::gamepad::PadSettings, + /// Horizon's optional extras (`horizon-extras.txt`), all off by default. + pub extras: crate::extras::Extras, } impl Default for Settings { fn default() -> Self { @@ -249,6 +251,7 @@ impl Default for Settings { sprint_window: 7, horizon: Default::default(), controller: Default::default(), + extras: Default::default(), } } } @@ -278,6 +281,12 @@ fn put_s(f: &mut OptionsFile, key: &str, v: &str) { } } impl Settings { + /// `ClampingLazyMaxIntRange.validateValue`: clamp once the framebuffer is known. + pub fn clamp_gui_scale(&mut self, framebuffer: [i32; 2]) { + let max = crate::window::calculate_scale(framebuffer, 0, self.force_unicode) as u32; + self.gui_scale = self.gui_scale.min(max); + } + pub fn load(path: &Path) -> Self { let horizon = path .parent() @@ -287,15 +296,21 @@ impl Settings { .parent() .map(crate::gamepad::PadSettings::load) .unwrap_or_default(); + let extras = path + .parent() + .map(crate::extras::Extras::load) + .unwrap_or_default(); let settings = match fs::read(path) { Ok(bytes) => Self { horizon, controller, + extras, ..Self::parse(&String::from_utf8_lossy(&bytes)) }, Err(_) => Self { horizon, controller, + extras, ..Self::default() }, }; @@ -395,6 +410,7 @@ impl Settings { sprint_window: f.int("sprintWindow"), horizon: Default::default(), controller: Default::default(), + extras: Default::default(), auto_jump: f.bool("autoJump"), language: f.string("lang"), force_unicode: f.bool("forceUnicodeFont"), @@ -528,6 +544,7 @@ impl Settings { if let Some(dir) = path.parent() { self.horizon.save(dir); self.controller.save(dir); + self.extras.save(dir); } } /// Volume of a sound source (master excluded). diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index 5c325e684..e59a2b6c5 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -48,6 +48,8 @@ pub struct Sprites { pub animations: Vec, pub opaque: Vec, pub translucent: Vec, + /// Each layer's `MipmapGenerator` settings. + pub mips: Vec, /// Each layer's frames at the texture's own resolution (square), and the /// frame shown first. native: Vec<(u32, Arc>>, usize)>, @@ -124,6 +126,7 @@ impl Sprites { let layer = u32::try_from(self.layers.len())?; self.opaque.push(true); self.translucent.push(false); + self.mips.push(crate::mipmap::Settings::default()); self.layers.insert(name.to_owned(), layer); self.native.push((SPRITE_SIZE, Arc::new(vec![frame]), 0)); Ok(layer) @@ -213,6 +216,27 @@ impl Sprites { clip: Arc::new(clip), }); } + // SpriteContents: TextureMetadataSection's mipmap strategy and alpha + // cutoff bias, and the whole image's NativeImage.computeTransparency. + let texture = metadata + .as_ref() + .and_then(|v| v.get("texture")) + .and_then(|v| serde_json::from_str::(v.get()).ok()); + self.mips.push(crate::mipmap::Settings { + strategy: texture + .as_ref() + .and_then(|t| t["mipmap_strategy"].as_str()) + .and_then(crate::mipmap::Strategy::parse) + .unwrap_or_default(), + alpha_cutoff_bias: texture + .as_ref() + .and_then(|t| t["alpha_cutoff_bias"].as_f64()) + .unwrap_or(0.0) as f32, + has_transparent: pixels.as_chunks::<4>().0.iter().any(|p| p[3] == 0), + item: name + .split_once(':') + .is_some_and(|(_, p)| p.starts_with("item/")), + }); self.opaque .push(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255)); self.translucent.push( diff --git a/crates/horizon-client/src/tab_list.rs b/crates/horizon-client/src/tab_list.rs index 85391b9fe..2c03f999f 100644 --- a/crates/horizon-client/src/tab_list.rs +++ b/crates/horizon-client/src/tab_list.rs @@ -90,6 +90,7 @@ fn sprite(name: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw { h, region: None, color: WHITE, + blend: crate::hud_layout::Blend::Textured, } } diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index d70617851..e9710e442 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -39,6 +39,16 @@ pub fn named_color(name: &str) -> Option { COLORS.iter().find(|c| c.1 == name).map(|c| c.2) } +/// Click actions carried by locally constructed text components. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ClickEvent { + SuggestCommand(String), + CopyToClipboard(String), + /// A local file to open with the system handler. + /// Only allow this in locally constructed messages, never server/LAN text. + OpenFile(String), +} + /// Text style; `None` fields inherit from the enclosing style. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Style { @@ -48,8 +58,7 @@ pub struct Style { pub underlined: Option, pub strikethrough: Option, pub obfuscated: Option, - /// ClickEvent.SuggestCommand: clicking puts this into the chat box. - pub suggest: Option, + pub click: Option, /// Hover text. pub hover: Option>, } @@ -68,8 +77,8 @@ impl Style { self.underlined = self.underlined.or(base.underlined); self.strikethrough = self.strikethrough.or(base.strikethrough); self.obfuscated = self.obfuscated.or(base.obfuscated); - if self.suggest.is_none() { - self.suggest.clone_from(&base.suggest); + if self.click.is_none() { + self.click.clone_from(&base.click); } if self.hover.is_none() { self.hover.clone_from(&base.hover); @@ -134,6 +143,34 @@ impl Text { pub fn colored(s: impl Into, color: u32) -> Self { Self::styled(s, Style::color(color)) } + /// ComponentUtils.copyOnClickText: a green, bracketed clipboard link. + pub fn copyable(s: impl Into) -> Self { + let s = s.into(); + Self::literal("[") + .append(Self::styled( + s.clone(), + Style { + click: Some(ClickEvent::CopyToClipboard(s)), + hover: Some(Box::new(Self::translate("chat.copy.click", &[]))), + ..Style::color(GREEN) + }, + )) + .append("]") + } + /// LocateCommand's coordinate link: suggest a teleport without executing it. + /// Structure and POI results preserve the player's current height (`~`). + pub fn teleport_link(x: i32, y: Option, z: i32) -> Self { + let y = y.map_or_else(|| "~".to_owned(), |y| y.to_string()); + let coords = Self::tr("chat.coordinates", &[&x, &y, &z]); + Self::literal("[") + .append(coords) + .append("]") + .with_style(&Style { + click: Some(ClickEvent::SuggestCommand(format!("/tp @s {x} {y} {z}"))), + hover: Some(Box::new(Self::translate("chat.coordinates.tooltip", &[]))), + ..Style::color(GREEN) + }) + } /// Component.translatable(key, args) in the current language. pub fn translate(key: &str, args: &[Text]) -> Self { let mut t = format_translation(&lang::get(key), args); @@ -423,11 +460,17 @@ fn style_json(style: &Style) -> Vec<(String, Value)> { out.push((key.to_owned(), f.into())); } } - if let Some(command) = &style.suggest { - out.push(( - "click_event".to_owned(), - json!({ "action": "suggest_command", "command": command }), - )); + if let Some(click) = &style.click { + let event = match click { + ClickEvent::SuggestCommand(command) => { + json!({ "action": "suggest_command", "command": command }) + } + ClickEvent::CopyToClipboard(value) => { + json!({ "action": "copy_to_clipboard", "value": value }) + } + ClickEvent::OpenFile(path) => json!({ "action": "open_file", "path": path }), + }; + out.push(("click_event".to_owned(), event)); } if let Some(hover) = &style.hover { out.push(( @@ -516,6 +559,41 @@ pub fn format_translation(template: &str, args: &[Text]) -> Text { #[cfg(test)] mod tests { use super::*; + #[test] + fn click_events_serialize_and_inherit_as_one_style_field() { + for (event, json) in [ + ( + ClickEvent::SuggestCommand("/seed".into()), + json!({"action": "suggest_command", "command": "/seed"}), + ), + ( + ClickEvent::CopyToClipboard("-9223372036854775808".into()), + json!({"action": "copy_to_clipboard", "value": "-9223372036854775808"}), + ), + ( + ClickEvent::OpenFile("/tmp/My screenshots/世界.png".into()), + json!({"action": "open_file", "path": "/tmp/My screenshots/世界.png"}), + ), + ] { + let style = Style { + click: Some(event.clone()), + ..Style::default() + }; + let text = Text::literal("link").with_style(&style); + assert_eq!(text.component()["click_event"], json); + assert_eq!(text.spans[0].style.click, Some(event)); + let child = Text::copyable("42").with_style(&style); + assert_eq!( + child.spans[1].style.click, + Some(ClickEvent::CopyToClipboard("42".into())) + ); + assert_eq!( + child.component()["extra"][0]["click_event"], + json!({"action": "copy_to_clipboard", "value": "42"}) + ); + } + } + #[test] fn formats_like_translatable_contents() { let a = [Text::literal("Steve"), Text::colored("Zombie", RED)]; diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 1d21aa305..c526d7905 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -2,9 +2,62 @@ //! SelectWorldScreen, CreateWorldScreen layouts), drawn as HUD quads. use crate::{ hud::{HudAtlas, HudBatch, rgba}, + lang, save::Level, + text::{Text, format_translation}, }; use std::path::{Path, PathBuf}; +use std::{ + cell::{Cell, RefCell}, + sync::mpsc, +}; + +#[cfg(test)] +mod tests; +mod world_management; + +const LIST_TOP: f32 = 48.0; +const LIST_BOTTOM: f32 = 58.0; +const ROW_HEIGHT: f32 = 36.0; +const ROW_WIDTH: f32 = 270.0; + +fn edit_top(h: f32) -> f32 { + ((h.ceil() - 234.0) / 2.0).floor() +} +fn confirm_top(h: f32, lines: usize) -> f32 { + ((h.ceil() - 61.0 - lines as f32 * 9.0) / 2.0).floor() +} + +fn translate(key: &str, fallback: &str, args: &[&dyn std::fmt::Display]) -> String { + let args: Vec = args + .iter() + .map(|arg| Text::literal(arg.to_string())) + .collect(); + format_translation(&lang::get_or(key, fallback), &args).plain() +} + +enum BackupToast { + Created { folder: String, bytes: u64 }, + Failed(String), +} +impl BackupToast { + fn text(&self) -> (String, String) { + match self { + Self::Created { folder, bytes } => ( + translate("selectWorld.edit.backupCreated", "Backed up: %s", &[folder]), + translate( + "selectWorld.edit.backupSize", + "Size: %s MB", + &[&((*bytes as f64 / 1_048_576.0).ceil() as u64)], + ), + ), + Self::Failed(error) => ( + lang::get_or("selectWorld.edit.backupFailed", "Backup failed"), + error.clone(), + ), + } + } +} #[derive(Clone, Debug)] pub struct WorldEntry { @@ -12,6 +65,8 @@ pub struct WorldEntry { pub name: String, pub creative: bool, pub modified: std::time::SystemTime, + pub commands: bool, + pub version: String, } #[derive(Clone, Debug)] pub enum Mode { @@ -26,6 +81,21 @@ pub enum Mode { creative: bool, focus: u8, }, + Edit { + world: WorldEntry, + name: String, + focused: bool, + }, + Backup { + world: WorldEntry, + }, + Delete { + world: WorldEntry, + }, + Error { + message: String, + return_to: Box, + }, Multiplayer(crate::multiplayer::Screen), } #[derive(Clone, Debug, PartialEq)] @@ -50,6 +120,15 @@ pub struct Title { pub mode: Mode, pub saves: PathBuf, pub started: std::time::Instant, + search: String, + search_focused: bool, + scroll: Cell, + create_return_to_main: bool, + message_lines: Cell, + backup: Option>>, + backup_shown: Cell, + toast: Option<(std::time::Instant, BackupToast)>, + icons: RefCell>)>>, /// The mode last drawn and when it appeared (Horizon's screen fades). shown: std::cell::Cell<(std::mem::Discriminant, std::time::Instant)>, /// The launcher-style opening (Horizon style, first title of the session). @@ -89,11 +168,21 @@ pub fn list_worlds(saves: &Path) -> Vec { let modified = std::fs::metadata(path.join("level.dat")) .and_then(|m| m.modified()) .ok()?; + let data = crate::save::read_dat(&path.join("level.dat"))?; + let data = data.get("Data")?; + let modified = match data.get("LastPlayed") { + Some(horizon_world::nbt::Tag::Long(millis)) if *millis >= 0 => std::time::UNIX_EPOCH + std::time::Duration::from_millis(*millis as u64), + _ => modified, + }; Some(WorldEntry { folder: e.file_name().to_string_lossy().into_owned(), name: level.name, creative: level.creative, modified, + commands: matches!(data.get("allowCommands"), Some(horizon_world::nbt::Tag::Byte(v)) if *v != 0), + version: data.get("Version").and_then(|v| v.get("Name")) + .and_then(|v| match v { horizon_world::nbt::Tag::String(s) => Some(s.to_string_lossy()), _ => None }) + .unwrap_or_else(|| "Unknown".into()), }) }) .collect(); @@ -109,10 +198,175 @@ impl Title { mode, saves, started: now, + search: String::new(), + search_focused: false, + scroll: Cell::new(0.0), + create_return_to_main: false, + message_lines: Cell::new(1), + backup: None, + backup_shown: Cell::new(false), + toast: None, + icons: RefCell::new(std::collections::HashMap::new()), opening: std::cell::Cell::new(None), recent: std::cell::RefCell::new(None), } } + /// Vanilla bypasses the selector when there are no saves. + pub fn enter_singleplayer(&mut self) { + self.search.clear(); + self.search_focused = true; + self.scroll.set(0.0); + let worlds = list_worlds(&self.saves); + self.create_return_to_main = worlds.is_empty(); + self.mode = if worlds.is_empty() { + Self::new_world() + } else { + Mode::Select { + worlds, + selected: None, + } + }; + } + fn new_world() -> Mode { + Mode::Create { + name: "New World".into(), + seed: String::new(), + creative: false, + focus: 0, + } + } + fn return_to_list(&mut self, folder: Option<&str>) { + let worlds = list_worlds(&self.saves); + let selected = folder.and_then(|folder| { + worlds + .iter() + .position(|w| w.folder == folder && self.matches_search(w)) + }); + self.mode = Mode::Select { worlds, selected }; + *self.recent.borrow_mut() = None; + } + fn cancel_create(&mut self) { + if self.create_return_to_main { + self.mode = Mode::Main; + } else { + self.return_to_list(None); + } + } + 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) + } + fn visible_worlds<'a>( + &self, + worlds: &'a [WorldEntry], + ) -> impl Iterator { + worlds + .iter() + .enumerate() + .filter(|(_, w)| self.matches_search(w)) + .collect::>() + .into_iter() + } + /// Mouse wheel over the classic world list. + pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + let Mode::Select { worlds, .. } = &self.mode else { + return; + }; + if cursor.1 < LIST_TOP || cursor.1 >= size.1 - LIST_BOTTOM { + return; + } + let max = (self.visible_worlds(worlds).count() as f32 * ROW_HEIGHT + 4.0 + - (size.1 - LIST_TOP - LIST_BOTTOM)) + .max(0.0); + self.scroll + .set((self.scroll.get() - delta * ROW_HEIGHT / 2.0).clamp(0.0, max)); + } + fn failed(&mut self, error: impl std::fmt::Display) { + let return_to = Box::new(self.mode.clone()); + self.mode = Mode::Error { + message: error.to_string(), + return_to, + }; + } + /// Polling is done once per rendered frame so filesystem work never blocks drawing. + pub fn poll_backup(&mut self) { + if !self.backup_shown.get() { + return; + } + let Some(receiver) = &self.backup else { + return; + }; + let result = match receiver.try_recv() { + Ok(result) => result, + Err(mpsc::TryRecvError::Empty) => return, + Err(mpsc::TryRecvError::Disconnected) => Err("Backup worker stopped".into()), + }; + self.backup = None; + if let Mode::Backup { world } = &self.mode { + let folder = world.folder.clone(); + self.return_to_list(Some(&folder)); + let toast = match result { + Ok(bytes) => BackupToast::Created { folder, bytes }, + Err(error) => BackupToast::Failed(error), + }; + self.toast = Some((std::time::Instant::now(), toast)); + } + } + fn start_backup(&mut self, world: WorldEntry) { + let (send, receive) = mpsc::channel(); + let saves = self.saves.clone(); + let folder = world.folder.clone(); + std::thread::spawn(move || { + let _ = send.send(world_management::backup(&saves, &folder).map_err(|e| e.to_string())); + }); + self.backup_shown.set(false); + self.backup = Some(receive); + self.mode = Mode::Backup { world }; + } + fn icon( + &self, + atlas: &HudAtlas, + batch: &mut HudBatch, + world: &WorldEntry, + slot: usize, + x: f32, + y: f32, + ) { + let path = self.saves.join(&world.folder).join("icon.png"); + let mut icons = self.icons.borrow_mut(); + let pixels = if let Ok(modified) = std::fs::metadata(&path).and_then(|m| m.modified()) { + let cached = icons + .entry(path.clone()) + .or_insert_with(|| (std::time::UNIX_EPOCH, None)); + if cached.0 != modified { + *cached = ( + modified, + crate::hud::decode(&path) + .ok() + .filter(|(w, h, _)| *w == 64 && *h == 64) + .map(|(_, _, p)| p), + ); + } + cached.1.as_ref() + } else { + None + }; + let sprite = format!("horizon/world-icon{slot}"); + if let Some(pixels) = pixels + && let Some(rect) = atlas.sprites.get(&sprite) + { + batch.patches.push(crate::font::Patch { + x: (rect.u0 * atlas.width as f32).round() as u32, + y: (rect.v0 * atlas.height as f32).round() as u32, + width: 64, + height: 64, + rgba: pixels.clone(), + }); + batch.sprite_scaled(atlas, &sprite, x, y, 32.0, 32.0, u32::MAX); + } else { + batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX); + } + } /// The worlds, newest first, cached for two seconds (drawn every frame). pub fn recent_worlds(&self) -> Vec { let mut recent = self.recent.borrow_mut(); @@ -177,6 +431,7 @@ impl Title { } } fn buttons(&self, w: f32, h: f32) -> Vec GitHub Download @@ -73,47 +73,42 @@
-

01What it is

-

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

-
-
+

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

+
+
+

Your own copy

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

-
+
+

Native on three platforms

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

-
+
+

Open source

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

@@ -165,14 +160,14 @@

04The launcher

One small app, then play

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

-
    -
  • One-click install

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

  • -
  • Updates on its own

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

  • -
  • Client or server

    Start the client, or a dedicated server in a folder you choose, with a live console.

  • -
  • Your choice of menus

    Play with Horizon's own menus, shown here, or vanilla's classic screens.

  • +
      +
    • One-click install

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

    • +
    • Updates on its own

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

    • +
    • Client or server

      Start the client, or a dedicated server in a folder you choose, with a live console.

    • +
    • Your choice of menus

      Play with Horizon's own menus, shown here, or vanilla's classic screens.

@@ -180,18 +175,20 @@
- + +
-
Horizon's title screen: a sidebar, the Horizon title, Singleplayer and Multiplayer buttons and the last world played, over a blurred frozen landscape
-
The Singleplayer page: three worlds with their dates and game modes, and Create world and Play buttons
-
The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs
-
The pause screen of the world Glacier Pass, with Back to game, Open to LAN and Save and quit
+
The launcher's Play page: the version, Client and Server, the version picker and Play, the prepared resources and the Minecraft folder as a numbered list
+
Horizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, the last world played and the faint wordmark, over a veiled snowy landscape
+
The Singleplayer page: the worlds as a numbered list with their dates and game modes, and Create world and Play
+
The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs
+
The pause screen of a world, with Back to game, Open to LAN and Save and quit
-

Horizon's own menus, in the game. The launcher opens them, or vanilla's.

+

The launcher, and Horizon's own menus in the game. The launcher opens them, or vanilla's.

@@ -212,10 +209,10 @@

06Community

Built in the open

-
- DiscordQuestions, bug reports and screenshots. - SponsorSponsors on GitHub fund the next release. - SourceIssues and pull requests are welcome. +

Contributors

@@ -231,19 +228,19 @@
- + -
+
diff --git a/website/src/main.js b/website/src/main.js index 118cd149a..8717aad98 100644 --- a/website/src/main.js +++ b/website/src/main.js @@ -9,7 +9,6 @@ const REPO = "ludovic111/horizon"; const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher-v&expanded=true`; const baked = JSON.parse(document.getElementById("baked").textContent); const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; -const finePointer = matchMedia("(hover: hover) and (pointer: fine)").matches; // --- GitHub -------------------------------------------------------------------------- @@ -31,21 +30,34 @@ async function get(url, as = "json") { return as === "json" ? res.json() : res.text(); } -const releases = cached("horizon:releases", () => - get(`https://api.github.com/repos/${REPO}/releases?per_page=30`).then((list) => - list - .filter((r) => !r.draft) - .map((r) => ({ - tag_name: r.tag_name, - name: r.name, - published_at: r.published_at, - html_url: r.html_url, - prerelease: r.prerelease, - body: r.body || "", - assets: r.assets.map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), - })), - ), -).catch(() => baked.releases); +const slim = (r) => ({ + tag_name: r.tag_name, + name: r.name, + published_at: r.published_at, + html_url: r.html_url, + prerelease: r.prerelease, + body: r.body || "", + assets: r.assets.map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), +}); +const isLauncher = (r) => r.tag_name.startsWith("launcher-v") && !r.prerelease; +const versionKey = (tag) => tag.replace("launcher-v", "").split(".").map(Number); +const newer = (a, b) => versionKey(b).reduce((d, n, i) => d || n - (versionKey(a)[i] || 0), 0); + +// The newest 30 releases. Game releases come out several times a day, so the newest launcher release can be +// older than all of them: then it is looked up by its tag (the newest launcher-v tag with a published release). +async function loadReleases() { + const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=30`)).filter((r) => !r.draft).map(slim); + if (list.some(isLauncher)) return list; + const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/launcher-v`).catch(() => []); + const tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter((t) => /^launcher-v\d+\.\d+\.\d+$/.test(t)).sort(newer); + for (const tag of tags.slice(0, 3)) { + const release = await get(`https://api.github.com/repos/${REPO}/releases/tags/${tag}`).catch(() => null); + if (release && !release.draft) return [...list, slim(release)]; + } + return list; +} + +const releases = cached("horizon:releases", loadReleases).catch(() => baked.releases); async function setUpContributors() { let list = baked.contributors || []; @@ -234,14 +246,35 @@ function setUpLightbox() { }); } +// --- Light and dark ------------------------------------------------------------------ + +// The page follows the system; the toggle picks the other appearance and remembers it. +function setUpTheme() { + const root = document.documentElement; + const button = document.querySelector(".theme-toggle"); + const label = button.querySelector("[data-theme-label]"); + const system = matchMedia("(prefers-color-scheme: dark)"); + const dark = () => (root.dataset.theme ? root.dataset.theme === "dark" : system.matches); + const show = () => (label.textContent = dark() ? "Light" : "Dark"); + button.addEventListener("click", () => { + root.dataset.theme = dark() ? "light" : "dark"; + try { + localStorage.setItem("theme", root.dataset.theme); + } catch {} + show(); + }); + system.addEventListener("change", show); + show(); +} + // --- Motion --------------------------------------------------------------------------- function setUpReveal() { // Siblings that enter together come in one after another. const stagger = (els, step) => els.forEach((el, i) => el.style.setProperty("--d", `${i * step}ms`)); - document.querySelectorAll(".facts, .features, .cards, .mosaic").forEach((group) => stagger([...group.children], 90)); - document.querySelectorAll(".section-head, .parity-count, .parity-copy, .launcher-copy").forEach((group) => stagger([...group.querySelectorAll(":scope > .reveal")], 70)); - stagger([...document.querySelectorAll(".system")], 45); + document.querySelectorAll(".facts, .features, .cards, .mosaic, .hero-index").forEach((group) => stagger([...group.children], 40)); + document.querySelectorAll(".hero .container, .section-head, .parity-count, .parity-copy, .launcher-copy").forEach((group) => stagger([...group.querySelectorAll(":scope > .reveal")], 60)); + stagger([...document.querySelectorAll(".system")], 40); const count = document.querySelector("[data-digits]"); count.innerHTML = [...count.textContent].map((c) => `${escape(c)}`).join(""); @@ -264,54 +297,8 @@ function setUpReveal() { items.forEach((el) => observer.observe(el)); } -// The statement lights up in reading order as it scrolls through the view. -function setUpStatement() { - const fill = document.querySelector(".fill"); - if (reducedMotion) return; - const block = fill.parentElement; - const update = () => { - const r = block.getBoundingClientRect(); - if (r.bottom < -200 || r.top > innerHeight + 200) return; - const p = Math.min(1, Math.max(0, (innerHeight * 0.85 - r.top) / (innerHeight * 0.4 + r.height))); - fill.style.setProperty("--p", (p * 104).toFixed(1)); - }; - onScroll(update); - update(); -} - -// The hero's landscape moves slower than the page, and its text drifts up as it leaves. -function setUpParallax() { - if (reducedMotion) return; - const hero = document.querySelector(".hero"); - const layer = hero.querySelector(".hero-parallax"); - const content = hero.querySelector(".hero-content"); - onScroll(() => { - const y = scrollY; - if (y > hero.offsetHeight) return; - layer.style.transform = `translate3d(0, ${(y * 0.3).toFixed(1)}px, 0)`; - content.style.transform = `translate3d(0, ${(y * -0.08).toFixed(1)}px, 0)`; - content.style.opacity = String(Math.max(0, 1 - y / (hero.offsetHeight * 0.7)).toFixed(3)); - }); -} - -// Buttons lean a little towards the pointer. -function setUpMagnetic() { - if (reducedMotion || !finePointer) return; - document.querySelectorAll(".magnetic").forEach((el) => { - el.addEventListener("pointermove", (e) => { - const r = el.getBoundingClientRect(); - const x = (e.clientX - r.left - r.width / 2) * 0.18; - const y = (e.clientY - r.top - r.height / 2) * 0.3; - el.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0)`; - }); - el.addEventListener("pointerleave", () => (el.style.transform = "")); - }); -} - setUpReveal(); -setUpStatement(); -setUpParallax(); -setUpMagnetic(); +setUpTheme(); setUpNav(); setUpTabs(); setUpLightbox(); diff --git a/website/src/style.css b/website/src/style.css index edcd4f1ae..fb4021c05 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -1,73 +1,56 @@ -/* Horizon's design language (crates/horizon-theme), set as a page rather than a window: - the dark palette and one violet accent, Instrument Serif for display type and Geist for - everything else, 1px dividers, and short motion eased out, never bouncy. */ +/* Horizon's design language (docs/design-system.md), set as a page. The tokens come from + crates/horizon-theme through src/tokens.css, which build.mjs puts before this file: the + same palette, type, spacing and motion as the launcher and the game's menus. Type is the + interface; content is numbered index lists with one-pixel rules; one violet accent for the + main action, links and focus; space instead of borders; quiet motion. */ @font-face { font-family: "Geist"; src: url("/fonts/Geist-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } @font-face { font-family: "Geist"; src: url("/fonts/Geist-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } +@font-face { font-family: "Geist"; src: url("/fonts/Geist-SemiBold.woff2") format("woff2"); font-weight: 600; font-display: swap; } @font-face { font-family: "Geist Mono"; src: url("/fonts/GeistMono-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } -@font-face { font-family: "Instrument Serif"; src: url("/fonts/InstrumentSerif-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } :root { - --bg: #111113; - --deep: #0c0c0d; - --raised: #1a1a1d; - --hover: #202024; - --border: #26262a; - --text: #e8e8ea; - --muted: #9a9aa1; - --faint: #8a8a92; /* the token's #626269, lifted to pass WCAG AA for small text */ - --accent: #7c5cc4; - --accent-text: #a48ae6; /* the accent as text, readable on --bg */ - --on-accent: #ffffff; - - --font: "Geist", ui-sans-serif, system-ui, sans-serif; - --display: "Instrument Serif", ui-serif, Georgia, serif; - --mono: "Geist Mono", ui-monospace, monospace; - - --radius: 8px; - --radius-large: 12px; - --gutter: clamp(20px, 5vw, 72px); - --max: 1280px; - --nav: 68px; - - /* GPUI's ease_out_quint: quick for hovers, longer for things entering the page. */ - --ease: cubic-bezier(0.22, 1, 0.36, 1); - --quick: 180ms; - --move: 320ms; - --enter: 900ms; + --g: clamp(var(--gutter-narrow), 4.5vw, var(--gutter)); + --max: 1440px; + --nav: 72px; } *, *::before, *::after { box-sizing: border-box; } html { - background: var(--bg); - color: var(--text); - font: 400 16px/1.65 var(--font); + background: var(--page); + color: var(--ink); + font: 400 var(--text-body) / var(--text-body-line) var(--font); font-synthesis: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-rendering: optimizeLegibility; scroll-behavior: smooth; scroll-padding-top: calc(var(--nav) + 16px); + transition: background-color var(--move) var(--ease-move), color var(--move) var(--ease-move); } body { margin: 0; min-height: 100vh; overflow-x: clip; } img { display: block; max-width: 100%; height: auto; } -h1, h2, h3 { margin: 0; font-weight: 400; } +h1, h2, h3 { margin: 0; font-weight: var(--text-heading-weight); } p { margin: 0; } -::selection { background: rgba(124, 92, 196, 0.5); color: #fff; } +ol, ul { margin: 0; padding: 0; list-style: none; } +::selection { background: var(--accent); color: var(--on-accent); } -a { color: var(--accent-text); text-decoration: none; transition: color var(--quick) var(--ease); } -a:hover { color: var(--text); } +a { color: var(--accent); text-decoration: none; transition: color var(--quick) var(--ease-quick); } +a:hover { color: var(--ink); } [hidden] { display: none !important; } /* Links inside running text are underlined, so they don't rely on colour alone. */ -p a:not(.button):not(.link-arrow) { text-decoration: underline; text-decoration-color: rgba(164, 138, 230, 0.45); text-decoration-thickness: 1px; text-underline-offset: 3px; } -p a:not(.button):not(.link-arrow):hover { text-decoration-color: currentColor; } -:focus-visible { outline: 2px solid var(--accent-text); outline-offset: 3px; border-radius: 6px; } +p a:not(.button):not(.link-arrow), li > p a, .prose a { + color: inherit; text-decoration: underline; text-decoration-color: var(--rule); + text-decoration-thickness: 1px; text-underline-offset: 3px; + transition: text-decoration-color var(--quick) var(--ease-quick); +} +p a:not(.button):not(.link-arrow):hover, li > p a:hover, .prose a:hover { text-decoration-color: currentColor; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: var(--radius); } code { font: 0.86em/1.5 var(--mono); - background: var(--raised); - border: 1px solid var(--border); + background: var(--plate-soft); border-radius: 4px; padding: 1px 5px; overflow-wrap: anywhere; @@ -77,572 +60,369 @@ code { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; } - .skip { - position: fixed; left: 16px; top: 12px; z-index: 100; - padding: 10px 14px; border-radius: var(--radius); - background: var(--raised); color: var(--text); border: 1px solid var(--border); - transform: translateY(-200%); transition: transform var(--quick) var(--ease); + position: fixed; left: var(--g); top: 12px; z-index: 50; padding: 8px 14px; + background: var(--ink); color: var(--page); border-radius: var(--radius-pill); + transform: translateY(-200%); } .skip:focus { transform: none; } -.container { width: 100%; max-width: calc(var(--max) + 2 * var(--gutter)); margin: 0 auto; padding: 0 var(--gutter); } +.container { width: 100%; max-width: var(--max); margin: 0 auto; padding: 0 var(--g); } -/* --- Type --------------------------------------------------------------------------- */ +/* --- Type ----------------------------------------------------------------------------- */ -.eyebrow { font-size: 14px; color: var(--muted); letter-spacing: 0.01em; } - -.kicker { - display: flex; align-items: center; gap: 14px; - margin-bottom: clamp(32px, 5vw, 56px); - font-size: 13px; font-weight: 500; color: var(--muted); letter-spacing: 0.02em; -} -.kicker span { font: 12px/1 var(--mono); color: var(--accent-text); } -.kicker::after { content: ""; flex: 1; height: 1px; background: var(--border); } - -.title { - font: 400 clamp(46px, 6.4vw, 96px)/0.98 var(--display); - letter-spacing: -0.025em; - color: var(--text); +.display { + font-size: var(--text-display); line-height: var(--text-display-line); + letter-spacing: var(--text-display-tracking); font-weight: var(--text-display-weight); text-wrap: balance; } -.lede { font-size: clamp(17px, 1.35vw, 19px); line-height: 1.6; color: var(--muted); max-width: 46ch; text-wrap: pretty; } -.meta { font-size: 13.5px; color: var(--faint); } +.title { + font-size: var(--text-title); line-height: var(--text-title-line); + letter-spacing: var(--text-title-tracking); font-weight: var(--text-title-weight); + text-wrap: balance; +} +.lede { max-width: var(--measure); color: var(--muted); text-wrap: pretty; } +.kicker, .meta, .download-meta, .eyebrow, .row-index, .row-meta, .disclaimer { + font: var(--text-micro-weight) var(--text-micro) / var(--text-micro-line) var(--mono); + letter-spacing: var(--text-micro-tracking); + color: var(--muted); +} +.kicker { display: flex; gap: 16px; text-transform: uppercase; margin-bottom: 24px; } +.kicker span { color: var(--ink); } +.meta { margin-top: 16px; } +.download-meta { margin-top: 12px; } +.download-meta a { color: inherit; } -.prose { color: var(--muted); } -.prose > * + * { margin-top: 1em; } -.prose strong { color: var(--text); font-weight: 500; } -.prose a { text-decoration: underline; text-decoration-color: rgba(164, 138, 230, 0.4); text-underline-offset: 3px; } -.prose a:hover { text-decoration-color: currentColor; } -.prose ul, .prose ol { padding-left: 1.2em; } -.prose li + li { margin-top: 0.55em; } -.prose li::marker { color: var(--faint); } -.prose h2, .prose h3, .prose h4 { font: 400 26px/1.15 var(--display); color: var(--text); letter-spacing: -0.01em; margin-top: 1.6em; } -.prose pre { overflow-x: auto; background: var(--deep); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px 16px; } -.prose pre code { background: none; border: 0; padding: 0; } -.prose blockquote { margin-left: 0; padding-left: 16px; border-left: 1px solid var(--border); } -.prose hr { border: 0; height: 1px; background: var(--border); } - -/* --- Buttons ------------------------------------------------------------------------ */ +/* --- Buttons --------------------------------------------------------------------------- */ .button { display: inline-flex; align-items: center; justify-content: center; gap: 8px; - height: 44px; padding: 0 20px; - border: 1px solid transparent; border-radius: var(--radius); - font: 500 15px/1 var(--font); white-space: nowrap; - cursor: pointer; - transition: background-color var(--quick) var(--ease), border-color var(--quick) var(--ease), - box-shadow var(--move) var(--ease), color var(--quick) var(--ease), transform var(--move) var(--ease); + height: var(--control); padding: 0 16px; border: 0; border-radius: var(--radius-pill); + font: 500 var(--text-label) / 1 var(--font); cursor: pointer; white-space: nowrap; + transition: background-color var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick), opacity var(--quick) var(--ease-quick); } -.button.large { height: 52px; padding: 0 26px; font-size: 15.5px; } -.button.small { height: 34px; padding: 0 14px; font-size: 14px; border-radius: 7px; } -.button.primary { - background: var(--accent); color: var(--on-accent); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 10px 30px -12px rgba(124, 92, 196, 0.7); -} -.button.primary:hover { background: #8a6bd1; color: var(--on-accent); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.24), 0 14px 40px -12px rgba(124, 92, 196, 0.85); } -.button.ghost { - background: rgba(255, 255, 255, 0.06); color: var(--text); - border-color: rgba(255, 255, 255, 0.14); - -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); -} -.button.ghost:hover { background: rgba(255, 255, 255, 0.11); border-color: rgba(255, 255, 255, 0.22); color: var(--text); } -.button.secondary { background: var(--raised); color: var(--text); border-color: var(--border); } -.button.secondary:hover { background: var(--hover); color: var(--text); } +.button.large { height: var(--control-large); padding: 0 22px; font-size: var(--text-ui); } +.button.small { height: 30px; padding: 0 14px; } +.button.primary { background: var(--accent); color: var(--on-accent); } +.button.primary:hover { color: var(--on-accent); opacity: 0.88; } +.button.secondary { background: var(--plate-soft); color: var(--ink); } +.button.secondary:hover { background: var(--plate); color: var(--ink); } +.button.ghost { background: transparent; color: var(--muted); } +.button.ghost:hover { background: var(--plate-soft); color: var(--ink); } .button:active { opacity: 0.85; } -.link-arrow { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; font-weight: 500; } -.link-arrow span { transition: transform var(--move) var(--ease); } -.link-arrow:hover span { transform: translateX(4px); } +.link-arrow { display: inline-flex; gap: 8px; color: var(--accent); font-weight: 500; } +.link-arrow span { transition: transform var(--quick) var(--ease-quick); } +.link-arrow:hover span { transform: translateX(3px); } -.download-meta { font-size: 13.5px; color: var(--faint); } -.download-meta a { color: var(--accent-text); } - -/* --- Navigation --------------------------------------------------------------------- */ +/* --- Navigation ------------------------------------------------------------------------- */ .nav { - position: fixed; inset: 0 0 auto; z-index: 50; - border-bottom: 1px solid transparent; - transition: background-color var(--move) var(--ease), border-color var(--move) var(--ease), - -webkit-backdrop-filter var(--move) var(--ease), backdrop-filter var(--move) var(--ease); + position: fixed; inset: 0 0 auto; z-index: 20; height: var(--nav); + background: color-mix(in srgb, var(--page) 0%, transparent); + transition: background-color var(--move) var(--ease-move), box-shadow var(--move) var(--ease-move); } .nav.is-scrolled, .nav.is-menu { - background: rgba(17, 17, 19, 0.72); - border-bottom-color: rgba(255, 255, 255, 0.07); - -webkit-backdrop-filter: blur(18px) saturate(140%); backdrop-filter: blur(18px) saturate(140%); + background: color-mix(in srgb, var(--page) 88%, transparent); + -webkit-backdrop-filter: blur(16px) saturate(1.2); backdrop-filter: blur(16px) saturate(1.2); + box-shadow: 0 1px 0 var(--rule); } -.nav-inner { - display: flex; align-items: center; gap: 24px; - height: var(--nav); max-width: calc(var(--max) + 2 * var(--gutter)); margin: 0 auto; padding: 0 var(--gutter); +.nav-inner { display: flex; align-items: center; gap: 24px; height: 100%; max-width: var(--max); margin: 0 auto; padding: 0 var(--g); } +.nav-mark { display: inline-flex; align-items: center; gap: 10px; color: var(--ink); font-weight: 500; font-size: var(--text-label); } +.nav-mark:hover { color: var(--ink); } +.mark { width: 18px; height: 18px; } +.mark-stem { fill: var(--ink); } +.mark-low { fill: var(--ink); opacity: 0.36; } +.mark-line { fill: var(--accent); } +.nav-links { display: flex; gap: 2px; margin-left: auto; } +.nav-links a, .nav-github, .theme-toggle { + display: inline-flex; align-items: center; height: 32px; padding: 0 12px; + border-radius: var(--radius-pill); color: var(--muted); font-size: var(--text-label); + transition: background-color var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick); } -.nav-mark { font: 400 26px/1 var(--display); color: var(--text); letter-spacing: -0.01em; padding: 10px 0; } -.nav-mark:hover { color: var(--text); } -.nav-links { display: none; gap: 4px; margin: 0 auto; } -.nav-links a { - position: relative; padding: 8px 12px; font-size: 14px; color: rgba(232, 232, 234, 0.72); +.nav-links a:hover, .nav-github:hover, .theme-toggle:hover { color: var(--ink); background: var(--plate-soft); } +.nav-links a[aria-current] { color: var(--ink); background: var(--plate-soft); } +.nav-end { display: flex; align-items: center; gap: 2px; } +.theme-toggle { + border: 0; background: none; cursor: pointer; + font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; } -.nav-links a::after { - content: ""; position: absolute; left: 12px; right: 12px; bottom: 3px; height: 1px; - background: var(--accent-text); transform: scaleX(0); transform-origin: left; - transition: transform var(--move) var(--ease); -} -.nav-links a:hover { color: var(--text); } -.nav-links a[aria-current="true"] { color: var(--text); } -.nav-links a[aria-current="true"]::after { transform: scaleX(1); } -.nav-end { display: flex; align-items: center; gap: 8px; margin-left: auto; } -.nav-github { display: none; align-items: center; min-height: 44px; padding: 0 12px; font-size: 14px; color: rgba(232, 232, 234, 0.72); } -.nav-github:hover { color: var(--text); } -.nav-end .button.small { display: none; } - +.nav-end .button { margin-left: 8px; } .menu-button { - display: inline-flex; align-items: center; gap: 12px; - height: 44px; padding: 0 4px 0 14px; - background: none; border: 0; color: var(--text); font: 500 15px/1 var(--font); cursor: pointer; + display: none; align-items: center; gap: 10px; height: 44px; padding: 0 4px 0 14px; margin-left: 4px; + border: 0; background: none; color: var(--ink); font: 500 var(--text-label) / 1 var(--font); cursor: pointer; } -.menu-icon { position: relative; width: 20px; height: 10px; } +.menu-icon { position: relative; width: 18px; height: 10px; } .menu-icon::before, .menu-icon::after { - content: ""; position: absolute; left: 0; right: 0; height: 1.5px; background: currentColor; border-radius: 1px; - transition: transform var(--move) var(--ease), top var(--move) var(--ease); + content: ""; position: absolute; left: 0; right: 0; height: 1.5px; border-radius: 1px; background: currentColor; + transition: transform var(--move) var(--ease-move), top var(--move) var(--ease-move); } .menu-icon::before { top: 0; } -.menu-icon::after { top: 8.5px; } -.menu-button[aria-expanded="true"] .menu-icon::before { top: 4.25px; transform: rotate(45deg); } -.menu-button[aria-expanded="true"] .menu-icon::after { top: 4.25px; transform: rotate(-45deg); } +.menu-icon::after { top: 8px; } +.is-menu .menu-icon::before { top: 4px; transform: rotate(45deg); } +.is-menu .menu-icon::after { top: 4px; transform: rotate(-45deg); } .menu { - position: fixed; inset: 0; z-index: 40; - display: flex; flex-direction: column; justify-content: space-between; - padding: calc(var(--nav) + 24px) var(--gutter) max(28px, env(safe-area-inset-bottom)); - background: rgba(12, 12, 13, 0.92); - -webkit-backdrop-filter: blur(24px); backdrop-filter: blur(24px); - opacity: 0; transition: opacity var(--move) var(--ease); - overflow-y: auto; + position: fixed; inset: var(--nav) 0 0; z-index: 19; display: flex; flex-direction: column; + justify-content: space-between; padding: 24px var(--g) 32px; background: var(--page); + opacity: 0; transition: opacity var(--move) var(--ease-move); } .menu.is-open { opacity: 1; } .menu nav { display: flex; flex-direction: column; } .menu nav a { - display: block; padding: 6px 0; - font: 400 clamp(38px, 10vw, 56px)/1.12 var(--display); color: var(--text); letter-spacing: -0.02em; - opacity: 0; transform: translateY(14px); - transition: opacity 500ms var(--ease), transform 500ms var(--ease), color var(--quick) var(--ease); + display: flex; align-items: baseline; gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--rule); + color: var(--ink); font-size: var(--text-title); line-height: var(--text-title-line); + letter-spacing: var(--text-title-tracking); font-weight: 500; + opacity: 0; transform: translateY(var(--rise)); + transition: opacity var(--enter) var(--ease-enter), transform var(--enter) var(--ease-enter); } .menu.is-open nav a { opacity: 1; transform: none; } -.menu nav a:hover { color: var(--accent-text); } -.menu-foot { display: grid; gap: 20px; padding-top: 32px; border-top: 1px solid var(--border); margin-top: 32px; } -.menu-foot p { font-size: 13.5px; color: var(--muted); } -.menu-foot .button { justify-self: start; } +.menu-foot { display: flex; flex-direction: column; gap: 16px; } +.menu-foot p { font-size: var(--text-caption); color: var(--muted); } -@media (min-width: 640px) { .nav-github { display: inline-flex; } } -@media (min-width: 900px) { .nav-end .button.small { display: inline-flex; } } -@media (min-width: 1120px) { - .nav-links { display: flex; } - .nav-inner { gap: 32px; } - .menu-button, .menu { display: none !important; } - .nav-end { margin-left: 0; } +@media (max-width: 1119px) { + .nav-links, .nav-github { display: none; } + .menu-button { display: inline-flex; } +} +@media (max-width: 520px) { + .nav-end .button { display: none; } } -/* --- Hero --------------------------------------------------------------------------- */ +/* --- Index lists: the signature component ------------------------------------------------ */ -.hero { - position: relative; isolation: isolate; overflow: hidden; - display: flex; flex-direction: column; justify-content: flex-end; - min-height: 100vh; min-height: 100svh; - padding-top: var(--nav); +.index { border-top: 1px solid var(--rule); } +.row { position: relative; border-bottom: 1px solid var(--rule); } +.row > a, .row.card { + position: relative; display: grid; grid-template-columns: var(--index) 1fr auto; align-items: baseline; + column-gap: 16px; padding: 18px 0; color: var(--ink); } -.hero-media { position: absolute; inset: 0; z-index: -1; background: #1a1418; } -.hero-parallax { position: absolute; inset: -6% 0; will-change: transform; } -.hero-parallax picture { display: block; height: 100%; animation: settle 2.8s var(--ease) both; } -.hero-parallax img { - width: 100%; height: 100%; object-fit: cover; object-position: 50% 40%; - animation: drift 48s ease-in-out 2.8s infinite alternate; -} -.hero-veil { - position: absolute; inset: 0; - background: - linear-gradient(180deg, rgba(17, 17, 19, 0.7) 0%, rgba(17, 17, 19, 0) 24%), - linear-gradient(180deg, rgba(17, 17, 19, 0) 40%, rgba(17, 17, 19, 0.62) 70%, var(--bg) 100%), - radial-gradient(130% 90% at 50% 38%, rgba(17, 17, 19, 0) 45%, rgba(10, 10, 12, 0.6) 100%), - linear-gradient(180deg, rgba(62, 40, 120, 0.22), rgba(62, 40, 120, 0) 50%); -} -.grain { - position: absolute; inset: -60%; pointer-events: none; opacity: 0.11; - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.9 0'/%3E%3C/filter%3E%3Crect width='160' height='160' filter='url(%23n)'/%3E%3C/svg%3E"); - animation: grain 1.4s steps(6) infinite; +.row-index { transition: color var(--quick) var(--ease-quick); } +.row-name { font-size: var(--text-title); line-height: var(--text-title-line); letter-spacing: var(--text-title-tracking); font-weight: 500; } +.row-meta { text-align: right; } +/* Hover: a soft plate fades in behind the row and reaches past it; the index turns to ink. */ +.row > a::before, .row.card::before { + content: ""; position: absolute; inset: 0 calc(-1 * var(--plate-bleed)); z-index: -1; + border-radius: var(--radius-plate); background: var(--plate-soft); opacity: 0; + transition: opacity var(--quick) var(--ease-quick); } +.row > a, .row.card { z-index: 0; } +.row > a:hover::before, .row.card:hover::before { opacity: 1; } +.row > a:hover .row-index, .row.card:hover .row-index { color: var(--ink); } +.row > a:hover, .row.card:hover { color: var(--ink); } -.hero-content { - width: 100%; max-width: calc(var(--max) + 2 * var(--gutter)); margin: 0 auto; - padding: 0 var(--gutter) clamp(44px, 9vh, 112px); - text-align: center; -} -.hero-title { - margin: 0; - font: 400 clamp(96px, 25vw, 300px)/0.84 var(--display); - letter-spacing: -0.035em; color: #f5f5f6; - text-shadow: 0 4px 60px rgba(0, 0, 0, 0.35); -} -.letters { display: inline-block; white-space: nowrap; } -.letters span { display: inline-block; animation: letter 1.3s var(--ease) both; } -.letters span:nth-child(1) { animation-delay: 0.2s; } -.letters span:nth-child(2) { animation-delay: 0.26s; } -.letters span:nth-child(3) { animation-delay: 0.32s; } -.letters span:nth-child(4) { animation-delay: 0.38s; } -.letters span:nth-child(5) { animation-delay: 0.44s; } -.letters span:nth-child(6) { animation-delay: 0.5s; } -.letters span:nth-child(7) { animation-delay: 0.56s; } -.hero-line { - max-width: 36em; margin: clamp(20px, 3vh, 32px) auto 0; - font-size: clamp(17px, 1.45vw, 20px); line-height: 1.55; color: rgba(232, 232, 234, 0.86); - text-wrap: balance; - animation: rise 1s var(--ease) 0.7s both; -} -.hero-actions { - display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; - margin-top: clamp(28px, 4vh, 40px); - animation: rise 1s var(--ease) 0.82s both; -} -.hero .download-meta { margin-top: 16px; color: rgba(232, 232, 234, 0.6); animation: rise 1s var(--ease) 0.9s both; } -.hero .download-meta a { color: #c3b2f2; } +/* --- Hero -------------------------------------------------------------------------------- */ -.hero-foot { - display: flex; align-items: center; justify-content: space-between; gap: 24px; - width: 100%; max-width: calc(var(--max) + 2 * var(--gutter)); margin: 0 auto; - padding: 16px var(--gutter) 18px; - animation: rise 1s var(--ease) 1s both; -} -.hero-foot::before { - content: ""; position: absolute; left: var(--gutter); right: var(--gutter); height: 1px; margin-top: -16px; - background: rgba(255, 255, 255, 0.09); -} -.hero-foot { position: relative; } -.disclaimer { font-size: 13.5px; line-height: 1.5; color: #cfcfd4; } -.disclaimer-tag { - display: inline-block; margin-right: 8px; padding: 2px 7px; - font: 11px/1.4 var(--mono); letter-spacing: 0.06em; text-transform: uppercase; color: var(--text); - border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 4px; vertical-align: 1px; -} -.scroll-cue { - display: none; align-items: center; gap: 12px; min-height: 44px; - font-size: 13px; color: rgba(232, 232, 234, 0.7); white-space: nowrap; -} -.scroll-cue span { position: relative; width: 1px; height: 28px; background: rgba(255, 255, 255, 0.18); overflow: hidden; } -.scroll-cue span::after { content: ""; position: absolute; left: 0; top: 0; width: 1px; height: 12px; background: #fff; animation: cue 2.4s var(--ease) infinite; } -.scroll-cue:hover { color: var(--text); } -@media (min-width: 760px) { .scroll-cue { display: inline-flex; } } +.hero { padding: calc(var(--nav) + clamp(48px, 9vw, 120px)) 0 clamp(64px, 8vw, 112px); } +.hero-title { max-width: 14ch; margin-bottom: 20px; } +.hero .lede { font-size: var(--text-body); } +.hero-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 32px; } +.hero-index { margin-top: clamp(48px, 7vw, 88px); } +.hero .disclaimer { margin-top: 24px; } -/* --- Sections ----------------------------------------------------------------------- */ +/* --- Sections ------------------------------------------------------------------------------- */ -.section { padding: clamp(96px, 12vw, 168px) 0 0; } -.section-head { display: grid; gap: 24px; margin-bottom: clamp(44px, 6vw, 72px); } -.section-head .kicker { margin-bottom: 8px; } -@media (min-width: 1000px) { - .section-head { grid-template-columns: 1.2fr 1fr; align-items: end; column-gap: 64px; } - .section-head .kicker { grid-column: 1 / -1; margin-bottom: clamp(16px, 2vw, 32px); } - .section-head .lede { justify-self: end; } -} +.section { padding: clamp(72px, 10vw, 144px) 0; } +.section-head { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px 48px; align-items: end; margin-bottom: 48px; } +.section-head .kicker { grid-column: 1 / -1; margin-bottom: 0; } +.section .title { font-size: var(--text-display); line-height: var(--text-display-line); letter-spacing: var(--text-display-tracking); } -/* What it is: a statement that lights up word by word as it scrolls past. */ .statement { - max-width: 21em; - font: 400 clamp(32px, 4.5vw, 64px)/1.1 var(--display); - letter-spacing: -0.018em; color: var(--text); - text-wrap: pretty; + max-width: 28ch; font-size: var(--text-title); line-height: 1.15; + letter-spacing: var(--text-title-tracking); font-weight: 500; text-wrap: balance; } -/* The fill runs along the whole inline box, so it lights the lines in reading order. */ -.js .fill { - color: transparent; - background: linear-gradient(90deg, var(--text) calc(var(--p, 0) * 1% - 2%), #3a3a40 calc(var(--p, 0) * 1% + 2%)); - -webkit-background-clip: text; background-clip: text; +.facts { margin-top: 56px; } +.fact, .features li { + display: grid; grid-template-columns: var(--index) minmax(0, 18rem) minmax(0, 1fr); column-gap: 16px; + align-items: baseline; padding: 20px 0; } -.facts { display: grid; gap: 40px; margin-top: clamp(64px, 8vw, 112px); } -.fact { padding-top: 24px; border-top: 1px solid var(--border); } -.fact h3 { font-size: 16px; font-weight: 500; color: var(--text); margin-bottom: 10px; } -.fact p { font-size: 15px; color: var(--muted); max-width: 40ch; } -@media (min-width: 900px) { .facts { grid-template-columns: repeat(3, 1fr); gap: 48px; } } +.fact h3, .features h3 { font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); } +.fact p, .features p { max-width: var(--measure); color: var(--muted); } -/* In game: a mosaic of large screenshots. */ -.mosaic { display: grid; gap: clamp(12px, 1.6vw, 20px); grid-template-columns: 1fr; } -.tile { margin: 0; min-width: 0; } -.zoom { - position: relative; display: block; width: 100%; padding: 0; border: 0; background: var(--deep); - border-radius: var(--radius-large); overflow: hidden; cursor: zoom-in; aspect-ratio: 16 / 10; -} -.zoom::after { content: ""; position: absolute; inset: 0; border-radius: inherit; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.06); pointer-events: none; } -.zoom img { width: 100%; height: 100%; object-fit: cover; transition: transform 1.6s var(--ease), scale 900ms var(--ease); } -.zoom:hover img { scale: 1.035; } -.tile figcaption { display: flex; gap: 12px; margin-top: 14px; font-size: 14px; color: var(--muted); } -.tile figcaption span { font: 12px/1.7 var(--mono); color: var(--faint); } -@media (min-width: 640px) { - .mosaic { grid-template-columns: repeat(2, 1fr); } - .tile-wide { grid-column: 1 / -1; } -} -@media (min-width: 1000px) { - .mosaic { grid-template-columns: repeat(12, 1fr); } - .tile { grid-column: span 4; } - .tile-wide { grid-column: span 8; } - .tile-tall { display: flex; flex-direction: column; } - .tile-tall .zoom { flex: 1; aspect-ratio: auto; } - .tile-wide .zoom { aspect-ratio: 16 / 9.4; } -} +/* Screenshots: no frames, the images themselves. */ +.mosaic { display: grid; grid-template-columns: repeat(6, 1fr); gap: 12px; } +.tile { margin: 0; grid-column: span 2; } +.tile-wide { grid-column: span 4; } +.tile-tall { grid-column: span 2; } +.tile-wide, .tile-tall { grid-row: span 1; } +.zoom { display: block; width: 100%; padding: 0; border: 0; background: var(--plate-soft); border-radius: var(--radius-plate); overflow: hidden; cursor: zoom-in; } +.zoom img { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; transition: transform var(--enter) var(--ease-enter); } +.zoom:hover img { transform: scale(1.02); } +figcaption { display: flex; gap: 12px; margin-top: 10px; font-size: var(--text-caption); color: var(--muted); } +figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter-spacing: var(--text-micro-tracking); padding-top: 1px; } -/* Parity: the harness count, then the fourteen subsystems. */ -.parity-hero { display: grid; gap: 32px; } -.count { - margin: 0; - font: 400 clamp(150px, 27vw, 400px)/0.78 var(--display); - letter-spacing: -0.045em; - color: var(--text); -} -/* Each digit carries the fade itself, so the digits can move on their own layers. */ -.digits, .digits span { - background: linear-gradient(180deg, #f4f4f5 30%, #5c5c64 100%); - -webkit-background-clip: text; background-clip: text; color: transparent; - padding-bottom: 0.06em; -} -.digits span { display: inline-block; } -.parity-copy { display: grid; gap: 22px; max-width: 640px; } -.count-label { margin-top: 20px; font-size: clamp(16px, 1.25vw, 18px); color: var(--muted); max-width: 34ch; } -.parity-copy .title { font-size: clamp(40px, 4.8vw, 72px); } -.parity-copy .prose { font-size: 15px; max-width: 58ch; } -@media (min-width: 1000px) { - .parity-hero { grid-template-columns: auto 1fr; align-items: end; column-gap: clamp(48px, 6vw, 96px); } -} - -.systems { - list-style: none; margin: clamp(64px, 8vw, 104px) 0 0; padding: 0; - display: grid; grid-template-columns: 1fr; - border: 1px solid var(--border); border-radius: var(--radius-large); overflow: hidden; -} -/* Each cell draws its own right and bottom divider; the container's border hides the outer ones. */ +/* Parity: the count, then every subsystem as an index row. */ +.parity-hero { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 48px; align-items: end; margin-bottom: 64px; } +.count { font-size: clamp(96px, 16vw, 220px); line-height: 0.85; letter-spacing: -0.05em; font-weight: 500; } +.count .digits span { display: inline-block; } +.count-label { margin-top: 20px; max-width: 32ch; color: var(--muted); } +.parity-copy .title { margin-bottom: 16px; } +.prose { color: var(--ink-soft); max-width: var(--measure); } +.prose > * + * { margin-top: 12px; } +.systems { border-top: 1px solid var(--rule); } .system { - background: var(--bg); padding: 26px 26px 30px; - box-shadow: 1px 0 0 var(--border), 0 1px 0 var(--border); - transition: background-color var(--move) var(--ease); + display: grid; grid-template-columns: var(--index) minmax(0, 1fr) auto; column-gap: 16px; row-gap: 6px; + padding: 20px 0; border-bottom: 1px solid var(--rule); position: relative; } -.system:hover { background: #151517; } -.system-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; font-size: 13px; } -.system-index { font: 12px/1 var(--mono); color: var(--faint); } -.system-state { display: inline-flex; align-items: center; gap: 7px; color: var(--muted); } -.system.is-full .system-state { color: #c9bdf0; } -.check { width: 15px; height: 15px; fill: none; stroke: var(--accent-text); stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; } -.check path { stroke-dasharray: 16; stroke-dashoffset: 0; } -.system h3 { margin: clamp(28px, 3vw, 44px) 0 12px; font: 400 28px/1.08 var(--display); letter-spacing: -0.01em; color: var(--text); } -.system-detail { font-size: 14px; line-height: 1.6; color: var(--muted); } -.system-detail .gap { color: var(--text); } -.system-detail code { white-space: nowrap; font-size: 12.5px; background: none; border: 0; padding: 0; color: var(--text); } -.legend { margin-top: 20px; max-width: 80ch; } -@media (min-width: 700px) { .systems { grid-template-columns: repeat(2, 1fr); } } -@media (min-width: 1140px) { .systems { grid-template-columns: repeat(3, 1fr); } } +.system-head { display: contents; } +.system-index { grid-column: 1; grid-row: 1; font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); padding-top: 0.6em; } +.system h3 { grid-column: 2; grid-row: 1; font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); } +.system-state { + grid-column: 3; grid-row: 1; display: inline-flex; align-items: center; gap: 6px; padding-top: 0.5em; + font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); + text-transform: uppercase; color: var(--muted); +} +.system.is-full .system-state { color: var(--success); } +.check { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 1.6; } +.system-detail { grid-column: 2 / 4; max-width: 72ch; font-size: var(--text-caption); line-height: 1.6; color: var(--muted); } +.gap { color: var(--ink); font-weight: 500; } +.legend { max-width: 80ch; } -/* The launcher: what it does, beside Horizon's own menus. */ -.launcher-grid { display: grid; gap: 56px; } -.launcher-copy .title { margin-bottom: 24px; } -.features { list-style: none; margin: 40px 0 0; padding: 0; } -.features li { padding: 20px 0; border-top: 1px solid var(--border); } -.features li:last-child { border-bottom: 1px solid var(--border); } -.features h3 { font-size: 16px; font-weight: 500; color: var(--text); margin-bottom: 6px; } -.features p { font-size: 15px; color: var(--muted); max-width: 52ch; } -.launcher-actions { display: grid; justify-items: start; gap: 14px; margin-top: 36px; } -.screens { position: relative; min-width: 0; } -.screens::before { - content: ""; position: absolute; inset: 10% -6% -6%; z-index: -1; pointer-events: none; - background: radial-gradient(50% 50% at 50% 50%, rgba(124, 92, 196, 0.2), rgba(124, 92, 196, 0)); -} -.tabs { - position: relative; display: inline-flex; flex-wrap: wrap; gap: 2px; padding: 4px; - background: rgba(255, 255, 255, 0.03); border: 1px solid var(--border); border-radius: 10px; -} +/* The launcher: copy and features on the left, the menus on the right. */ +.launcher-grid { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: clamp(32px, 5vw, 80px); align-items: start; } +.launcher-copy .title { margin-bottom: 16px; } +.launcher-copy .features { margin-top: 40px; } +.features li { grid-template-columns: var(--index) minmax(0, 1fr); row-gap: 4px; } +.features li p { grid-column: 2; font-size: var(--text-ui); } +.launcher-actions { margin-top: 32px; } +.screens { position: sticky; top: calc(var(--nav) + 24px); } +.tabs { position: relative; display: inline-flex; padding: 2px; gap: 2px; margin-bottom: 16px; border-radius: var(--radius-pill); background: var(--plate-soft); } .tabs button { - position: relative; z-index: 1; height: 44px; padding: 0 16px; - background: none; border: 0; border-radius: 7px; - font: 500 14px/1 var(--font); color: var(--muted); cursor: pointer; - transition: color var(--quick) var(--ease); + position: relative; z-index: 1; height: var(--segment); padding: 0 14px; border: 0; background: none; + border-radius: var(--radius-pill); color: var(--muted); font: 500 var(--text-label) / 1 var(--font); cursor: pointer; + transition: color var(--quick) var(--ease-quick); } -.tabs button:hover, .tabs button[aria-selected="true"] { color: var(--text); } -.tab-pill { - position: absolute; left: 0; top: 0; border-radius: 7px; - background: var(--raised); border: 1px solid var(--border); - transition: transform var(--move) var(--ease), width var(--move) var(--ease); -} -.no-js .tabs { display: none; } -.screen { - position: relative; margin-top: 16px; aspect-ratio: 16 / 10; - border-radius: var(--radius-large); overflow: hidden; background: var(--deep); - border: 1px solid var(--border); - box-shadow: 0 50px 120px -50px rgba(0, 0, 0, 0.9); -} -.screen-panel { - position: absolute; inset: 0; - opacity: 0; transform: scale(1.02); filter: blur(6px); - transition: opacity 520ms var(--ease), transform 700ms var(--ease), filter 520ms var(--ease); -} -.screen-panel.is-active { opacity: 1; transform: none; filter: none; } +.tabs button:hover { color: var(--ink); } +.tabs button[aria-selected="true"] { color: var(--page); } +.tab-pill { position: absolute; top: 0; left: 0; border-radius: var(--radius-pill); background: var(--ink); transition: transform var(--move) var(--ease-move), width var(--move) var(--ease-move); } +.screen { position: relative; aspect-ratio: 16 / 10; border-radius: var(--radius-plate); overflow: hidden; background: var(--plate-soft); } +.screen-panel { position: absolute; inset: 0; opacity: 0; transition: opacity var(--move) var(--ease-move); } +.screen-panel.is-active { opacity: 1; } .screen-panel img { width: 100%; height: 100%; object-fit: cover; } -.no-js .screen { aspect-ratio: auto; display: grid; gap: 1px; background: var(--border); } -.no-js .screen-panel { position: static; opacity: 1; transform: none; filter: none; } -.screen-caption { margin-top: 14px; font-size: 13.5px; color: var(--faint); } -@media (min-width: 1000px) { - .launcher-grid { grid-template-columns: 5fr 7fr; align-items: center; column-gap: clamp(48px, 6vw, 96px); } - .tabs button { height: 36px; } -} +.screen-caption { margin-top: 12px; font-size: var(--text-caption); color: var(--muted); } -/* Patch notes: the latest release set like a page, the ones before it folded. */ -.release-latest { display: grid; gap: 40px; } -.release-head { display: grid; align-content: start; gap: 14px; } -.release-version { font: 400 clamp(56px, 7vw, 108px)/0.92 var(--display); letter-spacing: -0.03em; color: var(--text); } -.release-line { font-size: 18px; color: var(--muted); max-width: 26ch; } -.release-head .link-arrow { margin-top: 6px; } -.release-body { max-width: 58ch; font-size: 16px; } -.release-body > p:first-child { font-size: 18px; color: var(--text); } -.release-body h3:first-child, .release-body h2:first-child { margin-top: 0; } -@media (min-width: 1000px) { - .release-latest { grid-template-columns: 4fr 7fr; column-gap: clamp(48px, 6vw, 96px); } - .release-head { position: sticky; top: calc(var(--nav) + 32px); align-self: start; } -} -.release-older { margin-top: clamp(64px, 8vw, 104px); } -.release-older-title { font-size: 13px; font-weight: 500; color: var(--muted); margin-bottom: 12px; } -.release { border-top: 1px solid var(--border); } -.release:last-of-type { border-bottom: 1px solid var(--border); } +/* Patch notes. */ +.release-latest { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: 48px; padding-top: 32px; border-top: 1px solid var(--rule); } +.release-head { position: sticky; top: calc(var(--nav) + 24px); align-self: start; display: flex; flex-direction: column; gap: 12px; } +.eyebrow { text-transform: uppercase; } +.release-version { font-size: var(--text-display); line-height: var(--text-display-line); letter-spacing: var(--text-display-tracking); font-weight: 500; } +.release-line { color: var(--muted); max-width: 36ch; } +.release-body { font-size: var(--text-ui); } +.prose h2, .prose h3, .prose h4 { font-size: var(--text-heading); line-height: var(--text-heading-line); color: var(--ink); margin-top: 28px; } +.prose ul, .prose ol { padding-left: 18px; list-style: disc; } +.prose li + li { margin-top: 6px; } +.prose li::marker { color: var(--muted); } +.prose strong { color: var(--ink); font-weight: 500; } +.prose pre { padding: 16px; border-radius: var(--radius-plate); background: var(--plate-soft); overflow-x: auto; } +.prose pre code { background: none; padding: 0; } +.release-older { margin-top: 64px; } +.release-older-title { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); text-transform: uppercase; margin-bottom: 12px; } +.release { border-top: 1px solid var(--rule); } +.release:last-of-type { border-bottom: 1px solid var(--rule); } .release summary { - display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 4px 24px; - min-height: 72px; padding: 14px 0; cursor: pointer; list-style: none; + display: grid; grid-template-columns: minmax(0, 12rem) minmax(0, 1fr) auto; gap: 16px; align-items: baseline; + padding: 18px 0; cursor: pointer; list-style: none; } .release summary::-webkit-details-marker { display: none; } -.release-tag { font: 400 26px/1.1 var(--display); color: var(--text); } -.release-sub { font-size: 15px; color: var(--muted); } -.release time { font: 12.5px/1 var(--mono); color: var(--faint); } -.release summary::after { - content: ""; grid-column: 3; grid-row: 1; justify-self: end; width: 9px; height: 9px; margin-left: 56px; - border-right: 1.5px solid var(--muted); border-bottom: 1.5px solid var(--muted); - transform: translateY(-3px) rotate(45deg); transition: transform var(--move) var(--ease); -} -.release[open] summary::after { transform: translateY(2px) rotate(-135deg); } -.release summary time { grid-column: 3; grid-row: 1; margin-right: 28px; } -.release summary:hover .release-tag { color: var(--accent-text); } -.release .prose { padding: 4px 0 32px; max-width: 58ch; } -.release-more { margin-top: 20px; } -@media (max-width: 640px) { - .release summary { grid-template-columns: 1fr auto; } - .release-sub { grid-column: 1 / -1; grid-row: 2; } - .release summary time { grid-column: 2; } - .release summary::after { grid-column: 2; margin-left: 0; } -} +.release-tag { font-size: var(--text-heading); font-weight: 500; letter-spacing: var(--text-heading-tracking); } +.release-sub { color: var(--muted); font-size: var(--text-ui); } +.release time { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } +.release[open] summary .release-tag { color: var(--accent); } +.release .prose { padding: 0 0 24px 12rem; margin-left: 16px; font-size: var(--text-ui); } +.release-more { margin-top: 24px; } /* Community. */ -.community .title { margin-bottom: clamp(44px, 6vw, 72px); } -.cards { - display: grid; gap: 1px; background: var(--border); - border: 1px solid var(--border); border-radius: var(--radius-large); overflow: hidden; -} -.card { - position: relative; display: grid; grid-template-rows: auto 1fr auto; gap: 12px; - min-height: 220px; padding: 30px 30px 26px; background: var(--bg); color: var(--text); - transition: background-color var(--move) var(--ease); -} -.card:hover { background: #151517; color: var(--text); } -.card:focus-visible { outline-offset: -3px; border-radius: 0; } -.card-title { font: 400 44px/1 var(--display); letter-spacing: -0.02em; } -.card-text { font-size: 15px; color: var(--muted); max-width: 30ch; } -.card-arrow { justify-self: end; font-size: 22px; color: var(--muted); transition: transform var(--move) var(--ease), color var(--quick) var(--ease); } -.card:hover .card-arrow { transform: translateX(6px); color: var(--accent-text); } -@media (min-width: 860px) { .cards { grid-template-columns: repeat(3, 1fr); } } +.cards { margin-top: 48px; } +.row.card { grid-template-columns: var(--index) minmax(0, 1fr) minmax(0, 1.4fr) auto; } +.card-title { font-size: var(--text-title); line-height: var(--text-title-line); letter-spacing: var(--text-title-tracking); font-weight: 500; } +.card-text { color: var(--muted); } +.card-arrow { color: var(--muted); transition: transform var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick); } +.card:hover .card-arrow { color: var(--accent); transform: translateX(4px); } +.contributors { margin-top: 96px; } +.contributors-title { font-size: var(--text-heading); line-height: var(--text-heading-line); } +.contributors-text { margin-top: 8px; color: var(--muted); } +.contributors-list { margin-top: 24px; display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 0 24px; border-top: 1px solid var(--rule); } +.contributor { display: grid; grid-template-columns: 32px 1fr; column-gap: 12px; align-items: center; padding: 14px 0; border-bottom: 1px solid var(--rule); color: var(--ink); } +.contributor-avatar { grid-row: span 2; width: 32px; height: 32px; border-radius: 50%; background: var(--plate); } +.contributor-name { font-weight: 500; } +.contributor-count { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } +.contributor:hover .contributor-name { color: var(--accent); } -.contributors { margin-top: clamp(64px, 8vw, 112px); } -.contributors-title { font: 400 clamp(28px, 3vw, 40px)/1.1 var(--display); letter-spacing: -0.015em; color: var(--text); } -.contributors-text { margin-top: 10px; font-size: 15px; color: var(--muted); max-width: 46ch; } -.contributors-list { - display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr)); column-gap: 32px; - list-style: none; margin-top: clamp(24px, 3vw, 36px); padding: 0; -} -.contributors-list li { border-top: 1px solid var(--border); } -.contributor { - display: grid; grid-template-columns: 48px 1fr; grid-template-rows: auto auto; column-gap: 16px; align-items: center; - min-height: 44px; padding: 20px 0; color: var(--text); -} -.contributor-avatar { grid-row: 1 / 3; width: 48px; height: 48px; border-radius: 50%; background: var(--raised); border: 1px solid var(--border); object-fit: cover; } -.contributor-name { align-self: end; font-size: 16px; font-weight: 500; line-height: 1.3; overflow-wrap: anywhere; transition: color var(--quick) var(--ease); } -.contributor-count { align-self: start; font: 12px/1.7 var(--mono); color: var(--faint); } -.contributor:hover .contributor-name { color: var(--accent-text); } +/* --- Footer: small print, then the giant faint wordmark --------------------------------- */ -/* --- Footer ------------------------------------------------------------------------- */ - -.footer { margin-top: clamp(112px, 14vw, 200px); border-top: 1px solid var(--border); padding-top: clamp(64px, 8vw, 104px); overflow: hidden; } -.footer-disclaimer { max-width: 22em; font: 400 clamp(28px, 3.4vw, 46px)/1.15 var(--display); letter-spacing: -0.01em; color: var(--text); text-wrap: balance; } -.footer-cols { display: grid; gap: 24px; margin-top: 48px; } -.footer-cols p { font-size: 14px; color: var(--muted); max-width: 62ch; } -@media (min-width: 1180px) { .footer-cols { grid-template-columns: repeat(3, 1fr); gap: 48px; } } -.footer-bar { - display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 32px; - margin-top: 56px; padding: 16px 0; border-top: 1px solid var(--border); -} -.footer-mark { font: 400 24px/1 var(--display); } -.footer-links { display: flex; flex-wrap: wrap; gap: 0 22px; } -.footer-links a { display: inline-flex; align-items: center; min-height: 44px; font-size: 14px; color: var(--muted); } -.footer-links a:hover { color: var(--text); } +.footer { padding: clamp(72px, 9vw, 120px) 0 0; overflow: hidden; } +.footer-disclaimer { max-width: 24ch; font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); font-weight: 500; } +.footer-cols { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 32px; margin-top: 40px; } +.footer-cols p { font-size: var(--text-caption); line-height: 1.7; color: var(--muted); } +.footer-bar { display: flex; justify-content: space-between; align-items: center; gap: 24px; margin-top: 56px; font-size: var(--text-caption); color: var(--muted); } +.footer-links { display: flex; flex-wrap: wrap; gap: 20px; } +.footer-links a { color: var(--muted); } +.footer-links a:hover { color: var(--ink); } .footer-word { - margin: 24px 0 -0.24em; text-align: center; white-space: nowrap; - font: 400 27vw/0.9 var(--display); letter-spacing: -0.045em; - color: transparent; -webkit-text-stroke: 1px #24242a; - pointer-events: none; - user-select: none; + box-sizing: border-box; width: 100%; margin: 24px auto 0; padding: 0 var(--g); max-width: var(--max); + font-size: var(--text-wordmark); line-height: var(--text-wordmark-line); letter-spacing: var(--text-wordmark-tracking); + font-weight: var(--text-wordmark-weight); color: var(--plate); white-space: nowrap; user-select: none; + translate: -0.05em 0.12em; } +:root[data-theme="dark"] .footer-word { color: var(--plate-soft); } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .footer-word { color: var(--plate-soft); } } -/* --- Lightbox ----------------------------------------------------------------------- */ +/* --- Lightbox ---------------------------------------------------------------------------- */ -.lightbox { - max-width: min(1600px, 94vw); max-height: 94vh; padding: 0; border: 0; background: none; color: var(--text); overflow: visible; -} -.lightbox[open] { animation: open 420ms var(--ease) both; } -.lightbox::backdrop { background: rgba(8, 8, 9, 0.88); -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); } -.lightbox img { max-height: 84vh; width: auto; margin: 0 auto; border-radius: var(--radius-large); } -.lightbox form { display: flex; justify-content: flex-end; margin-bottom: 12px; } -.lightbox-caption { margin-top: 12px; font-size: 14px; color: var(--muted); text-align: center; } +.lightbox { width: min(1400px, 94vw); max-height: 92vh; padding: 0; border: 0; border-radius: var(--radius-plate); background: var(--surface); color: var(--ink); } +.lightbox::backdrop { background: color-mix(in srgb, var(--page) 86%, transparent); -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); } +.lightbox img { width: 100%; } +.lightbox form { position: absolute; top: 12px; right: 12px; } +.lightbox-caption { padding: 14px 16px; font-size: var(--text-caption); color: var(--muted); } -/* --- Motion ------------------------------------------------------------------------- */ +/* --- 404 --------------------------------------------------------------------------------- */ + +.lost { min-height: 100vh; display: flex; flex-direction: column; justify-content: space-between; } +.lost .hero { padding-top: clamp(96px, 16vh, 200px); } + +/* --- Motion: content arrives with a fade and a short rise, a few tens of ms apart --------- */ -.js .reveal { opacity: 0; transform: translateY(22px); filter: blur(6px); } -.js .reveal-media { opacity: 0; transform: translateY(44px); } -.js .reveal-media .zoom img { transform: scale(1.1); } .js .reveal, .js .reveal-media { - transition: opacity var(--enter) var(--ease) var(--d, 0ms), transform 1.1s var(--ease) var(--d, 0ms), filter var(--enter) var(--ease) var(--d, 0ms); + opacity: 0; transform: translateY(var(--rise)); filter: blur(4px); + transition: opacity var(--enter) var(--ease-enter) var(--d, 0ms), transform var(--enter) var(--ease-enter) var(--d, 0ms), filter var(--enter) var(--ease-enter) var(--d, 0ms); } -.js .is-visible { opacity: 1; transform: none; filter: none; } -.js .is-visible .zoom img { transform: none; } -.js .systems .system { opacity: 0; transform: translateY(14px); transition: opacity 700ms var(--ease) var(--d, 0ms), transform 900ms var(--ease) var(--d, 0ms), background-color var(--move) var(--ease); } +.js .reveal.is-visible, .js .reveal-media.is-visible { opacity: 1; transform: none; filter: none; } +.js .systems .system { opacity: 0; transform: translateY(var(--rise)); transition: opacity var(--enter) var(--ease-enter) var(--d, 0ms), transform var(--enter) var(--ease-enter) var(--d, 0ms); } .js .systems.is-visible .system { opacity: 1; transform: none; } -.js .systems .check path { stroke-dashoffset: 16; transition: stroke-dashoffset 700ms var(--ease) calc(var(--d, 0ms) + 350ms); } -.js .systems.is-visible .check path { stroke-dashoffset: 0; } -.js .count.is-visible .digits span { animation: letter 1.2s var(--ease) both; } -.js .count.is-visible .digits span:nth-child(2) { animation-delay: 0.08s; } -.js .count.is-visible .digits span:nth-child(3) { animation-delay: 0.16s; } -.js .count.is-visible .digits span:nth-child(4) { animation-delay: 0.24s; } -.magnetic { will-change: transform; } - -@keyframes letter { from { opacity: 0; transform: translateY(0.18em); filter: blur(14px); } to { opacity: 1; transform: none; filter: none; } } -@keyframes rise { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } } -@keyframes settle { from { transform: scale(1.09); } to { transform: none; } } -@keyframes drift { from { transform: scale(1.02); } to { transform: scale(1.07) translate3d(-1.2%, -0.8%, 0); } } -@keyframes grain { - 0% { transform: translate(0, 0); } 17% { transform: translate(-4%, 3%); } 33% { transform: translate(3%, -5%); } - 50% { transform: translate(-6%, -2%); } 67% { transform: translate(5%, 4%); } 83% { transform: translate(-2%, 6%); } -} -@keyframes cue { from { transform: translateY(-12px); } to { transform: translateY(28px); } } -@keyframes open { from { opacity: 0; transform: scale(0.97); } to { opacity: 1; transform: none; } } - @media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } - *, *::before, *::after { animation: none !important; transition-duration: 1ms !important; transition-delay: 0ms !important; } - .js .reveal, .js .reveal-media, .js .systems .system { opacity: 1; transform: none; filter: none; } - .js .reveal-media .zoom img { transform: none; } - .js .systems .check path { stroke-dashoffset: 0; } - .js .fill { color: var(--text); background: none; } + .js .reveal, .js .reveal-media, .js .systems .system { transform: none; filter: none; transition: opacity 200ms linear; } + .menu nav a { transform: none; } } -/* --- The not-found page ------------------------------------------------------------- */ +/* --- Touch: every target at least 44 px high ------------------------------------------- */ -.lost { display: grid; min-height: 100vh; } -.lost .hero { min-height: 100vh; } -.lost .hero-content { padding-bottom: clamp(64px, 14vh, 160px); } -.lost .eyebrow { margin-bottom: 12px; } -.lost .hero-title { font-size: clamp(88px, 16vw, 240px); } -.lost .disclaimer { margin-top: 40px; } +@media (pointer: coarse) { + .button, .button.large, .button.small, .tabs button { height: 44px; } + .nav-mark, .theme-toggle, .nav-github { min-height: 44px; } + .link-arrow, .footer-links a { display: inline-flex; align-items: center; min-height: 44px; } +} + +/* --- Narrow screens ------------------------------------------------------------------------ */ + +@media (max-width: 900px) { + .section-head, .parity-hero, .launcher-grid, .release-latest { grid-template-columns: minmax(0, 1fr); } + .section-head { gap: 16px; } + .screens, .release-head { position: static; } + .fact { grid-template-columns: var(--index) minmax(0, 1fr); row-gap: 6px; } + .fact p { grid-column: 2; } + .mosaic { grid-template-columns: minmax(0, 1fr); } + .tile, .tile-wide, .tile-tall { grid-column: auto; } + .row.card { grid-template-columns: var(--index) minmax(0, 1fr) auto; row-gap: 4px; } + .card-text { grid-column: 2; grid-row: 2; font-size: var(--text-ui); } + .card-arrow { grid-row: 1; grid-column: 3; } + .release summary { grid-template-columns: minmax(0, 1fr) auto; } + .release-sub { grid-column: 1 / -1; grid-row: 2; } + .release .prose { padding-left: 0; margin-left: 0; } + .footer-cols { grid-template-columns: minmax(0, 1fr); } + .footer-bar { flex-direction: column; align-items: flex-start; } + .system { grid-template-columns: var(--index) minmax(0, 1fr); } + .system-state { grid-column: 2; grid-row: 2; padding-top: 0; } + .system-detail { grid-column: 2; } + .row > a { grid-template-columns: 28px 1fr auto; padding: 16px 0; } + :root { --index: 28px; } +} diff --git a/website/src/tokens.css b/website/src/tokens.css new file mode 100644 index 000000000..d272865cc --- /dev/null +++ b/website/src/tokens.css @@ -0,0 +1,121 @@ +/* Generated from crates/horizon-theme by `cargo run -p xtask -- tokens`; do not edit. + docs/design-system.md describes the tokens. */ + +:root { + --page: #fafafc; + --plate-soft: #f3f3f8; + --plate: #ebecf4; + --surface: #ffffff; + --rule: #e2e3ea; + --ink: #16181f; + --ink-soft: #3b3e49; + --muted: #646875; + --accent: #5b3fd6; + --on-accent: #ffffff; + --danger: #b4372a; + --success: #1d7a48; + color-scheme: light; + --font: "Geist", ui-sans-serif, system-ui, sans-serif; + --mono: "Geist Mono", ui-monospace, monospace; + --text-micro: 11px; + --text-micro-line: 1.5; + --text-micro-tracking: 0.04em; + --text-micro-weight: 400; + --text-caption: 12px; + --text-caption-line: 1.5; + --text-caption-tracking: 0em; + --text-caption-weight: 400; + --text-label: 13px; + --text-label-line: 1.5; + --text-label-tracking: 0em; + --text-label-weight: 400; + --text-ui: 14px; + --text-ui-line: 1.5; + --text-ui-tracking: 0em; + --text-ui-weight: 400; + --text-body: clamp(15px, calc(15px + 2 * (100vw - 375px) / 1065), 17px); + --text-body-line: 1.6; + --text-body-tracking: 0em; + --text-body-weight: 400; + --text-heading: clamp(20px, calc(20px + 4 * (100vw - 375px) / 1065), 24px); + --text-heading-line: 1.3; + --text-heading-tracking: -0.01em; + --text-heading-weight: 500; + --text-title: clamp(32px, calc(32px + 16 * (100vw - 375px) / 1065), 48px); + --text-title-line: 1.05; + --text-title-tracking: -0.02em; + --text-title-weight: 500; + --text-display: clamp(34px, calc(34px + 30 * (100vw - 375px) / 1065), 64px); + --text-display-line: 1.05; + --text-display-tracking: -0.025em; + --text-display-weight: 500; + --text-wordmark: 18vw; + --text-wordmark-line: 0.8; + --text-wordmark-tracking: -0.04em; + --text-wordmark-weight: 500; + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 24px; + --space-6: 32px; + --space-7: 48px; + --space-8: 64px; + --space-9: 96px; + --gutter: 64px; + --gutter-narrow: 16px; + --radius: 8px; + --radius-plate: 12px; + --radius-pill: 999px; + --rule-width: 1px; + --control: 32px; + --control-large: 40px; + --segment: 28px; + --field: 36px; + --row: 86px; + --index: 40px; + --plate-bleed: 16px; + --rise: 8px; + --measure: 56ch; + --quick: 150ms; + --ease-quick: cubic-bezier(0.4, 0, 0.2, 1); + --move: 240ms; + --ease-move: cubic-bezier(0.23, 1, 0.32, 1); + --enter: 600ms; + --ease-enter: cubic-bezier(0.23, 1, 0.32, 1); + --stagger: 40ms; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --page: #0d0e13; + --plate-soft: #181a22; + --plate: #20222c; + --surface: #16181f; + --rule: #24262f; + --ink: #ecedf3; + --ink-soft: #c5c7d1; + --muted: #8b8f9c; + --accent: #9a86ff; + --on-accent: #0d0e13; + --danger: #f07a68; + --success: #45c27a; + color-scheme: dark; + } +} + +:root[data-theme="dark"] { + --page: #0d0e13; + --plate-soft: #181a22; + --plate: #20222c; + --surface: #16181f; + --rule: #24262f; + --ink: #ecedf3; + --ink-soft: #c5c7d1; + --muted: #8b8f9c; + --accent: #9a86ff; + --on-accent: #0d0e13; + --danger: #f07a68; + --success: #45c27a; + color-scheme: dark; +} diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 9c84fa59b..de1a0ecab 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -4,7 +4,10 @@ version = "0.1.0" edition.workspace = true license.workspace = true publish = false -description = "Repository tasks: cargo run -p xtask -- package BINARY OUTDIR" +description = "Repository tasks: cargo run -p xtask -- package BINARY OUTDIR | tokens" + +[dependencies] +horizon-theme = { path = "../crates/horizon-theme" } [lints] workspace = true diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3b6b6a1ce..18544f617 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -5,12 +5,19 @@ //! horizon-prepare), the exporters horizon-prepare compiles, its sources (the launcher compares //! them to its own), and PLAY.txt. It holds none of Minecraft's files: players prepare those //! from their own copy. .github/workflows/release.yml makes the release folders with it. +//! +//! `tokens`: writes `website/src/tokens.css`, the design tokens of `crates/horizon-theme` as CSS +//! custom properties (a horizon-theme test fails when the file is out of date). +//! +//! `icons`: renders the icon masters in `docs/media/brand` (with `rsvg-convert`, from librsvg) +//! into every size the platforms and the website use, and packs `packaging/icons/horizon.ico` +//! and `horizon.icns`. `docs/media/brand/README.md` lists what goes where. use std::fs; use std::path::{Component, Path, PathBuf}; use std::process::{Command, ExitCode}; -const USAGE: &str = "usage: cargo run -p xtask -- package BINARY OUTDIR"; +const USAGE: &str = "usage: cargo run -p xtask -- package BINARY OUTDIR | tokens | icons"; /// What the release folder takes from the repository at HEAD, as `git archive` writes it. const ARCHIVED: [&str; 5] = [ @@ -30,6 +37,8 @@ fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); let result = match args.as_slice() { [task, binary, out] if task == "package" => package(Path::new(binary), Path::new(out)), + [task] if task == "tokens" => tokens(), + [task] if task == "icons" => icons(), _ => Err(USAGE.to_string()), }; match result { @@ -58,6 +67,152 @@ fn git(repo: &Path, args: &[&str]) -> Result, String> { Ok(output.stdout) } +fn tokens() -> Result<(), String> { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../website/src/tokens.css"); + fs::write(&path, horizon_theme::css()).map_err(|e| format!("{}: {e}", path.display()))?; + println!("wrote website/src/tokens.css"); + Ok(()) +} + +/// The square icon's sizes: Linux's hicolor theme, and the ones the .ico holds. +const HICOLOR: [u32; 8] = [16, 24, 32, 48, 64, 128, 256, 512]; +const ICO: [u32; 7] = [16, 24, 32, 48, 64, 128, 256]; +/// The .icns entries: type and pixel size, macOS's tile drawn on Apple's grid. +const ICNS: [(&[u8; 4], u32); 11] = [ + (b"icp4", 16), + (b"icp5", 32), + (b"icp6", 64), + (b"ic07", 128), + (b"ic08", 256), + (b"ic09", 512), + (b"ic10", 1024), + (b"ic11", 32), + (b"ic12", 64), + (b"ic13", 256), + (b"ic14", 512), +]; + +fn render(svg: &Path, size: (u32, u32)) -> Result, String> { + let output = Command::new("rsvg-convert") + .arg("-w") + .arg(size.0.to_string()) + .arg("-h") + .arg(size.1.to_string()) + .arg(svg) + .output() + .map_err(|e| format!("rsvg-convert (librsvg): {e}"))?; + if !output.status.success() { + return Err(format!( + "rsvg-convert {}: {}", + svg.display(), + String::from_utf8_lossy(&output.stderr).trim() + )); + } + Ok(output.stdout) +} + +fn write(path: &Path, data: &[u8]) -> Result<(), String> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + fs::write(path, data).map_err(|e| format!("{}: {e}", path.display())) +} + +/// An .ico whose images are PNGs (Windows Vista and later read them at every size). +fn ico(images: &[(u32, Vec)]) -> Vec { + let mut out = vec![0, 0, 1, 0]; + out.extend((images.len() as u16).to_le_bytes()); + let mut offset = 6 + 16 * images.len(); + for (size, png) in images { + // A width or height of 256 is written as 0. + let side = if *size >= 256 { 0 } else { *size as u8 }; + out.extend([side, side, 0, 0]); + out.extend(1u16.to_le_bytes()); + out.extend(32u16.to_le_bytes()); + out.extend((png.len() as u32).to_le_bytes()); + out.extend((offset as u32).to_le_bytes()); + offset += png.len(); + } + for (_, png) in images { + out.extend(png); + } + out +} + +/// An .icns of PNG entries. +fn icns(entries: &[(&[u8; 4], Vec)]) -> Vec { + let body: usize = entries.iter().map(|(_, png)| 8 + png.len()).sum(); + let mut out = b"icns".to_vec(); + out.extend(((8 + body) as u32).to_be_bytes()); + for (kind, png) in entries { + out.extend(*kind); + out.extend(((8 + png.len()) as u32).to_be_bytes()); + out.extend(png); + } + out +} + +fn icons() -> Result<(), String> { + let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let brand = repo.join("docs/media/brand"); + let square = brand.join("icon.svg"); + let packaging = repo.join("packaging/icons"); + for size in HICOLOR { + let png = render(&square, (size, size))?; + write( + &packaging.join(format!("hicolor/{size}x{size}/apps/horizon.png")), + &png, + )?; + } + write( + &packaging.join("hicolor/scalable/apps/horizon.svg"), + &fs::read(&square).map_err(|e| format!("{}: {e}", square.display()))?, + )?; + let images = ICO + .iter() + .map(|&s| render(&square, (s, s)).map(|png| (s, png))) + .collect::, _>>()?; + write(&packaging.join("horizon.ico"), &ico(&images))?; + let macos = brand.join("icon-macos.svg"); + let entries = ICNS + .iter() + .map(|&(kind, s)| render(&macos, (s, s)).map(|png| (kind, png))) + .collect::, _>>()?; + write(&packaging.join("horizon.icns"), &icns(&entries))?; + // The window icon the game and the launcher set at run time (X11 and Windows title bars). + write( + &repo.join("crates/horizon-theme/icons/horizon-64.png"), + &render(&square, (64, 64))?, + )?; + // Avatars and the website's icons. + let avatar = brand.join("avatar.svg"); + for (svg, size, out) in [ + ( + &avatar, + 500, + "docs/media/brand/social/github-avatar-500.png", + ), + (&avatar, 512, "docs/media/brand/social/discord-icon-512.png"), + ( + &brand.join("avatar-kira.svg"), + 512, + "docs/media/brand/social/kira-avatar-512.png", + ), + (&avatar, 180, "website/public/apple-touch-icon.png"), + (&square, 32, "website/public/favicon-32.png"), + (&square, 1024, "docs/media/brand/icon-1024.png"), + (&macos, 1024, "docs/media/brand/icon-macos-1024.png"), + ] { + write(&repo.join(out), &render(svg, (size, size))?)?; + } + write( + &repo.join("website/public/favicon.svg"), + &fs::read(&square).map_err(|e| format!("{}: {e}", square.display()))?, + )?; + println!("wrote packaging/icons, the window icon, the avatars and the website's icons"); + Ok(()) +} + fn package(binary: &Path, out: &Path) -> Result<(), String> { let top = git( Path::new(env!("CARGO_MANIFEST_DIR")),
Horizon's title screen: a sidebar, the Horizon title, Singleplayer and Multiplayer buttons and the last world played, over a blurred frozen landscapeHorizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, and the last world played and the faint wordmark, over a veiled snowy landscape
The Singleplayer page: three worlds with their dates and game modes, and Create world and Play buttons