Merge main while preserving fluid phases and baked arrow rendering
This commit is contained in:
@@ -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]
|
||||
@@ -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
|
||||
|
||||
+157
-37
@@ -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 <branch> # 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/
|
||||
|
||||
@@ -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
|
||||
+206
-40
@@ -1,57 +1,223 @@
|
||||
name: release builds
|
||||
# Started by hand: gh workflow run release.yml --ref <branch>
|
||||
# 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 <branch> # 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/
|
||||
|
||||
@@ -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.
|
||||
|
||||
Generated
+45
@@ -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"
|
||||
|
||||
@@ -47,8 +47,8 @@ Horizon is downloaded only through **the Horizon launcher**: get it from [playho
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/launcher-play.webp" alt="The launcher's Play page: v2026.10.13.1 ready to play, its summary, Client and Server, the Play button and prepared resources"></td>
|
||||
<td width="50%"><img src="docs/media/launcher-patch-notes.webp" alt="The launcher's Patch notes page, showing the notes of Horizon 2026.10.13.1"></td>
|
||||
<td width="50%"><img src="docs/media/launcher-play.webp" alt="The 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 list"></td>
|
||||
<td width="50%"><img src="docs/media/launcher-patch-notes.webp" alt="The launcher's Patch notes page, showing the notes of Horizon 2026.10.14.1"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -62,7 +62,7 @@ Captured in the Rust client itself, with vanilla assets and no mods or shaders.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td colspan="2"><img src="docs/media/menu-title.webp" alt="Horizon's title screen: a sidebar, the Horizon title, Singleplayer and Multiplayer buttons and the last world played, over a blurred frozen landscape"></td>
|
||||
<td colspan="2"><img src="docs/media/menu-title.webp" alt="Horizon'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"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/menu-worlds.webp" alt="The Singleplayer page: three worlds with their dates and game modes, and Create world and Play buttons"></td>
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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})
|
||||
}
|
||||
|
||||
@@ -93,8 +93,9 @@ fn encode(draws: &[GuiDraw]) -> Vec<Value> {
|
||||
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<GuiDraw> {
|
||||
// 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);
|
||||
|
||||
@@ -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<String> = 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::<horizon_client::Result<Vec<u32>>>()?;
|
||||
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(())
|
||||
}
|
||||
@@ -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(),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -64,6 +64,8 @@ pub struct Assets {
|
||||
pub animations: Vec<crate::sprites::SpriteAnimation>,
|
||||
pub sprite_layers: std::collections::BTreeMap<String, u32>,
|
||||
pub translucent_layers: Vec<bool>,
|
||||
/// Each layer's `MipmapGenerator` settings.
|
||||
pub sprite_mips: Vec<crate::mipmap::Settings>,
|
||||
/// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors).
|
||||
pub blocks_fluid_flow: BTreeSet<String>,
|
||||
}
|
||||
@@ -248,6 +250,7 @@ impl Assets {
|
||||
animations: sprites.animations,
|
||||
sprite_layers: sprites.layers,
|
||||
translucent_layers: sprites.translucent,
|
||||
sprite_mips: sprites.mips,
|
||||
blocks_fluid_flow,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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<f32>, linear: Option<f32>, at: [f32; 3], looping: bool) -> Channel {
|
||||
Channel {
|
||||
samples: Some((Arc::new(samples), 48_000)),
|
||||
|
||||
@@ -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<ClickEvent> {
|
||||
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<String> {
|
||||
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) {
|
||||
|
||||
@@ -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())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<Aabb>,
|
||||
) -> (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 {
|
||||
|
||||
@@ -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<String, Arc<MobType>>, 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<ExperienceOrb> {
|
||||
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<Tag>,
|
||||
raw: Option<&Tag>,
|
||||
) -> Option<Tag> {
|
||||
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<Arrow> {
|
||||
/// 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<Tag>)> {
|
||||
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.
|
||||
|
||||
@@ -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::<u8>() {
|
||||
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<f32> = 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<f64>,
|
||||
}
|
||||
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<Result<Item, &'static str>> {
|
||||
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<T: Copy + PartialEq>(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<crate::graphics_style::Cost> {
|
||||
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<bool> {
|
||||
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<u8> = 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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<f32>,
|
||||
/// `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,
|
||||
|
||||
+135
-114
@@ -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<u32>,
|
||||
) -> 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,
|
||||
|
||||
+119
-117
@@ -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<horizon_client::world_spawn::PlayerSpawnFinder>,
|
||||
mobs: Vec<Mob>,
|
||||
arrows: Vec<Arrow>,
|
||||
creatures: creatures::Creatures,
|
||||
sculk: sculk::SculkState,
|
||||
raiding: raids::Raiding,
|
||||
@@ -832,6 +834,8 @@ struct Game<'a> {
|
||||
armor_stand_assets: armor_stands::ArmorStandAssets,
|
||||
boats: Vec<boats::Boat>,
|
||||
boat_models: boats::BoatModels,
|
||||
/// EndCrystalModel's baked layer.
|
||||
crystal_model: Option<horizon_client::mobs::Part>,
|
||||
carts: Vec<minecarts::Minecart>,
|
||||
/// 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<String>)>,
|
||||
/// 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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<String>,
|
||||
/// File name of an F2 screenshot waiting for its frame.
|
||||
pub screenshot_message: Option<String>,
|
||||
/// Path of an F2 screenshot waiting for its frame.
|
||||
pub screenshot_message: Option<std::path::PathBuf>,
|
||||
/// 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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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('#') {
|
||||
|
||||
@@ -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)?
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)?;
|
||||
}
|
||||
|
||||
@@ -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<Vertex>,
|
||||
) {
|
||||
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<MobEvent>) -> 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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<f32> {
|
||||
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<f32> = 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();
|
||||
|
||||
@@ -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<Vertex>) {
|
||||
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<Vertex>) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Dim>,
|
||||
/// 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<KeyCode> {
|
||||
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<Retry> {
|
||||
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<Retry>) {
|
||||
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<View> {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<bool> {
|
||||
let nearest = |hits: &[Option<f64>]| 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()
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<Vertex>,
|
||||
) {
|
||||
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..] {
|
||||
|
||||
@@ -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(),
|
||||
});
|
||||
|
||||
@@ -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<Event>) -> 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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<String>) -> 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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<crate::mipmap::Settings>,
|
||||
/// 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<wgpu::PresentMode>,
|
||||
}
|
||||
fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec<u8>, 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<u8>, 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);
|
||||
|
||||
@@ -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<Action> {
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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/<sha1>`), 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<u8>)> {
|
||||
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<crate::font::Patch>,
|
||||
/// Vertex ranges drawn with `RenderPipelines.CROSSHAIR`'s
|
||||
/// `BlendFunction.INVERT` instead of alpha blending.
|
||||
pub invert: Vec<std::ops::Range<u32>>,
|
||||
}
|
||||
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<u32>, 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<wgpu::Texture>,
|
||||
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::<HudVertex>() 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::<HudVertex>() 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!(
|
||||
|
||||
@@ -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<GuiDraw> {
|
||||
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>) -> 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<f32>, full: bool) -> Vec<GuiDraw> {
|
||||
crosshair_draws(w, h, attack, full)
|
||||
.into_iter()
|
||||
.map(crosshair_blend)
|
||||
.collect()
|
||||
}
|
||||
fn crosshair_draws(w: i32, h: i32, attack: Option<f32>, full: bool) -> Vec<GuiDraw> {
|
||||
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,
|
||||
|
||||
@@ -160,6 +160,7 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec<GuiDraw> {
|
||||
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<GuiDraw> {
|
||||
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<GuiDra
|
||||
h: 5,
|
||||
region: Some([182, 5, 0, 0]),
|
||||
color: crate::hud_layout::WHITE,
|
||||
blend: crate::hud_layout::Blend::Textured,
|
||||
};
|
||||
out.push(sprite(BOSS_COLORS[bar.color].to_owned()));
|
||||
if bar.overlay != 0 {
|
||||
@@ -517,6 +520,7 @@ pub fn jump_bar(w: i32, h: i32, cooldown: i32, scale: f32) -> Vec<GuiDraw> {
|
||||
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 {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<u8>,
|
||||
/// 0 none, 1 water, 2 lava; | 4 for air; | 8 when sturdy on top.
|
||||
flags: Vec<u8>,
|
||||
}
|
||||
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<i16>, 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<Palette>,
|
||||
composed: Option<View>,
|
||||
/// Tiles changed since the image was composed.
|
||||
changed: bool,
|
||||
/// The composed image, `SIZE` x `SIZE` RGBA.
|
||||
pub image: Vec<u8>,
|
||||
}
|
||||
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<Item = (i32, i32)> {
|
||||
(-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<Chunk>) -> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Self> {
|
||||
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::<u32>() / 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<Image> {
|
||||
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
|
||||
}
|
||||
@@ -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<PlayerView>,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<super::MobEvent>) {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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<MobEvent>) {
|
||||
if !m.alive() {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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<bool> {
|
||||
Ok(self.resources.fluids.sturdy(s, d))
|
||||
|
||||
@@ -47,6 +47,8 @@ pub enum Screen {
|
||||
},
|
||||
Disconnected {
|
||||
reason: String,
|
||||
/// Auto-reconnect's next attempt, until it is cancelled.
|
||||
retry: Option<crate::reconnect::Retry>,
|
||||
},
|
||||
}
|
||||
/// 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<crate::reconnect::Retry> {
|
||||
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 {
|
||||
|
||||
@@ -40,7 +40,13 @@ pub enum Event {
|
||||
DecodeError(String),
|
||||
/// The server sent us back to configuration and finished it again.
|
||||
Reconfigured(Arc<Dynamic>),
|
||||
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<Option<ConnWriter>>,
|
||||
shared_counters: &Mutex<Option<Arc<Counters>>>,
|
||||
) -> Result<String, String> {
|
||||
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::<serde_json::Value>(&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"));
|
||||
|
||||
@@ -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<String> =
|
||||
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<Event> {
|
||||
@@ -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);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Event> {
|
||||
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<Event> {
|
||||
// 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<LanguageInfo> {
|
||||
(0..30)
|
||||
.map(|i| LanguageInfo {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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] {
|
||||
|
||||
@@ -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<Box<crate::arrows::ArrowState>>,
|
||||
}
|
||||
/// 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<Who>) -> 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);
|
||||
|
||||
@@ -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<String>,
|
||||
/// The player name the connection used.
|
||||
name: String,
|
||||
/// Attempts already made since the last stable connection.
|
||||
attempts: usize,
|
||||
joined: Option<Instant>,
|
||||
}
|
||||
/// 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<Retry> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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")],
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -48,6 +48,8 @@ pub struct Sprites {
|
||||
pub animations: Vec<SpriteAnimation>,
|
||||
pub opaque: Vec<bool>,
|
||||
pub translucent: Vec<bool>,
|
||||
/// Each layer's `MipmapGenerator` settings.
|
||||
pub mips: Vec<crate::mipmap::Settings>,
|
||||
/// Each layer's frames at the texture's own resolution (square), and the
|
||||
/// frame shown first.
|
||||
native: Vec<(u32, Arc<Vec<Vec<u8>>>, 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::<serde_json::Value>(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(
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,16 @@ pub fn named_color(name: &str) -> Option<u32> {
|
||||
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<bool>,
|
||||
pub strikethrough: Option<bool>,
|
||||
pub obfuscated: Option<bool>,
|
||||
/// ClickEvent.SuggestCommand: clicking puts this into the chat box.
|
||||
pub suggest: Option<String>,
|
||||
pub click: Option<ClickEvent>,
|
||||
/// Hover text.
|
||||
pub hover: Option<Box<Text>>,
|
||||
}
|
||||
@@ -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<String>, color: u32) -> Self {
|
||||
Self::styled(s, Style::color(color))
|
||||
}
|
||||
/// ComponentUtils.copyOnClickText: a green, bracketed clipboard link.
|
||||
pub fn copyable(s: impl Into<String>) -> 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<i32>, 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)];
|
||||
|
||||
+915
-110
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,535 @@
|
||||
use super::*;
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::{
|
||||
fs,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
title: Title,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"horizon-world-menu-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(root.join("saves")).unwrap();
|
||||
Self {
|
||||
title: Title::new(root.join("saves")),
|
||||
root,
|
||||
}
|
||||
}
|
||||
fn world(&self, folder: &str, name: &str) {
|
||||
crate::save::write_dat(
|
||||
&self.title.saves.join(folder).join("level.dat"),
|
||||
Tag::compound([
|
||||
(
|
||||
"Data",
|
||||
Tag::compound([
|
||||
("LevelName", Tag::String(name.into())),
|
||||
("GameType", Tag::Int(1)),
|
||||
("allowCommands", Tag::Byte(1)),
|
||||
(
|
||||
"WorldGenSettings",
|
||||
Tag::compound([("seed", Tag::Long(123456))]),
|
||||
),
|
||||
(
|
||||
"Version",
|
||||
Tag::compound([("Name", Tag::String("26.3".into()))]),
|
||||
),
|
||||
("UnmodeledData", Tag::Long(987654321)),
|
||||
]),
|
||||
),
|
||||
("OtherRootData", Tag::String("preserve me".into())),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
fn click(&mut self, label: &str) -> Action {
|
||||
self.click_with_sound(label).0
|
||||
}
|
||||
fn click_with_sound(&mut self, label: &str) -> (Action, bool) {
|
||||
let button = self
|
||||
.title
|
||||
.buttons(480.0, 262.0)
|
||||
.into_iter()
|
||||
.find(|b| b.label == label)
|
||||
.unwrap();
|
||||
self.title
|
||||
.click(button.x + button.w / 2.0, button.y + 10.0, (480.0, 262.0))
|
||||
}
|
||||
fn select(&mut self) {
|
||||
self.title.enter_singleplayer();
|
||||
self.title.click(240.0, 60.0, (480.0, 262.0));
|
||||
}
|
||||
fn finish_backup(&mut self) {
|
||||
self.title.backup_shown.set(true);
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while matches!(self.title.mode, Mode::Backup { .. }) {
|
||||
assert!(std::time::Instant::now() < deadline);
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
self.title.poll_backup();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_singleplayer_opens_creation_and_cancel_returns_to_title() {
|
||||
let mut f = Fixture::new();
|
||||
f.click("Singleplayer");
|
||||
assert!(matches!(f.title.mode, Mode::Create { .. }));
|
||||
f.click("Cancel");
|
||||
assert!(matches!(f.title.mode, Mode::Main));
|
||||
f.click("Singleplayer");
|
||||
f.title.escape();
|
||||
assert!(matches!(f.title.mode, Mode::Main));
|
||||
// Filtering an existing list down to zero results must not create a world.
|
||||
f.world("One", "One");
|
||||
f.title.enter_singleplayer();
|
||||
f.title.type_text("no match");
|
||||
assert!(matches!(f.title.mode, Mode::Select { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selector_controls_require_selection_and_search_uses_filtered_indices() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("A", "Alpha");
|
||||
f.world("B", "Beta");
|
||||
f.title.enter_singleplayer();
|
||||
let Mode::Select { worlds, .. } = &mut f.title.mode else {
|
||||
panic!("existing worlds should open the selector");
|
||||
};
|
||||
// Beta must have a different index in the full list and filtered list.
|
||||
// Filesystem timestamp precision must not decide which world comes first.
|
||||
worlds.sort_by(|a, b| a.folder.cmp(&b.folder));
|
||||
for label in ["Play Selected World", "Edit", "Delete", "Re-Create"] {
|
||||
assert!(
|
||||
!f.title
|
||||
.buttons(480.0, 262.0)
|
||||
.iter()
|
||||
.find(|b| b.label == label)
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
assert_eq!(f.click(label), Action::None);
|
||||
}
|
||||
// Clicking the disabled footer controls leaves the search box unfocused.
|
||||
f.title.click(240.0, 31.0, (480.0, 262.0));
|
||||
f.title.type_text("bEtA");
|
||||
assert_eq!(f.title.search, "bEtA");
|
||||
f.title.click(240.0, 60.0, (480.0, 262.0));
|
||||
f.click("Edit");
|
||||
assert!(matches!(&f.title.mode, Mode::Edit { world, .. } if world.folder == "B"));
|
||||
f.title.escape();
|
||||
assert!(
|
||||
matches!(&f.title.mode, Mode::Select { worlds, selected: Some(i) } if worlds[*i].folder == "B")
|
||||
);
|
||||
f.title.search_focused = true;
|
||||
f.title.backspace();
|
||||
assert!(matches!(f.title.mode, Mode::Select { selected: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_layout_disables_unsupported_optimization_and_missing_icon() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "New World");
|
||||
f.select();
|
||||
f.click("Edit");
|
||||
let buttons = f.title.buttons(480.0, 262.0);
|
||||
let reset = buttons.iter().find(|b| b.label == "Reset Icon").unwrap();
|
||||
assert_eq!(
|
||||
(reset.x, reset.y, reset.w, reset.enabled),
|
||||
(140.0, 78.0, 200.0, false)
|
||||
);
|
||||
// A 1920x1046 client area has a fractional height at GUI scale 4;
|
||||
// vanilla rounds up to 262 GUI pixels before positioning the layout.
|
||||
assert_eq!(f.title.buttons(480.0, 261.5)[0].y, 78.0);
|
||||
assert!(
|
||||
!buttons
|
||||
.iter()
|
||||
.find(|b| b.label == "Optimize World")
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
f.click("Optimize World");
|
||||
assert!(matches!(f.title.mode, Mode::Edit { .. }));
|
||||
fs::write(f.title.saves.join("World/icon.png"), b"icon").unwrap();
|
||||
assert!(
|
||||
f.title
|
||||
.buttons(480.0, 262.0)
|
||||
.iter()
|
||||
.find(|b| b.label == "Reset Icon")
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
f.click("Reset Icon");
|
||||
assert!(!f.title.saves.join("World/icon.png").exists());
|
||||
assert!(
|
||||
!f.title
|
||||
.buttons(480.0, 262.0)
|
||||
.iter()
|
||||
.find(|b| b.label == "Reset Icon")
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
f.title.click(240.0, 60.0, (480.0, 262.0));
|
||||
for _ in 0..32 {
|
||||
f.title.backspace();
|
||||
}
|
||||
assert!(
|
||||
!f.title
|
||||
.buttons(480.0, 262.0)
|
||||
.iter()
|
||||
.find(|b| b.label == "Save")
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_preserves_unknown_metadata_and_cancel_discards_edits() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "Original");
|
||||
let path = f.title.saves.join("World/level.dat");
|
||||
let original = crate::save::read_dat(&path).unwrap();
|
||||
f.select();
|
||||
f.click("Edit");
|
||||
f.title.type_text(" discarded");
|
||||
f.click("Cancel");
|
||||
assert_eq!(crate::save::read_dat(&path).unwrap(), original);
|
||||
f.click("Edit");
|
||||
for _ in 0..32 {
|
||||
f.title.backspace();
|
||||
}
|
||||
f.title.type_text(" Renamed 世界 ");
|
||||
f.click("Save");
|
||||
let mut expected = original;
|
||||
let Some(Tag::Compound(data)) = expected.get_mut("Data") else {
|
||||
panic!()
|
||||
};
|
||||
data.insert("LevelName".into(), Tag::String("Renamed 世界".into()));
|
||||
assert_eq!(crate::save::read_dat(&path).unwrap(), expected);
|
||||
assert!(path.with_file_name("level.dat_old").is_file());
|
||||
assert!(
|
||||
matches!(&f.title.mode, Mode::Select { worlds, selected: Some(i) } if worlds[*i].name == "Renamed 世界")
|
||||
);
|
||||
f.click("Edit");
|
||||
f.title.type_text(" via Enter");
|
||||
f.title.confirm_edit();
|
||||
assert_eq!(
|
||||
Level::read(&f.title.saves.join("World")).unwrap().name,
|
||||
"Renamed 世界 via Enter"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_requires_confirmation_and_both_cancel_paths_preserve_world() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
f.select();
|
||||
f.click("Delete");
|
||||
assert!(matches!(f.title.mode, Mode::Delete { .. }));
|
||||
assert!(f.title.saves.join("World/level.dat").is_file());
|
||||
f.click("Cancel");
|
||||
f.click("Delete");
|
||||
f.title.escape();
|
||||
assert!(f.title.saves.join("World/level.dat").is_file());
|
||||
f.click("Delete");
|
||||
let delete = f
|
||||
.title
|
||||
.buttons(480.0, 262.0)
|
||||
.into_iter()
|
||||
.find(|b| b.label == "Delete")
|
||||
.unwrap();
|
||||
assert_eq!((delete.x, delete.y, delete.w), (88.0, 146.0, 150.0));
|
||||
f.click("Delete");
|
||||
assert!(!f.title.saves.join("World").exists());
|
||||
assert!(matches!(&f.title.mode, Mode::Select { worlds, selected: None } if worlds.is_empty()));
|
||||
f.click("Back");
|
||||
f.click("Singleplayer");
|
||||
assert!(matches!(f.title.mode, Mode::Create { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_zip_preserves_nested_files_excludes_lock_and_keeps_duplicate_backups() {
|
||||
let f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
let world = f.title.saves.join("World");
|
||||
fs::create_dir_all(world.join("dimensions/minecraft/overworld/region")).unwrap();
|
||||
fs::write(world.join("session.lock"), b"locked").unwrap();
|
||||
fs::write(
|
||||
world.join("dimensions/minecraft/overworld/region/r.0.0.mca"),
|
||||
b"chunk bytes",
|
||||
)
|
||||
.unwrap();
|
||||
for _ in 0..2 {
|
||||
assert!(world_management::backup(&f.title.saves, "World").unwrap() > 0);
|
||||
}
|
||||
let archives: Vec<_> = fs::read_dir(f.root.join("backups"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().path())
|
||||
.collect();
|
||||
assert_eq!(archives.len(), 2);
|
||||
for archive in archives {
|
||||
let mut zip = zip::ZipArchive::new(fs::File::open(archive).unwrap()).unwrap();
|
||||
assert!(zip.by_name("World/session.lock").is_err());
|
||||
let mut bytes = Vec::new();
|
||||
std::io::Read::read_to_end(&mut zip.by_name("World/level.dat").unwrap(), &mut bytes)
|
||||
.unwrap();
|
||||
assert_eq!(bytes, fs::read(world.join("level.dat")).unwrap());
|
||||
bytes.clear();
|
||||
std::io::Read::read_to_end(
|
||||
&mut zip
|
||||
.by_name("World/dimensions/minecraft/overworld/region/r.0.0.mca")
|
||||
.unwrap(),
|
||||
&mut bytes,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(bytes, b"chunk bytes");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_screen_blocks_navigation_and_returns_to_the_selected_world() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
f.select();
|
||||
f.click("Edit");
|
||||
f.title.type_text(" unsaved");
|
||||
f.click("Make Backup");
|
||||
assert!(matches!(f.title.mode, Mode::Backup { .. }));
|
||||
assert!(f.title.buttons(480.0, 262.0).is_empty());
|
||||
f.title.escape();
|
||||
assert!(matches!(f.title.mode, Mode::Backup { .. }));
|
||||
// The first frame must be shown even when the backup finishes immediately.
|
||||
f.title.poll_backup();
|
||||
assert!(matches!(f.title.mode, Mode::Backup { .. }));
|
||||
f.finish_backup();
|
||||
assert!(
|
||||
matches!(&f.title.mode, Mode::Select { worlds, selected: Some(i) } if worlds[*i].folder == "World")
|
||||
);
|
||||
assert!(
|
||||
matches!(&f.title.toast, Some((_, BackupToast::Created { folder, bytes })) if folder == "World" && *bytes > 0)
|
||||
);
|
||||
assert_eq!(
|
||||
Level::read(&f.title.saves.join("World")).unwrap().name,
|
||||
"World"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_backup_returns_to_the_selected_world_with_an_error_toast() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
f.select();
|
||||
f.click("Edit");
|
||||
f.title.type_text(" unsaved");
|
||||
// A file at the backup-directory path makes the real worker fail reliably.
|
||||
fs::write(f.root.join("backups"), b"not a directory").unwrap();
|
||||
f.click("Make Backup");
|
||||
f.finish_backup();
|
||||
assert!(
|
||||
matches!(&f.title.mode, Mode::Select { worlds, selected: Some(i) } if worlds[*i].folder == "World")
|
||||
);
|
||||
let Some((_, BackupToast::Failed(error))) = &f.title.toast else {
|
||||
panic!("backup failures should produce an error toast");
|
||||
};
|
||||
assert!(!error.is_empty());
|
||||
assert_eq!(
|
||||
Level::read(&f.title.saves.join("World")).unwrap().name,
|
||||
"World"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(f.root.join("backups")).unwrap(),
|
||||
b"not a directory"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_backup_worker_returns_to_the_list_with_an_error_toast() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
let world = list_worlds(&f.title.saves).remove(0);
|
||||
let (send, receive) = mpsc::channel();
|
||||
f.title.mode = Mode::Backup { world };
|
||||
f.title.backup = Some(receive);
|
||||
f.title.backup_shown.set(true);
|
||||
drop(send);
|
||||
f.title.poll_backup();
|
||||
assert!(
|
||||
matches!(&f.title.mode, Mode::Select { worlds, selected: Some(i) } if worlds[*i].folder == "World")
|
||||
);
|
||||
assert!(
|
||||
matches!(&f.title.toast, Some((_, BackupToast::Failed(error))) if error == "Backup worker stopped")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_operations_show_error_and_leave_world_intact() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
f.select();
|
||||
f.click("Edit");
|
||||
fs::remove_file(f.title.saves.join("World/level.dat")).unwrap();
|
||||
f.click("Save");
|
||||
assert!(matches!(f.title.mode, Mode::Error { .. }));
|
||||
f.click("Back");
|
||||
assert!(matches!(f.title.mode, Mode::Edit { .. }));
|
||||
assert!(f.title.saves.join("World").is_dir());
|
||||
for bad in ["../World", "..", ".", "/World"] {
|
||||
assert!(world_management::delete(&f.title.saves, bad).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn backup_rejects_symlinks_and_removes_incomplete_archive() {
|
||||
let f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
std::os::unix::fs::symlink(f.root.join("outside"), f.title.saves.join("World/link")).unwrap();
|
||||
assert!(world_management::backup(&f.title.saves, "World").is_err());
|
||||
assert_eq!(fs::read_dir(f.root.join("backups")).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recreate_uses_existing_name_seed_and_mode_and_scroll_reaches_later_rows() {
|
||||
let mut f = Fixture::new();
|
||||
for i in 0..10 {
|
||||
f.world(&format!("World{i}"), &format!("World {i}"));
|
||||
}
|
||||
f.select();
|
||||
f.click("Re-Create");
|
||||
assert!(
|
||||
matches!(&f.title.mode,Mode::Create { name,seed,creative:true,.. } if name.starts_with("World ") && seed == "123456")
|
||||
);
|
||||
f.click("Cancel");
|
||||
f.title
|
||||
.scroll_worlds(-100.0, (240.0, 100.0), (480.0, 262.0));
|
||||
assert!(f.title.scroll.get() > 0.0);
|
||||
let Mode::Select { worlds, .. } = &f.title.mode else {
|
||||
panic!()
|
||||
};
|
||||
let last = worlds.last().unwrap().folder.clone();
|
||||
f.title.click(240.0, 180.0, (480.0, 262.0));
|
||||
assert!(
|
||||
matches!(&f.title.mode,Mode::Select { worlds,selected:Some(i) } if worlds[*i].folder == last)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_navigation_buttons_sound_even_without_a_game_action() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
assert_eq!(
|
||||
f.title.click(0.0, 0.0, (480.0, 262.0)),
|
||||
(Action::None, false)
|
||||
);
|
||||
assert_eq!(
|
||||
f.click_with_sound("Minecraft Realms"),
|
||||
(Action::None, false)
|
||||
);
|
||||
assert_eq!(f.click_with_sound("Singleplayer"), (Action::None, true));
|
||||
assert_eq!(
|
||||
f.click_with_sound("Play Selected World"),
|
||||
(Action::None, false)
|
||||
);
|
||||
assert_eq!(f.click_with_sound("Create New World"), (Action::None, true));
|
||||
assert_eq!(
|
||||
f.title.click(240.0, 55.0, (480.0, 262.0)),
|
||||
(Action::None, false)
|
||||
);
|
||||
assert_eq!(
|
||||
f.click_with_sound("Game Mode: Survival"),
|
||||
(Action::None, true)
|
||||
);
|
||||
assert_eq!(f.click_with_sound("Cancel"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Back"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Options..."), (Action::Options, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_world_selection_is_silent_until_the_entry_launches() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
f.title.enter_singleplayer();
|
||||
assert_eq!(
|
||||
f.title.click(240.0, 60.0, (480.0, 262.0)),
|
||||
(Action::None, false)
|
||||
);
|
||||
assert_eq!(
|
||||
f.title.click(240.0, 60.0, (480.0, 262.0)),
|
||||
(
|
||||
Action::Play {
|
||||
folder: "World".into()
|
||||
},
|
||||
true
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_management_buttons_sound_when_enabled() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
f.select();
|
||||
assert_eq!(f.click_with_sound("Edit"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Reset Icon"), (Action::None, false));
|
||||
assert_eq!(f.click_with_sound("Optimize World"), (Action::None, false));
|
||||
fs::write(f.title.saves.join("World/icon.png"), b"icon").unwrap();
|
||||
assert_eq!(f.click_with_sound("Reset Icon"), (Action::None, true));
|
||||
let Mode::Edit { name, .. } = &mut f.title.mode else {
|
||||
panic!("edit screen")
|
||||
};
|
||||
name.clear();
|
||||
assert_eq!(f.click_with_sound("Save"), (Action::None, false));
|
||||
let Mode::Edit { name, .. } = &mut f.title.mode else {
|
||||
panic!("edit screen")
|
||||
};
|
||||
*name = "Renamed".into();
|
||||
assert_eq!(f.click_with_sound("Save"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Edit"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Cancel"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Delete"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Cancel"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Delete"), (Action::None, true));
|
||||
assert_eq!(f.click_with_sound("Delete"), (Action::None, true));
|
||||
assert!(matches!(f.title.mode, Mode::Select { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_button_sounds_and_the_progress_screen_is_silent() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
f.select();
|
||||
f.click("Edit");
|
||||
assert_eq!(f.click_with_sound("Make Backup"), (Action::None, true));
|
||||
assert_eq!(
|
||||
f.title.click(240.0, 120.0, (480.0, 262.0)),
|
||||
(Action::None, false)
|
||||
);
|
||||
assert!(matches!(f.title.mode, Mode::Backup { .. }));
|
||||
f.finish_backup();
|
||||
assert!(matches!(f.title.mode, Mode::Select { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_world_operation_back_button_plays_the_click_sound() {
|
||||
let mut f = Fixture::new();
|
||||
f.world("World", "World");
|
||||
f.select();
|
||||
f.click("Edit");
|
||||
fs::remove_file(f.title.saves.join("World/level.dat")).unwrap();
|
||||
assert_eq!(f.click_with_sound("Save"), (Action::None, true));
|
||||
assert!(matches!(f.title.mode, Mode::Error { .. }));
|
||||
assert_eq!(f.click_with_sound("Back"), (Action::None, true));
|
||||
assert!(matches!(f.title.mode, Mode::Edit { .. }));
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! World-list operations. Metadata edits preserve every other NBT field;
|
||||
//! backups use vanilla's ZIP layout and never include the session lock.
|
||||
use crate::save::{read_dat, write_dat};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::{
|
||||
fs, io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
fn world_path(saves: &Path, folder: &str) -> crate::Result<PathBuf> {
|
||||
if Path::new(folder).components().count() != 1
|
||||
|| !matches!(
|
||||
Path::new(folder).components().next(),
|
||||
Some(std::path::Component::Normal(_))
|
||||
)
|
||||
{
|
||||
return Err("Invalid world folder".into());
|
||||
}
|
||||
let path = saves.join(folder);
|
||||
if !fs::symlink_metadata(&path)?.is_dir() {
|
||||
return Err("World folder is not a directory".into());
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub(super) fn rename(saves: &Path, folder: &str, name: &str) -> crate::Result<()> {
|
||||
let path = world_path(saves, folder)?.join("level.dat");
|
||||
let mut root = read_dat(&path).ok_or("Could not read level.dat")?;
|
||||
let Some(Tag::Compound(data)) = root.get_mut("Data") else {
|
||||
return Err("Missing level data".into());
|
||||
};
|
||||
data.insert("LevelName".into(), Tag::String(name.trim().into()));
|
||||
write_dat(&path, root)
|
||||
}
|
||||
|
||||
pub(super) fn reset_icon(saves: &Path, folder: &str) -> crate::Result<()> {
|
||||
fs::remove_file(world_path(saves, folder)?.join("icon.png"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn delete(saves: &Path, folder: &str) -> crate::Result<()> {
|
||||
fs::remove_dir_all(world_path(saves, folder)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn backups_path(saves: &Path) -> PathBuf {
|
||||
saves.parent().unwrap_or(saves).join("backups")
|
||||
}
|
||||
|
||||
pub(super) fn open_folder(path: &Path) -> crate::Result<()> {
|
||||
fs::create_dir_all(path)?;
|
||||
let path = fs::canonicalize(path)?;
|
||||
let program = if cfg!(target_os = "windows") {
|
||||
"explorer"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
// Reap the desktop opener without blocking the UI thread.
|
||||
let mut child = std::process::Command::new(program)
|
||||
.arg(path)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()?;
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn backup(saves: &Path, folder: &str) -> crate::Result<u64> {
|
||||
let world = world_path(saves, folder)?;
|
||||
let backups = backups_path(saves);
|
||||
fs::create_dir_all(&backups)?;
|
||||
let base = format!(
|
||||
"{}_{}",
|
||||
chrono::Local::now().format("%Y-%m-%d_%H-%M-%S"),
|
||||
folder
|
||||
);
|
||||
let mut index = 0;
|
||||
let (path, file) = loop {
|
||||
let name = if index == 0 {
|
||||
format!("{base}.zip")
|
||||
} else {
|
||||
format!("{base} ({index}).zip")
|
||||
};
|
||||
let path = backups.join(name);
|
||||
match fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&path)
|
||||
{
|
||||
Ok(file) => break (path, file),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => index += 1,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
};
|
||||
let result = (|| {
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
write_tree(&mut zip, &world, &world, folder)?;
|
||||
Ok(zip.finish()?.metadata()?.len())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn write_tree(
|
||||
zip: &mut zip::ZipWriter<fs::File>,
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
folder: &str,
|
||||
) -> crate::Result<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let kind = entry.file_type()?;
|
||||
if kind.is_symlink() {
|
||||
return Err(format!("Cannot back up symbolic link: {}", path.display()).into());
|
||||
}
|
||||
if kind.is_dir() {
|
||||
write_tree(zip, root, &path, folder)?;
|
||||
} else if kind.is_file() && entry.file_name() != "session.lock" {
|
||||
let relative = path.strip_prefix(root)?;
|
||||
let name = format!("{folder}/{}", relative.to_string_lossy().replace('\\', "/"));
|
||||
zip.start_file(
|
||||
name,
|
||||
zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated),
|
||||
)?;
|
||||
io::copy(&mut fs::File::open(path)?, zip)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,11 +5,13 @@
|
||||
//!
|
||||
//! It is the launcher's look, from the same tokens: `crates/horizon-theme`
|
||||
//! holds the palette, type scale, spacing, radii, control sizes, motion and
|
||||
//! the bundled fonts, and `launcher/src/theme.rs` reads the same values, so
|
||||
//! changing one changes both. The components below port the launcher's
|
||||
//! (`launcher/src/main.rs`): button with hover layer and press state, sidebar
|
||||
//! list with the sliding selection, segmented control, switch, settings rows,
|
||||
//! page header, and its `ease_out_quint` tweens over `QUICK` and `MOVE`.
|
||||
//! the bundled fonts (`docs/design-system.md` describes them), and
|
||||
//! `launcher/src/theme.rs` reads the same values, so changing one changes
|
||||
//! both. The components below port the launcher's (`launcher/src/main.rs`):
|
||||
//! pill buttons with a hover layer and press state, the sidebar of text items
|
||||
//! with the sliding selection, the segmented control with its ink pill, the
|
||||
//! switch, numbered settings rows with one-pixel rules, the page header, and
|
||||
//! tweens over `QUICK` and `MOVE`.
|
||||
//!
|
||||
//! How to use it from a screen (or to add options, e.g. the Simple/Advanced
|
||||
//! graphics settings): build a [`Ui`] over the frame's `HudBatch` with
|
||||
@@ -72,25 +74,35 @@ pub fn save_preferences(dir: &Path) {
|
||||
let _ = std::fs::write(dir.join("horizon.txt"), format!("menuStyle:{value}\n"));
|
||||
}
|
||||
|
||||
/// The launcher's dark palette (`horizon_theme::DARK`) in the HUD's colour
|
||||
/// encoding, plus the translucent surfaces the menus put over the backdrop.
|
||||
/// The dark palette (`horizon_theme::DARK`) in the HUD's colour encoding, plus the
|
||||
/// translucent surfaces the menus put over the backdrop.
|
||||
pub mod color {
|
||||
use crate::hud::rgba;
|
||||
use horizon_theme::DARK as P;
|
||||
pub const fn hex(c: u32, a: u8) -> u32 {
|
||||
(a as u32) << 24 | (c & 0xff) << 16 | (c >> 8 & 0xff) << 8 | (c >> 16 & 0xff)
|
||||
}
|
||||
pub const BG: u32 = hex(P.bg, 255);
|
||||
pub const SIDEBAR: u32 = hex(P.sidebar, 255);
|
||||
pub const RAISED: u32 = hex(P.raised, 255);
|
||||
pub const HOVER: u32 = hex(P.hover, 255);
|
||||
pub const BORDER: u32 = hex(P.border, 255);
|
||||
pub const TEXT: u32 = hex(P.text, 255);
|
||||
pub const MUTED: u32 = hex(P.muted, 255);
|
||||
pub const FAINT: u32 = hex(P.faint, 255);
|
||||
/// The page, under every veil.
|
||||
pub const BG: u32 = hex(P.page, 255);
|
||||
/// Hover plates, secondary buttons, fields, the segmented track: the
|
||||
/// dark palette's soft plate, as ink over the veil so the plates read the
|
||||
/// same over any backdrop (over the page colour they are `plate_soft`).
|
||||
pub const RAISED: u32 = hex(P.ink, 20);
|
||||
/// Pressed plates and a switch that is off (`plate`, the same way).
|
||||
pub const HOVER: u32 = hex(P.ink, 36);
|
||||
/// One-pixel rules between rows, slider tracks.
|
||||
pub const BORDER: u32 = hex(P.rule, 255);
|
||||
/// Text and selection (`ink`).
|
||||
pub const TEXT: u32 = hex(P.ink, 255);
|
||||
/// Values and secondary text (`ink_soft`).
|
||||
pub const MUTED: u32 = hex(P.ink_soft, 255);
|
||||
/// Labels, indices, descriptions over the veiled backdrop
|
||||
/// (`horizon_theme::BACKDROP_MUTED`, which holds AA there).
|
||||
pub const FAINT: u32 = hex(horizon_theme::BACKDROP_MUTED, 255);
|
||||
pub const ACCENT: u32 = hex(P.accent, 255);
|
||||
pub const ON_ACCENT: u32 = hex(P.on_accent, 255);
|
||||
pub const DANGER: u32 = hex(P.danger, 255);
|
||||
pub const SUCCESS: u32 = hex(P.success, 255);
|
||||
pub const WHITE: u32 = hex(0xffffff, 255);
|
||||
pub fn with_alpha(c: u32, a: f32) -> u32 {
|
||||
let base = (c >> 24) as f32;
|
||||
@@ -106,16 +118,31 @@ pub mod color {
|
||||
}
|
||||
|
||||
/// The launcher's type scale and shapes (`horizon_theme`), in dp.
|
||||
pub use horizon_theme::{
|
||||
BODY, CONTROL, CONTROL_LARGE, HERO, LARGE, RADIUS, RADIUS_CARD, RADIUS_GROUP, RADIUS_SEGMENT,
|
||||
ROW_LABEL, SEGMENT, SIDEBAR, SMALL, TITLE, WORDMARK, ease_out_cubic, ease_out_quint,
|
||||
};
|
||||
pub use horizon_theme::{CONTROL, CONTROL_LARGE, SEGMENT, ease_out_cubic, ease_out_quint};
|
||||
/// The type scale in dp: indices (mono), captions, labels and buttons, body,
|
||||
/// the large button, section heads, list names, page titles, the opening.
|
||||
pub const MICRO: f32 = horizon_theme::MICRO.px;
|
||||
pub const SMALL: f32 = horizon_theme::CAPTION.px;
|
||||
pub const BODY: f32 = horizon_theme::LABEL.px;
|
||||
pub const LARGE: f32 = horizon_theme::UI.px;
|
||||
pub const HEADING: f32 = horizon_theme::HEADING.px;
|
||||
pub const TITLE: f32 = horizon_theme::TITLE.px;
|
||||
pub const HERO: f32 = horizon_theme::DISPLAY.px;
|
||||
pub const WORDMARK: f32 = 96.;
|
||||
/// Fields; plates (hover rows, selection); pills (buttons, segments).
|
||||
pub const RADIUS: f32 = horizon_theme::RADIUS;
|
||||
pub const RADIUS_PLATE: f32 = horizon_theme::RADIUS_PLATE;
|
||||
pub const PILL: f32 = horizon_theme::RADIUS_PILL;
|
||||
/// The index column of a numbered row, and the label column after it.
|
||||
pub const INDEX: f32 = horizon_theme::INDEX;
|
||||
pub const ROW_LABEL: f32 = 150.;
|
||||
pub const SIDEBAR: f32 = 200.;
|
||||
/// Motion durations in seconds (`horizon_theme::QUICK` and `MOVE`).
|
||||
pub fn quick() -> f32 {
|
||||
horizon_theme::QUICK.as_secs_f32()
|
||||
horizon_theme::QUICK.secs()
|
||||
}
|
||||
pub fn move_() -> f32 {
|
||||
horizon_theme::MOVE.as_secs_f32()
|
||||
horizon_theme::MOVE.secs()
|
||||
}
|
||||
/// How visible the live title backdrop is (0..1), set by the game each frame.
|
||||
static BACKDROP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
@@ -153,7 +180,7 @@ impl Fonts {
|
||||
let f = |b: &'static [u8]| FontRef::try_from_slice(b).expect("bundled font");
|
||||
Self {
|
||||
faces: [
|
||||
f(horizon_theme::fonts::INSTRUMENT_SERIF),
|
||||
f(horizon_theme::fonts::GEIST_MEDIUM),
|
||||
f(horizon_theme::fonts::GEIST_REGULAR),
|
||||
f(horizon_theme::fonts::GEIST_MEDIUM),
|
||||
f(horizon_theme::fonts::GEIST_SEMIBOLD),
|
||||
@@ -405,6 +432,12 @@ pub struct Ui<'a> {
|
||||
pub opacity: f32,
|
||||
/// Added to every x / y drawn (screen slides).
|
||||
pub offset: (f32, f32),
|
||||
/// The number the next settings row shows (`01`, `02`…); `page_header`
|
||||
/// starts it again.
|
||||
pub row_index: usize,
|
||||
/// Secondary text (indices, inactive items, captions): `FAINT`, or `MUTED` over the home
|
||||
/// page's lighter veil (`horizon_theme::HOME_VEIL`).
|
||||
pub muted: u32,
|
||||
}
|
||||
impl<'a> Ui<'a> {
|
||||
/// `cursor` is in GUI pixels, like every screen's input.
|
||||
@@ -434,6 +467,8 @@ impl<'a> Ui<'a> {
|
||||
real: true,
|
||||
opacity: 1.0,
|
||||
offset: (0.0, 0.0),
|
||||
row_index: 0,
|
||||
muted: color::FAINT,
|
||||
}
|
||||
}
|
||||
/// A layout pass for hit testing: nothing is drawn and no tween starts.
|
||||
@@ -832,17 +867,51 @@ impl<'a> Ui<'a> {
|
||||
}
|
||||
|
||||
// ---- the launcher's components ----
|
||||
/// The launcher's `page_header`: an Instrument Serif title and a muted line.
|
||||
/// Returns the height used.
|
||||
/// The launcher's `page_header`: a display title and a muted line.
|
||||
/// Returns the height used, and numbers the rows below from 01.
|
||||
pub fn page_header(&mut self, x: f32, y: f32, title: &str, description: &str) -> f32 {
|
||||
self.text_line(Face::Display, TITLE, 32.0, x, y, color::TEXT, title);
|
||||
self.text(Face::Regular, BODY, x, y + 38.0, color::MUTED, description);
|
||||
38.0 + (BODY * 1.45).round()
|
||||
self.row_index = 0;
|
||||
let line = (HERO * 1.1).round();
|
||||
self.text_line(Face::Display, HERO, line, x, y, color::TEXT, title);
|
||||
self.text(
|
||||
Face::Regular,
|
||||
LARGE,
|
||||
x,
|
||||
y + line + 10.0,
|
||||
color::FAINT,
|
||||
description,
|
||||
);
|
||||
line + 10.0 + (LARGE * 1.5).round()
|
||||
}
|
||||
/// The launcher's `button`: 30 tall (or `CONTROL_LARGE` with `LARGE`
|
||||
/// text), 6 radius, medium weight, a hover layer easing in over `QUICK`,
|
||||
/// and the press state (opacity 0.82 for primary, 0.8 otherwise).
|
||||
/// Returns the hover.
|
||||
/// Mono capitals: the status above a title, section labels, footnotes.
|
||||
pub fn caps(&mut self, x: f32, y: f32, color: u32, text: &str) -> f32 {
|
||||
self.text(Face::Mono, MICRO, x, y, color, &text.to_uppercase())
|
||||
}
|
||||
/// Horizon's mark at `size` dp: two stems, their reflection at a third,
|
||||
/// the horizon across in the accent.
|
||||
pub fn mark(&mut self, x: f32, y: f32, size: f32) {
|
||||
let u = size / 16.0;
|
||||
for sx in [4.0, 10.0] {
|
||||
self.fill(x + sx * u, y + 3.0 * u, 2.0 * u, 4.0 * u, color::TEXT);
|
||||
self.fill(
|
||||
x + sx * u,
|
||||
y + 8.0 * u,
|
||||
2.0 * u,
|
||||
4.0 * u,
|
||||
color::with_alpha(color::TEXT, 0.36),
|
||||
);
|
||||
}
|
||||
self.fill(x + u, y + 7.0 * u, 14.0 * u, u, color::ACCENT);
|
||||
}
|
||||
/// The sidebar's frame, shared by the title, options and pause screens:
|
||||
/// no panel, only the mark and a name at the top, as the launcher's bar.
|
||||
pub fn sidebar_frame(&mut self, title: &str) {
|
||||
self.mark(22.0, 26.0, 18.0);
|
||||
self.text_line(Face::Medium, BODY, 18.0, 48.0, 26.0, color::TEXT, title);
|
||||
}
|
||||
/// The launcher's `button`: a pill 32 tall (or `CONTROL_LARGE` with
|
||||
/// `LARGE` text), medium weight, a hover layer easing in over `QUICK`,
|
||||
/// and the press state. Returns the hover.
|
||||
pub fn button(
|
||||
&mut self,
|
||||
id: u64,
|
||||
@@ -862,37 +931,32 @@ impl<'a> Ui<'a> {
|
||||
if !enabled {
|
||||
self.opacity *= horizon_theme::DISABLED;
|
||||
} else if self.pressed(x, y, w, h) {
|
||||
self.opacity *= if kind == Kind::Primary {
|
||||
horizon_theme::PRESSED
|
||||
} else {
|
||||
horizon_theme::PRESSED_SOFT
|
||||
};
|
||||
self.opacity *= horizon_theme::PRESSED;
|
||||
}
|
||||
let fg = match kind {
|
||||
Kind::Primary => {
|
||||
self.rounded(x, y, w, h, RADIUS, color::ACCENT);
|
||||
self.rounded(x, y, w, h, PILL, color::ACCENT);
|
||||
self.rounded(
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
RADIUS,
|
||||
color::with_alpha(color::WHITE, horizon_theme::PRIMARY_HOVER * hover),
|
||||
PILL,
|
||||
color::with_alpha(color::WHITE, 0.12 * hover),
|
||||
);
|
||||
color::ON_ACCENT
|
||||
}
|
||||
Kind::Secondary => {
|
||||
self.rounded(x, y, w, h, RADIUS, color::RAISED);
|
||||
self.rounded(x, y, w, h, RADIUS, color::with_alpha(color::HOVER, hover));
|
||||
self.border(x, y, w, h, RADIUS, color::BORDER);
|
||||
self.rounded(x, y, w, h, PILL, color::RAISED);
|
||||
self.rounded(x, y, w, h, PILL, color::with_alpha(color::HOVER, hover));
|
||||
color::TEXT
|
||||
}
|
||||
Kind::Ghost => {
|
||||
self.rounded(x, y, w, h, RADIUS, color::with_alpha(color::HOVER, hover));
|
||||
color::mix(color::MUTED, color::TEXT, hover)
|
||||
self.rounded(x, y, w, h, PILL, color::with_alpha(color::RAISED, hover));
|
||||
color::mix(self.muted, color::TEXT, hover)
|
||||
}
|
||||
Kind::Danger => {
|
||||
self.rounded(x, y, w, h, RADIUS, color::with_alpha(color::HOVER, hover));
|
||||
self.rounded(x, y, w, h, PILL, color::with_alpha(color::RAISED, hover));
|
||||
color::DANGER
|
||||
}
|
||||
};
|
||||
@@ -911,14 +975,14 @@ impl<'a> Ui<'a> {
|
||||
self.opacity = saved;
|
||||
hover
|
||||
}
|
||||
/// The width the launcher's button gives a label (padding 12, or 24 large).
|
||||
/// The width the launcher's button gives a label (padding 16, or 24 large).
|
||||
pub fn button_width(&self, label: &str, large: bool) -> f32 {
|
||||
let (size, pad) = if large { (LARGE, 24.0) } else { (BODY, 12.0) };
|
||||
let (size, pad) = if large { (LARGE, 24.0) } else { (BODY, 16.0) };
|
||||
(self.measure(Face::Medium, size, label) + pad * 2.0).ceil()
|
||||
}
|
||||
/// The launcher's sidebar list: 30-tall items 2 apart, a raised pill with
|
||||
/// a 1px border that slides to the selected item over `MOVE`, and hover
|
||||
/// layers on the others. Items are ids `base + index`.
|
||||
/// The launcher's navigation as a sidebar: text items 32 tall and 2 apart,
|
||||
/// a soft pill that slides to the selected item over `MOVE`, hover layers
|
||||
/// on the others. Items are ids `base + index`.
|
||||
pub fn sidebar_list(
|
||||
&mut self,
|
||||
base: u64,
|
||||
@@ -928,11 +992,10 @@ impl<'a> Ui<'a> {
|
||||
labels: &[&str],
|
||||
selected: usize,
|
||||
) {
|
||||
const STEP: f32 = 32.0;
|
||||
const STEP: f32 = 34.0;
|
||||
let pill = self.tween(base ^ 0x9111, selected as f32, move_());
|
||||
let py = y + pill * STEP;
|
||||
self.rounded(x, py, w, CONTROL, RADIUS, color::RAISED);
|
||||
self.border(x, py, w, CONTROL, RADIUS, color::BORDER);
|
||||
self.rounded(x, py, w, CONTROL, PILL, color::RAISED);
|
||||
for (i, label) in labels.iter().enumerate() {
|
||||
let iy = y + i as f32 * STEP;
|
||||
let active = i == selected;
|
||||
@@ -943,22 +1006,22 @@ impl<'a> Ui<'a> {
|
||||
iy,
|
||||
w,
|
||||
CONTROL,
|
||||
RADIUS,
|
||||
color::with_alpha(color::HOVER, 0.7 * hover),
|
||||
PILL,
|
||||
color::with_alpha(color::RAISED, 0.8 * hover),
|
||||
);
|
||||
}
|
||||
let (face, fg) = if active {
|
||||
(Face::Medium, color::TEXT)
|
||||
} else {
|
||||
(Face::Regular, color::MUTED)
|
||||
(Face::Regular, color::mix(self.muted, color::TEXT, hover))
|
||||
};
|
||||
self.text_line(face, BODY, CONTROL, x + 10.0, iy, fg, label);
|
||||
self.text_line(face, BODY, CONTROL, x + 12.0, iy, fg, label);
|
||||
}
|
||||
}
|
||||
/// The launcher's segmented control: a raised frame (radius 7, padding 2,
|
||||
/// 1px border) holding 26-tall segments; the active one has the page
|
||||
/// background, a border and medium text. Segments are ids `base + index`.
|
||||
/// Returns the control's width.
|
||||
/// The launcher's segmented control: a soft pill track (padding 2)
|
||||
/// holding 28-tall segments; the selected one is an ink pill with
|
||||
/// page-coloured text. Segments are ids `base + index`. Returns the
|
||||
/// control's width.
|
||||
pub fn segmented(
|
||||
&mut self,
|
||||
base: u64,
|
||||
@@ -971,31 +1034,28 @@ impl<'a> Ui<'a> {
|
||||
.iter()
|
||||
.map(|l| (self.measure(Face::Medium, BODY, l) + 28.0).ceil())
|
||||
.collect();
|
||||
let total = widths.iter().sum::<f32>() + 2.0 * (labels.len() as f32 - 1.0) + 4.0 + 2.0;
|
||||
let h = SEGMENT + 6.0;
|
||||
self.rounded(x, y, total, h, RADIUS_GROUP, color::RAISED);
|
||||
self.border(x, y, total, h, RADIUS_GROUP, color::BORDER);
|
||||
let mut sx = x + 3.0;
|
||||
let total = widths.iter().sum::<f32>() + 2.0 * (labels.len() as f32 - 1.0) + 4.0;
|
||||
let h = SEGMENT + 4.0;
|
||||
self.rounded(x, y, total, h, PILL, color::RAISED);
|
||||
let mut sx = x + 2.0;
|
||||
for (i, (label, sw)) in labels.iter().zip(&widths).enumerate() {
|
||||
let active = i == selected;
|
||||
let hover = self.interact(base + i as u64, sx, y + 3.0, *sw, SEGMENT, true);
|
||||
let hover = self.interact(base + i as u64, sx, y + 2.0, *sw, SEGMENT, true);
|
||||
if active {
|
||||
self.rounded(sx, y + 3.0, *sw, SEGMENT, RADIUS_SEGMENT, color::BG);
|
||||
self.border(sx, y + 3.0, *sw, SEGMENT, RADIUS_SEGMENT, color::BORDER);
|
||||
self.rounded(sx, y + 2.0, *sw, SEGMENT, PILL, color::TEXT);
|
||||
}
|
||||
let fg = if active {
|
||||
color::TEXT
|
||||
color::BG
|
||||
} else {
|
||||
color::mix(color::MUTED, color::TEXT, hover)
|
||||
color::mix(self.muted, color::TEXT, hover)
|
||||
};
|
||||
let face = if active { Face::Medium } else { Face::Regular };
|
||||
let lw = self.measure(face, BODY, label);
|
||||
let lw = self.measure(Face::Medium, BODY, label);
|
||||
self.text_line(
|
||||
face,
|
||||
Face::Medium,
|
||||
BODY,
|
||||
SEGMENT,
|
||||
sx + ((sw - lw) / 2.0).round(),
|
||||
y + 3.0,
|
||||
y + 2.0,
|
||||
fg,
|
||||
label,
|
||||
);
|
||||
@@ -1003,45 +1063,55 @@ impl<'a> Ui<'a> {
|
||||
}
|
||||
total
|
||||
}
|
||||
/// The launcher's `switch`: 34x20, accent when on, border colour when off,
|
||||
/// a white 16px knob sliding over `QUICK`. Right-aligned at `right`.
|
||||
/// The launcher's `switch`: 36x20, accent when on, the plate colour when
|
||||
/// off, a white 16px knob sliding over `MOVE`. Right-aligned at `right`.
|
||||
pub fn switch(&mut self, id: u64, right: f32, cy: f32, on: bool) {
|
||||
let (w, h) = (34.0, 20.0);
|
||||
let (w, h) = (36.0, 20.0);
|
||||
let (x, y) = (right - w, (cy - h / 2.0).round());
|
||||
self.interact(id, x - 4.0, y - 4.0, w + 8.0, h + 8.0, true);
|
||||
let t = self.tween(id ^ 0x5717c4, if on { 1.0 } else { 0.0 }, quick());
|
||||
let t = self.tween(id ^ 0x5717c4, if on { 1.0 } else { 0.0 }, move_());
|
||||
self.rounded(
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
h / 2.0,
|
||||
color::mix(color::BORDER, color::ACCENT, t),
|
||||
color::mix(color::HOVER, color::ACCENT, t),
|
||||
);
|
||||
self.rounded(x + 2.0 + 14.0 * t, y + 2.0, 16.0, 16.0, 8.0, color::WHITE);
|
||||
self.rounded(x + 2.0 + 16.0 * t, y + 2.0, 16.0, 16.0, 8.0, color::WHITE);
|
||||
}
|
||||
/// The launcher's settings `row`: a 150-wide muted label column, then the
|
||||
/// The next row's number, in mono, in the index column at `x`.
|
||||
fn index(&mut self, x: f32, y: f32) {
|
||||
self.row_index += 1;
|
||||
let n = format!("{:02}", self.row_index);
|
||||
let muted = self.muted;
|
||||
self.text(Face::Mono, MICRO, x, y + 2.0, muted, &n);
|
||||
}
|
||||
/// The launcher's settings `row`: its number, a label column, then the
|
||||
/// value; py 12. Returns the row height (draw the action yourself,
|
||||
/// right-aligned, and a `divider` under it).
|
||||
/// right-aligned, and a `divider` under it). `value_w` is measured from
|
||||
/// the value column as before the numbers came; the index takes its
|
||||
/// share from it.
|
||||
pub fn row(&mut self, x: f32, y: f32, label: &str, value: &str, value_w: f32) -> f32 {
|
||||
let line = (BODY * 1.45).round();
|
||||
let h = 12.0 + line.max(CONTROL) + 12.0;
|
||||
let ty = y + (h - line) / 2.0;
|
||||
self.text(Face::Regular, BODY, x, ty, color::MUTED, label);
|
||||
let value = self.fit(Face::Regular, BODY, value, value_w);
|
||||
self.index(x, ty);
|
||||
self.text(Face::Regular, BODY, x + INDEX, ty, color::TEXT, label);
|
||||
let value = self.fit(Face::Regular, BODY, value, (value_w - INDEX).max(0.0));
|
||||
self.text(
|
||||
Face::Regular,
|
||||
BODY,
|
||||
x + ROW_LABEL + 16.0,
|
||||
x + INDEX + ROW_LABEL + 16.0,
|
||||
ty,
|
||||
color::TEXT,
|
||||
color::MUTED,
|
||||
&value,
|
||||
);
|
||||
h
|
||||
}
|
||||
/// A settings row with, under its label, a one-line description led by
|
||||
/// the setting's frame-time cost (`cost` 0 none .. 3 high, coloured from
|
||||
/// faint to the danger colour). Same height as [`Ui::row`].
|
||||
/// the muted colour to the danger colour). Same height as [`Ui::row`].
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn described_row(
|
||||
&mut self,
|
||||
@@ -1056,8 +1126,10 @@ impl<'a> Ui<'a> {
|
||||
) -> f32 {
|
||||
let h = 12.0 + CONTROL + 12.0;
|
||||
let top = y + 8.0;
|
||||
self.index(x, top);
|
||||
let x = x + INDEX;
|
||||
self.text(Face::Regular, BODY, x, top, color::TEXT, label);
|
||||
let value = self.fit(Face::Regular, BODY, value, value_w);
|
||||
let value = self.fit(Face::Regular, BODY, value, (value_w - INDEX).max(0.0));
|
||||
self.text(
|
||||
Face::Regular,
|
||||
BODY,
|
||||
@@ -1070,12 +1142,17 @@ impl<'a> Ui<'a> {
|
||||
let tint = [0.0, 0.2, 0.55, 1.0][usize::from(cost.0.min(3))];
|
||||
let cost_color = color::mix(color::FAINT, color::DANGER, tint);
|
||||
self.text(Face::Medium, SMALL, x, dy, cost_color, cost.1);
|
||||
let used = self.measure(Face::Medium, SMALL, cost.1);
|
||||
// No cost label: the description starts at the row's edge.
|
||||
let used = if cost.1.is_empty() {
|
||||
-8.0
|
||||
} else {
|
||||
self.measure(Face::Medium, SMALL, cost.1)
|
||||
};
|
||||
let rest = self.fit(
|
||||
Face::Regular,
|
||||
SMALL,
|
||||
description,
|
||||
(description_w - used - 8.0).max(0.0),
|
||||
(description_w - INDEX - used - 8.0).max(0.0),
|
||||
);
|
||||
self.text(
|
||||
Face::Regular,
|
||||
@@ -1087,19 +1164,19 @@ impl<'a> Ui<'a> {
|
||||
);
|
||||
h
|
||||
}
|
||||
/// A slider in the launcher's language: a 4px track in the border colour
|
||||
/// filled with the accent, a white 14px knob. Dragging is the screen's
|
||||
/// job (see [`slider_value`]).
|
||||
/// A slider in the launcher's language: a 2px track in the rule colour
|
||||
/// filled with ink, an ink 14px knob that grows under the pointer.
|
||||
/// Dragging is the screen's job (see [`slider_value`]).
|
||||
pub fn slider(&mut self, id: u64, x: f32, cy: f32, w: f32, value: f32) {
|
||||
let hover = self.interact(id, x - 8.0, cy - 12.0, w + 16.0, 24.0, true);
|
||||
let v = value.clamp(0.0, 1.0);
|
||||
self.rounded(x, cy - 2.0, w, 4.0, 2.0, color::BORDER);
|
||||
self.rounded(x, cy - 2.0, w * v, 4.0, 2.0, color::ACCENT);
|
||||
self.rounded(x, cy - 1.0, w, 2.0, 1.0, color::BORDER);
|
||||
self.rounded(x, cy - 1.0, w * v, 2.0, 1.0, color::TEXT);
|
||||
let r = 7.0 + hover;
|
||||
self.rounded(x + w * v - r, cy - r, r * 2.0, r * 2.0, r, color::WHITE);
|
||||
self.rounded(x + w * v - r, cy - r, r * 2.0, r * 2.0, r, color::TEXT);
|
||||
}
|
||||
/// A text field: the launcher's raised control with a 1px border that
|
||||
/// takes the accent while focused.
|
||||
/// A text field: a soft plate with no border; focus draws a 1px accent
|
||||
/// ring.
|
||||
pub fn field(
|
||||
&mut self,
|
||||
id: u64,
|
||||
@@ -1118,71 +1195,62 @@ impl<'a> Ui<'a> {
|
||||
w,
|
||||
h,
|
||||
RADIUS,
|
||||
color::with_alpha(color::HOVER, hover * 0.7),
|
||||
);
|
||||
self.border(
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
RADIUS,
|
||||
color::mix(color::BORDER, color::ACCENT, focus),
|
||||
color::with_alpha(color::HOVER, hover * 0.6),
|
||||
);
|
||||
self.border(x, y, w, h, RADIUS, color::with_alpha(color::ACCENT, focus));
|
||||
let shown = self.fit(Face::Regular, BODY, value, w - 28.0);
|
||||
let tw = if value.is_empty() {
|
||||
self.text_line(
|
||||
Face::Regular,
|
||||
BODY,
|
||||
h,
|
||||
x + 12.0,
|
||||
x + 14.0,
|
||||
y,
|
||||
color::FAINT,
|
||||
placeholder,
|
||||
);
|
||||
0.0
|
||||
} else {
|
||||
self.text_line(Face::Regular, BODY, h, x + 12.0, y, color::TEXT, &shown)
|
||||
self.text_line(Face::Regular, BODY, h, x + 14.0, y, color::TEXT, &shown)
|
||||
};
|
||||
if focused && caret {
|
||||
self.fill(x + 12.0 + tw + 1.0, y + 8.0, 1.0, h - 16.0, color::TEXT);
|
||||
self.fill(x + 14.0 + tw + 1.0, y + 9.0, 1.0, h - 18.0, color::TEXT);
|
||||
}
|
||||
}
|
||||
/// The launcher's atmosphere over the backdrop: a veil of the page
|
||||
/// background, darker from the left and toward the bottom.
|
||||
/// The veil over the live backdrop: the page colour, flat, at `veil`.
|
||||
/// `shade` fades it in with the opening.
|
||||
pub fn atmosphere(&mut self, veil: f32, shade: f32) {
|
||||
let (w, h) = (self.w, self.h);
|
||||
self.fill(0.0, 0.0, w, h, color::with_alpha(color::BG, veil));
|
||||
self.hgradient(
|
||||
self.fill(
|
||||
0.0,
|
||||
0.0,
|
||||
w * 0.7,
|
||||
h,
|
||||
color::with_alpha(color::BG, 0.9 * shade),
|
||||
color::with_alpha(color::BG, 0.0),
|
||||
);
|
||||
self.gradient(
|
||||
0.0,
|
||||
h * 0.25,
|
||||
w,
|
||||
h * 0.75,
|
||||
color::with_alpha(color::BG, 0.0),
|
||||
color::with_alpha(color::BG, 0.75 * shade),
|
||||
h,
|
||||
color::with_alpha(color::BG, veil * shade.max(0.0)),
|
||||
);
|
||||
}
|
||||
/// The plain background while the live backdrop loads: the page colour
|
||||
/// with a faint cold light from the top.
|
||||
/// The giant faint wordmark, whole, as wide as the column at `x` (`w` wide, at most `max`
|
||||
/// tall) with its baseline at `bottom`.
|
||||
pub fn wordmark(&mut self, x: f32, w: f32, bottom: f32, max: f32) {
|
||||
let unit = self.measure(Face::Display, 100.0, "horizon") / 100.0;
|
||||
let size = (w / unit).min(max).floor();
|
||||
// Geist's x-height glyphs sit on the baseline; its ascenders reach 0.75 em above it.
|
||||
let line = (size * 1.2).round();
|
||||
let top = bottom - line * 0.5 - size * 0.36;
|
||||
self.text_line(
|
||||
Face::Display,
|
||||
size,
|
||||
line,
|
||||
x - size * 0.05,
|
||||
top,
|
||||
color::with_alpha(color::TEXT, 0.06),
|
||||
"horizon",
|
||||
);
|
||||
}
|
||||
/// The plain background while the live backdrop loads: the page colour.
|
||||
pub fn cold_background(&mut self, opacity: f32) {
|
||||
let (w, h) = (self.w, self.h);
|
||||
let a = |c: u32, k: f32| color::with_alpha(c, k * opacity);
|
||||
self.fill(0.0, 0.0, w, h, a(color::BG, 1.0));
|
||||
self.gradient(
|
||||
0.0,
|
||||
0.0,
|
||||
w,
|
||||
h * 0.7,
|
||||
a(color::hex(0x3a5a86, 255), 0.22),
|
||||
a(color::hex(0x3a5a86, 255), 0.0),
|
||||
);
|
||||
self.fill(0.0, 0.0, w, h, color::with_alpha(color::BG, opacity));
|
||||
}
|
||||
}
|
||||
/// The slider value (0..1) for a cursor x in GUI pixels over a track at
|
||||
|
||||
@@ -307,10 +307,30 @@ impl FullscreenState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Horizon's icon for the window's title bar and the task bar (X11 and Windows; Wayland takes
|
||||
/// it from the `horizon.desktop` entry, macOS from the app bundle). `None` if it can't be read.
|
||||
pub fn icon() -> Option<winit::window::Icon> {
|
||||
let mut decoder = png::Decoder::new(std::io::Cursor::new(horizon_theme::ICON_PNG));
|
||||
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
let mut reader = decoder.read_info().ok()?;
|
||||
let mut bytes = vec![0; reader.output_buffer_size()?];
|
||||
let info = reader.next_frame(&mut bytes).ok()?;
|
||||
if info.color_type != png::ColorType::Rgba {
|
||||
return None;
|
||||
}
|
||||
bytes.truncate(info.buffer_size());
|
||||
winit::window::Icon::from_rgba(bytes, info.width, info.height).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_window_icon_decodes() {
|
||||
assert!(icon().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fullscreen_follows_the_option_only_when_it_changes() {
|
||||
let mut f = FullscreenState::new(false);
|
||||
|
||||
@@ -398,7 +398,8 @@ impl Run<'_> {
|
||||
|
||||
/// Prepares the resources; returns their folder (`.local/horizon-client/<version>`).
|
||||
pub fn prepare(options: &Options, log: Log) -> Result<PathBuf, String> {
|
||||
let root = &options.root;
|
||||
let root = &std::path::absolute(&options.root)
|
||||
.map_err(|e| format!("{}: {e}", options.root.display()))?;
|
||||
let lock = artifacts::Lock::read(root)?;
|
||||
// Java first: nothing below can finish without it, and the player should hear it at once.
|
||||
let jdk = java::find(lock.java_major)?;
|
||||
|
||||
Binary file not shown.
@@ -1,93 +0,0 @@
|
||||
Copyright 2022 The Instrument Serif Project Authors (https://github.com/Instrument/instrument-serif)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 797 B |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user