Merge remote-tracking branch 'origin/main' into cg15/1955
# Conflicts: # tools/lan_e2e.py
This commit is contained in:
@@ -3,7 +3,8 @@ name: checks
|
||||
# check main requires, so it never has a condition: a skipped job counts as passed, and every run of this workflow
|
||||
# must report a real verify (a pull request that changes no Rust finishes it in seconds instead).
|
||||
# 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); .github/workflows/parity.yml. A fork's pull
|
||||
# maintainer's own Minecraft files (Horizon never downloads the game); .github/workflows/parity.yml. Only for a pull
|
||||
# request that changes a harness, oracle, probe or the runner: the rest are checked on main by parity-main. A fork's pull
|
||||
# request runs it only when a maintainer adds the run-parity label (.github/workflows/run-parity.yml), so labels
|
||||
# never start this workflow. See docs/release-flow.md.
|
||||
on:
|
||||
@@ -72,8 +73,37 @@ jobs:
|
||||
run: |
|
||||
cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack
|
||||
cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack
|
||||
parity:
|
||||
# Most pull requests leave the harnesses to parity-main, which runs them on main a batch of merges at a time
|
||||
# (.github/workflows/parity-main.yml; releases wait for it). A pull request still runs them itself when it changes
|
||||
# a harness, an oracle, a probe or the runner, or carries the run-parity label (run-parity.yml, when it is added).
|
||||
parity-scope:
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
run: ${{ steps.scope.outputs.run }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- id: scope
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
LABELS: ${{ join(github.event.pull_request.labels.*.name, ' ') }}
|
||||
run: |
|
||||
changed=$(git diff --name-only "$(git merge-base "$BASE_SHA" HEAD)" HEAD)
|
||||
harness=$(grep -E '^(tools/test_[a-z0-9_]+_parity\.py|tools/(parity[a-z_]*|lab)\.py|tools/parity_hosts\.json|mods/horizon/src/test/|crates/[^/]+/examples/|crates/horizon-client/src/game/[a-z_]*(fixture|harness)\.rs|\.github/workflows/parity[a-z-]*\.yml)' <<< "$changed" || true)
|
||||
if [ -n "$harness" ] || [[ " $LABELS " == *" run-parity "* ]]; then
|
||||
echo "run=true" >> "$GITHUB_OUTPUT"
|
||||
echo "The pull request runs its harnesses: ${harness:-label run-parity}"
|
||||
else
|
||||
echo "run=false" >> "$GITHUB_OUTPUT"
|
||||
echo "No harness, oracle, probe or runner change: parity-main checks this on main"
|
||||
fi
|
||||
parity:
|
||||
needs: parity-scope
|
||||
if: needs.parity-scope.outputs.run == 'true'
|
||||
uses: ./.github/workflows/parity.yml
|
||||
with:
|
||||
base: ${{ github.event.pull_request.base.sha }}
|
||||
|
||||
@@ -29,7 +29,8 @@ env:
|
||||
|
||||
jobs:
|
||||
audit:
|
||||
runs-on: [self-hosted, horizon-game]
|
||||
# The Mac mini's runners only: the audit compares with the previous one, so it stays on one platform.
|
||||
runs-on: [self-hosted, horizon-game, macOS]
|
||||
timeout-minutes: 150
|
||||
steps:
|
||||
- name: 03:00 in Paris
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
name: parity-main
|
||||
# The vanilla harnesses on main, a batch of merges at a time (docs/release-flow.md#parity-on-main), on the Mac mini's
|
||||
# runner. One run at a time: merges that land while a run goes on wait in one pending run (GitHub keeps only the
|
||||
# newest), which checks every merge since main's last green parity-main (tools/parity_main.py base). On a failure it
|
||||
# bisects the failing harnesses over those merges and comments on the pull request that broke them. Releases ship
|
||||
# only a commit whose parity-main passed (tools/release_train.py), so nothing a harness catches reaches players.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
# The comment on the merge that broke a harness.
|
||||
pull-requests: write
|
||||
# tools/parity_main.py base reads earlier runs.
|
||||
actions: read
|
||||
concurrency:
|
||||
group: parity-main
|
||||
cancel-in-progress: false
|
||||
env:
|
||||
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
|
||||
HORIZON_TELEMETRY_URL: "off"
|
||||
|
||||
jobs:
|
||||
parity-main:
|
||||
# The Mac mini's release runner (label added 2026-10-26), not the two `horizon-game` runners: behind PR parity jobs
|
||||
# this run waited 2 h while every merge replaced the pending one, and releases wait for it. Releases need it green
|
||||
# first, so the two never compete. Not the desktop: a job slowed down because the maintainer came back could time
|
||||
# out, and a failure here bisects and comments on merges.
|
||||
runs-on: [self-hosted, macOS, horizon-parity-main]
|
||||
timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.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: Main's last green parity-main
|
||||
id: base
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: echo "sha=$(python3 tools/parity_main.py base)" >> "$GITHUB_OUTPUT"
|
||||
- name: The harnesses the merges since then can affect
|
||||
env:
|
||||
PARITY_HOSTS: ''
|
||||
BASE_SHA: ${{ steps.base.outputs.sha }}
|
||||
run: |
|
||||
echo "Merges since ${BASE_SHA}:"
|
||||
git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD"
|
||||
python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400
|
||||
- name: The merge that broke them
|
||||
if: failure()
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PARITY_HOSTS: ''
|
||||
BASE_SHA: ${{ steps.base.outputs.sha }}
|
||||
run: |
|
||||
rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true
|
||||
python3 tools/parity_main.py bisect "$BASE_SHA" --comment
|
||||
- name: Logs of the failed harnesses
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: parity-main-logs
|
||||
path: .local/parity-main-logs/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
@@ -36,14 +36,69 @@ jobs:
|
||||
- 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
|
||||
env:
|
||||
BASE_SHA: ${{ inputs.base }}
|
||||
run: |
|
||||
# main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on
|
||||
# the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own.
|
||||
set -euo pipefail
|
||||
if git rev-parse --verify -q origin/main >/dev/null \
|
||||
&& git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then
|
||||
git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh"
|
||||
bash "$RUNNER_TEMP/vanilla-data.sh"
|
||||
else
|
||||
bash tools/ci/vanilla-data.sh
|
||||
fi
|
||||
- name: The prepared output is the one the preparer's OUTPUT_VERSION says
|
||||
env:
|
||||
BASE_SHA: ${{ inputs.base }}
|
||||
run: python3 tools/prepare_output.py check --cache --base "$BASE_SHA"
|
||||
- name: The version constants are the pinned jar's
|
||||
run: python3 tools/gen_version_consts.py --check
|
||||
- name: The harnesses this change can affect
|
||||
env:
|
||||
PARITY_HOSTS: ''
|
||||
BASE_SHA: ${{ inputs.base }}
|
||||
run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner
|
||||
run: |
|
||||
# main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a
|
||||
# branch made before a better selection landed gets it too; the head's own runner then runs those
|
||||
# harnesses. A branch that changes the selection itself selects with its own code.
|
||||
set -euo pipefail
|
||||
own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner
|
||||
fork_point=$(git merge-base "$BASE_SHA" HEAD)
|
||||
if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then
|
||||
own
|
||||
exit
|
||||
fi
|
||||
had_reach=$(git ls-files tools/parity_reach.py)
|
||||
git show origin/main:tools/parity.py > tools/parity.py
|
||||
git show origin/main:tools/parity_reach.py > tools/parity_reach.py
|
||||
status=0
|
||||
python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$?
|
||||
git checkout -- tools/parity.py
|
||||
if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi
|
||||
cat .local/parity-selection.txt
|
||||
if [ "$status" != 0 ]; then
|
||||
echo "main's selection failed: the head's own selection runs"
|
||||
own
|
||||
exit
|
||||
fi
|
||||
names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true)
|
||||
# The summary line says how many would run: a count that doesn't match the names read (a format change)
|
||||
# must not let the job pass untested.
|
||||
expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p')
|
||||
count=$(printf '%s' "$names" | grep -c . || true)
|
||||
if [ -z "$expected" ] || [ "$expected" != "$count" ]; then
|
||||
echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs"
|
||||
own
|
||||
exit
|
||||
fi
|
||||
if [ "$count" = 0 ]; then
|
||||
echo "Nothing to run."
|
||||
exit 0
|
||||
fi
|
||||
# shellcheck disable=SC2086
|
||||
python3 tools/parity.py $names --timeout 2400
|
||||
- name: Logs of the failed harnesses
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
name: release
|
||||
# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a
|
||||
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides:
|
||||
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides,
|
||||
# for a commit whose checks and parity-main (the vanilla harnesses on main) both passed:
|
||||
# a release when 5 pull requests merged since the last one changed what players run and the newest merged 5 minutes
|
||||
# ago, or when the oldest has waited 6 hours, or at once for a pull request labelled release-now.
|
||||
# RELEASES_PAUSED=1 (repository variable) stops them; so does an open issue labelled release-blocker, forced runs too.
|
||||
@@ -18,7 +19,8 @@ name: release
|
||||
# gh workflow run release -f dry_run=false -f force=true # on main: release now, whatever the rules say
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [checks]
|
||||
# A game release ships a commit both passed on (parity-main runs on batches: the newest commit it passed on).
|
||||
workflows: [checks, parity-main]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
schedule:
|
||||
@@ -64,8 +66,8 @@ jobs:
|
||||
env:
|
||||
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.
|
||||
# The commit whose checks or parity-main just passed; a dry run builds the branch it was started on;
|
||||
# otherwise main's newest commit with green checks and parity-main.
|
||||
HEAD_SHA: ${{ github.event.workflow_run.head_sha || (steps.mode.outputs.dry_run == 'true' && github.sha) || '' }}
|
||||
FORCE: ${{ inputs.force && 'yes' || '' }}
|
||||
run: |
|
||||
@@ -77,9 +79,50 @@ jobs:
|
||||
# A dry run builds whatever the decision, to test the builds.
|
||||
if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi
|
||||
|
||||
build:
|
||||
exporters:
|
||||
needs: decide
|
||||
if: needs.decide.outputs.release == 'true'
|
||||
# This runner holds the maintainer's own pinned Minecraft jars. Only our classes leave it.
|
||||
runs-on: ${{ vars.MAC_RUNNER || 'ludovics-mac-mini' }}
|
||||
# Three full preparations (two isolated, one batched) besides the compile.
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.decide.outputs.head }}
|
||||
persist-credentials: false
|
||||
clean: true
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- run: bash tools/ci/runner-env.sh
|
||||
- run: bash tools/ci/vanilla-data.sh
|
||||
- name: Compile and validate original exporters against the pinned jars
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# target/ is gone after the clean checkout, and vanilla-data.sh builds the preparer only when it
|
||||
# prepares afresh.
|
||||
cargo build --release --locked -p horizon-prepare
|
||||
# Compiled here, never taken from the runner's shared preparations: pull requests' parity jobs
|
||||
# write those (vanilla-data.sh links .local/exporters to them).
|
||||
rm -rf .local/exporters
|
||||
bundle=$(target/release/horizon-prepare compile-exporters --root "$PWD" | tail -1)
|
||||
mkdir -p exporters
|
||||
cp -R "$bundle/server" "$bundle/client" "$bundle/manifest.json" exporters/
|
||||
# Only our classes and their manifest leave this runner.
|
||||
stray=$(find exporters -type f ! -path exporters/manifest.json \
|
||||
! \( -name '*.class' \( -path 'exporters/server/dev/horizonlab/parity/*' -o -path 'exporters/client/dev/horizonlab/parity/*' \) \))
|
||||
[ -z "$stray" ] || { echo "::error::not one of our classes: $stray"; exit 1; }
|
||||
python3 tools/check_prepare_exporters.py --binary target/release/horizon-prepare
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: original-exporters
|
||||
path: exporters/
|
||||
if-no-files-found: error
|
||||
retention-days: 3
|
||||
|
||||
build:
|
||||
needs: [decide, exporters]
|
||||
if: needs.decide.outputs.release == 'true'
|
||||
name: build ${{ matrix.name }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -218,6 +261,10 @@ jobs:
|
||||
path: ${{ runner.temp }}/smoke-test.json
|
||||
if-no-files-found: error
|
||||
retention-days: 3
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: original-exporters
|
||||
path: exporters
|
||||
- name: Package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -31,3 +31,6 @@
|
||||
/.horizon-cache/
|
||||
/crash-reports/
|
||||
/debug/
|
||||
|
||||
# Release-only compiled original exporter bundle.
|
||||
/exporters/
|
||||
|
||||
@@ -82,7 +82,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
|
||||
~25, a file of the client lib ~103, of `horizon-world` ~103–109, of `horizon-core` ~119. Plan for it.
|
||||
- Rust integration tests: `crates/horizon-client/tests/` (`lan_bot.rs`, `generation_saves.rs`, `streaming_meshes.rs`).
|
||||
- **macOS:** `cargo build/test --workspace` may fail to link the two wasm guest cdylibs (undefined
|
||||
`horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude horizon-mods-test-guest --exclude horizon-mods-test-ui-guest`.
|
||||
`horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude predator-missile --exclude horizon-mods-test-guest --exclude horizon-mods-test-ui-guest`.
|
||||
Their real check is `cargo test -p horizon-mods` (builds them for `wasm32-unknown-unknown`).
|
||||
- Linux needs `libasound2-dev libudev-dev`; `--no-default-features` drops audio and controllers (the server build).
|
||||
- Run and drive the game (starts the `horizon-client` beside `horizon-ctl`; other arguments go to the game):
|
||||
|
||||
Generated
+238
-310
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -31,7 +31,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten in Rust: a native game that re
|
||||
|
||||
Horizon is installed through **the Horizon launcher**. Get it from [playhorizon.dev](https://playhorizon.dev) (the Download button picks your system) or from [the launcher releases](https://github.com/ludovic111/horizon/releases?q=launcher-v&expanded=true), for Linux x86-64, macOS on Apple Silicon or Windows x64. The launcher installs and updates the game, prepares its files from your own copy of Minecraft, and updates itself.
|
||||
|
||||
**You need** Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 JDK, for the one-time preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install).
|
||||
**You need** Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 runtime, for the one-time preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install).
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
|
||||
@@ -208,6 +208,9 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
|
||||
game_time: t,
|
||||
day_time: 1000 + t,
|
||||
}),
|
||||
// The GUI of a 1280 x 720 window at scale 3.
|
||||
gui_size: (427.0, 240.0),
|
||||
held: None,
|
||||
});
|
||||
mods.tick(t);
|
||||
for _ in 0..FRAMES_PER_TICK {
|
||||
@@ -224,11 +227,19 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
|
||||
Output::Feedback { text, error } => {
|
||||
format!("{}: {text}", if error { "error" } else { "feedback" })
|
||||
}
|
||||
Output::Command { line } => format!("command: /{line}"),
|
||||
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
|
||||
Output::OpenScreen { .. } => "opened a screen".to_string(),
|
||||
Output::CloseScreen { .. } => "closed its screen".to_string(),
|
||||
Output::Shake { strength, seconds } => {
|
||||
format!("shook the camera: {strength:.2} for {seconds:.1} s")
|
||||
}
|
||||
});
|
||||
}
|
||||
let shapes = mods.hud_shapes().count();
|
||||
if shapes > 0 {
|
||||
report.output.push(format!("drew {shapes} HUD shape(s)"));
|
||||
}
|
||||
match failed(&mods) {
|
||||
Some(reason) => Err(format!("it stopped: {reason}")),
|
||||
None => Ok(()),
|
||||
|
||||
@@ -367,6 +367,7 @@ pub fn main() -> Result<()> {
|
||||
lid: &|_| open,
|
||||
sign: &|_| sign.as_ref(),
|
||||
banner: &|_| layers.clone(),
|
||||
skull: &|_| None,
|
||||
glyph: &|c| atlas.glyph_cell(c),
|
||||
};
|
||||
let mut verts = Vec::new();
|
||||
|
||||
@@ -598,6 +598,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool, now: i6
|
||||
let _ = writeln!(out, " removed {reason}");
|
||||
return;
|
||||
}
|
||||
let _ = write!(out, "\tleashed {}", u8::from(m.extra.leash.is_some()));
|
||||
let p = m.position;
|
||||
let v = m.velocity;
|
||||
let _ = write!(
|
||||
@@ -977,6 +978,7 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
// Set once the brain exists (below).
|
||||
x if x.starts_with("cooldown=") => {}
|
||||
"dead" => m.health = 0.0,
|
||||
"leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player),
|
||||
x if x.starts_with("leashto=") => {
|
||||
let n: u32 = x[8..].parse().unwrap();
|
||||
@@ -1097,6 +1099,7 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
};
|
||||
}
|
||||
let mut dropped_leads = 0;
|
||||
for t in 1..=s.ticks {
|
||||
world.game_time += 1;
|
||||
if s.daycycle {
|
||||
@@ -1208,6 +1211,16 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
if !alive {
|
||||
m.removed = true;
|
||||
}
|
||||
// Apply the same detach/drop event as Game::break_leash.
|
||||
for event in &events[from..] {
|
||||
if let MobEvent::LeashBreak { mob, drop, .. } = event
|
||||
&& let Some(m) = mobs.iter_mut().find(|m| m.id == *mob)
|
||||
&& horizon_client::mobs::leash::remove(m).is_some()
|
||||
&& *drop
|
||||
{
|
||||
dropped_leads += 1;
|
||||
}
|
||||
}
|
||||
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
|
||||
villager_events(
|
||||
&mut mobs,
|
||||
@@ -1427,6 +1440,9 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
world.game_time,
|
||||
);
|
||||
}
|
||||
if s.name.starts_with("leash_death_") {
|
||||
let _ = writeln!(out, "{t} leads {dropped_leads}");
|
||||
}
|
||||
for e in &events {
|
||||
if let MobEvent::Sound(name, _, volume, pitch) = e {
|
||||
let _ = writeln!(
|
||||
|
||||
@@ -63,6 +63,10 @@ enum Animate {
|
||||
SculkSensor,
|
||||
/// Potent sulfur that is not dry.
|
||||
PotentSulfur,
|
||||
DriedGhast {
|
||||
waterlogged: bool,
|
||||
},
|
||||
EndPortal,
|
||||
}
|
||||
fn step(facing: &str) -> [i32; 3] {
|
||||
match facing {
|
||||
@@ -137,6 +141,10 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
|
||||
drag: prop("drag").as_deref() == Some("true"),
|
||||
},
|
||||
"fire" | "soul_fire" => Animate::Fire,
|
||||
"dried_ghast" => Animate::DriedGhast {
|
||||
waterlogged: prop("waterlogged").as_deref() == Some("true"),
|
||||
},
|
||||
"end_portal" => Animate::EndPortal,
|
||||
"sculk_sensor" | "calibrated_sculk_sensor"
|
||||
if prop("sculk_sensor_phase").as_deref() == Some("active") =>
|
||||
{
|
||||
@@ -180,6 +188,8 @@ pub struct AnimateTables {
|
||||
impermeable: Vec<bool>,
|
||||
power_provider: Vec<bool>,
|
||||
power_transmitter: Vec<bool>,
|
||||
/// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil).
|
||||
dried_ghast_sounds: Vec<bool>,
|
||||
/// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`).
|
||||
ambient: Vec<Vec<(T, f32)>>,
|
||||
}
|
||||
@@ -237,6 +247,7 @@ impl AnimateTables {
|
||||
impermeable: by_state("minecraft:impermeable"),
|
||||
power_provider: by_state("minecraft:enchantment_power_provider"),
|
||||
power_transmitter: by_state("minecraft:enchantment_power_transmitter"),
|
||||
dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"),
|
||||
ambient,
|
||||
})
|
||||
}
|
||||
@@ -869,6 +880,45 @@ fn block_animate_tick(
|
||||
];
|
||||
add(engine, T::Smoke, p, [0.0; 3]);
|
||||
}
|
||||
Animate::DriedGhast { waterlogged } => {
|
||||
// DriedGhastBlock.animateTick.
|
||||
let c = [fx + 0.5, fy + 0.5, fz + 0.5];
|
||||
if waterlogged {
|
||||
if next_int(engine.random(), 40) == 0 {
|
||||
let name = "minecraft:block.dried_ghast.ambient_water";
|
||||
sound(engine, name, c, 1.0, 1.0);
|
||||
}
|
||||
let r = engine.random();
|
||||
if next_int(r, 6) == 0 {
|
||||
let x = c[0] + f64::from((r.next_float() * 2.0 - 1.0) / 3.0);
|
||||
let y = c[1] + 0.4;
|
||||
let z = c[2] + f64::from((r.next_float() * 2.0 - 1.0) / 3.0);
|
||||
let v = [0.0, f64::from(r.next_float()), 0.0];
|
||||
add(engine, T::HappyVillager, [x, y, z], v);
|
||||
}
|
||||
} else {
|
||||
let below = ctx.state([pos[0], pos[1] - 1, pos[2]]);
|
||||
let triggers = || {
|
||||
tables
|
||||
.dried_ghast_sounds
|
||||
.get(below.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
};
|
||||
if next_int(engine.random(), 40) == 0 && triggers() {
|
||||
sound(engine, "minecraft:block.dried_ghast.ambient", c, 1.0, 1.0);
|
||||
}
|
||||
if next_int(engine.random(), 6) == 0 {
|
||||
add(engine, T::WhiteSmoke, c, [0.0, 0.02, 0.0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Animate::EndPortal => {
|
||||
// EndPortalBlock.animateTick: one smoke particle above the surface.
|
||||
let r = engine.random();
|
||||
let p = [fx + r.next_double(), fy + 0.8, fz + r.next_double()];
|
||||
add(engine, T::Smoke, p, [0.0; 3]);
|
||||
}
|
||||
Animate::EnderChest => {
|
||||
for _ in 0..3 {
|
||||
let r = engine.random();
|
||||
|
||||
@@ -730,6 +730,10 @@ pub struct Scene<'a> {
|
||||
pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>,
|
||||
/// Banner layers at a position: pattern texture and RGB tint, bottom first.
|
||||
pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>,
|
||||
/// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer`
|
||||
/// profile → skin): a downloaded `skins/<sha1>` slot or the profile's
|
||||
/// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (`DefaultPlayerSkin.getDefaultTexture`, slim steve).
|
||||
pub skull: &'a dyn Fn([i32; 3]) -> Option<&'a str>,
|
||||
/// Font glyph cell (none for blank glyphs such as the space) and advance.
|
||||
pub glyph: &'a dyn Fn(char) -> (Option<Rect>, f32),
|
||||
}
|
||||
@@ -1279,6 +1283,13 @@ impl BlockEntityRenderer {
|
||||
SkullType::Piglin => ("piglin_head", "entity/piglin/piglin"),
|
||||
SkullType::Player => ("player_head", "entity/player/slim/steve"),
|
||||
};
|
||||
// SkullBlockRenderer.getRenderType: the profile's skin when it
|
||||
// resolves, `SKIN_BY_TYPE` (steve) otherwise.
|
||||
let texture = if *kind == SkullType::Player {
|
||||
(scene.skull)(pos).unwrap_or(texture)
|
||||
} else {
|
||||
texture
|
||||
};
|
||||
let (Some(model), Some(paint)) =
|
||||
(self.models.get(model), paint(texture, 0xFFFFFF, packed))
|
||||
else {
|
||||
@@ -1886,6 +1897,7 @@ mod tests {
|
||||
lid: &|_| 0.0,
|
||||
sign: &|_| None,
|
||||
banner: &|_| Vec::new(),
|
||||
skull: &|_| None,
|
||||
glyph: &|_| (None, 0.0),
|
||||
};
|
||||
// Compare the cached world path with the original model renderer,
|
||||
|
||||
@@ -592,3 +592,21 @@ fn mod_commands_join_the_tree_for_every_player() {
|
||||
// The game's own tree is left as it was.
|
||||
assert!(vanilla::game_dispatcher().find("where").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizon_commands_are_off_unless_the_server_turns_them_on() {
|
||||
// By default the game runs vanilla's tree: /help lists no /pregen.
|
||||
assert!(vanilla::game_dispatcher().find("pregen").is_none());
|
||||
for dev in [false, true] {
|
||||
let vanilla_tree = vanilla::game_tree(dev, false);
|
||||
assert!(vanilla_tree.find("pregen").is_none());
|
||||
let d = vanilla::game_tree(dev, true);
|
||||
let parse = d.parse("pregen start 100 circle", ®());
|
||||
assert_eq!(parse.executable().unwrap().1, "pregen.start");
|
||||
// Vanilla's commands are the same with or without it.
|
||||
assert_eq!(
|
||||
d.nodes[0].children.len(),
|
||||
vanilla_tree.nodes[0].children.len() + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -538,12 +538,69 @@ fn apply_vanilla_order(d: &mut Dispatcher) {
|
||||
}
|
||||
/// The tree the game runs: a release integrated server's, or with
|
||||
/// `HORIZON_DEV_COMMANDS` set the development one
|
||||
/// (SharedConstants.DEBUG_DEV_COMMANDS).
|
||||
/// (SharedConstants.DEBUG_DEV_COMMANDS), plus Horizon's own commands when
|
||||
/// the server turned them on (`set_horizon_commands`).
|
||||
pub fn game_dispatcher() -> &'static Dispatcher {
|
||||
if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() {
|
||||
dispatcher()
|
||||
} else {
|
||||
release_dispatcher()
|
||||
game_tree(
|
||||
std::env::var_os("HORIZON_DEV_COMMANDS").is_some(),
|
||||
HORIZON_COMMANDS.load(std::sync::atomic::Ordering::Relaxed),
|
||||
)
|
||||
}
|
||||
/// Whether this process's server has Horizon's own commands (`/pregen`). Off
|
||||
/// by default, so `/help` and the command tree are vanilla's; a dedicated
|
||||
/// server turns them on with `horizon-pregen=true` in server.properties, the
|
||||
/// game with `--pregen` (docs/pregeneration.md).
|
||||
static HORIZON_COMMANDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
/// Turns Horizon's own commands on or off for the trees `game_dispatcher`
|
||||
/// returns from now on.
|
||||
pub fn set_horizon_commands(on: bool) {
|
||||
HORIZON_COMMANDS.store(on, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
/// The server.properties key that turns `/pregen` on (Horizon's own; vanilla
|
||||
/// ignores keys it doesn't know).
|
||||
pub const PREGEN_PROPERTY: &str = "horizon-pregen";
|
||||
pub(crate) fn game_tree(dev: bool, horizon: bool) -> &'static Dispatcher {
|
||||
static HORIZON: [std::sync::OnceLock<Dispatcher>; 2] =
|
||||
[const { std::sync::OnceLock::new() }; 2];
|
||||
match (dev, horizon) {
|
||||
(true, false) => dispatcher(),
|
||||
(false, false) => release_dispatcher(),
|
||||
(dev, true) => HORIZON[usize::from(dev)].get_or_init(|| {
|
||||
let mut d = build_with(dev);
|
||||
horizon_commands(&mut d, 0);
|
||||
d
|
||||
}),
|
||||
}
|
||||
}
|
||||
/// Commands vanilla doesn't have, after its own: `/pregen`
|
||||
/// (docs/pregeneration.md).
|
||||
fn horizon_commands(d: &mut Dispatcher, root: usize) {
|
||||
let pregen = d.literal(root, "pregen");
|
||||
d.requires(pregen, GAMEMASTERS);
|
||||
let start = d.literal(pregen, "start");
|
||||
let radius = d.argument(
|
||||
start,
|
||||
"radius",
|
||||
ArgType::Integer {
|
||||
min: 0,
|
||||
max: 30_000_000,
|
||||
},
|
||||
);
|
||||
d.executes(radius, "pregen.start");
|
||||
for shape in ["square", "circle"] {
|
||||
let shape = d.literal(radius, shape);
|
||||
d.executes(shape, "pregen.start");
|
||||
let center = d.argument(shape, "center", ArgType::ColumnPos);
|
||||
d.executes(center, "pregen.start");
|
||||
}
|
||||
for (word, id) in [
|
||||
("pause", "pregen.pause"),
|
||||
("continue", "pregen.continue"),
|
||||
("cancel", "pregen.cancel"),
|
||||
("status", "pregen.status"),
|
||||
] {
|
||||
let w = d.literal(pregen, word);
|
||||
d.executes(w, id);
|
||||
}
|
||||
}
|
||||
pub fn dispatcher() -> &'static Dispatcher {
|
||||
|
||||
@@ -83,6 +83,60 @@ pub enum BlockEntity {
|
||||
Beehive(Box<crate::beehive::Beehive>),
|
||||
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
|
||||
CommandBlock(Box<crate::command_block::CommandBlock>),
|
||||
/// `SkullBlockEntity` of every skull and head block.
|
||||
Skull(Skull),
|
||||
}
|
||||
/// `SkullBlockEntity`: the player profile the head shows (kept as loaded:
|
||||
/// a compound, or a string when it names a player only), the note block
|
||||
/// sound and `custom_name`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Skull {
|
||||
pub profile: Option<horizon_world::nbt::Tag>,
|
||||
pub note_block_sound: Option<String>,
|
||||
pub custom_name: Option<horizon_world::nbt::Tag>,
|
||||
/// What `profile` draws, read from it once rather than every frame.
|
||||
pub skin: Option<SkullSkin>,
|
||||
}
|
||||
impl Skull {
|
||||
pub fn new(
|
||||
profile: Option<horizon_world::nbt::Tag>,
|
||||
note_block_sound: Option<String>,
|
||||
custom_name: Option<horizon_world::nbt::Tag>,
|
||||
) -> Self {
|
||||
let skin = profile.as_ref().map(SkullSkin::of);
|
||||
Self {
|
||||
profile,
|
||||
note_block_sound,
|
||||
custom_name,
|
||||
skin,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `SkullBlockRenderer.getPlayerSkin` of a head's profile: its skin's URL
|
||||
/// with the `skins/<sha1>` sprite it downloads to, and the
|
||||
/// `DefaultPlayerSkin` drawn until that sprite is there (steve for a
|
||||
/// profile with no id).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SkullSkin {
|
||||
pub download: Option<(String, String)>,
|
||||
pub fallback: &'static str,
|
||||
}
|
||||
impl SkullSkin {
|
||||
pub fn of(profile: &horizon_world::nbt::Tag) -> Self {
|
||||
let download = crate::skins::profile_skin_url_nbt(profile).and_then(|url| {
|
||||
let location = crate::skins::skin_location(&crate::skins::texture_hash(&url)?);
|
||||
Some((url, location))
|
||||
});
|
||||
// DefaultPlayerSkin.get(id), or getDefaultSkin (slim steve) without an id.
|
||||
let fallback = crate::skins::profile_uuid_nbt(profile)
|
||||
.map_or("entity/player/slim/steve", crate::tab_list::default_skin);
|
||||
Self { download, fallback }
|
||||
}
|
||||
}
|
||||
/// The skull and head blocks (`SkullBlock`, `WallSkullBlock`): every
|
||||
/// `*_skull` and `*_head` but the piston's head.
|
||||
fn is_skull(name: &str) -> bool {
|
||||
name.ends_with("_skull") || (name.ends_with("_head") && name != "minecraft:piston_head")
|
||||
}
|
||||
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
|
||||
/// and the ticks left in the crafting animation.
|
||||
@@ -238,6 +292,9 @@ impl BlockEntity {
|
||||
if name.ends_with("_banner") {
|
||||
return Some(Self::Banner(Banner::default()));
|
||||
}
|
||||
if is_skull(name) {
|
||||
return Some(Self::Skull(Skull::default()));
|
||||
}
|
||||
if name == "minecraft:beacon" {
|
||||
return Some(Self::Beacon(Box::new(Beacon {
|
||||
last_check_y: i32::MIN / 2,
|
||||
@@ -283,6 +340,7 @@ impl BlockEntity {
|
||||
Self::Vault(_) => "minecraft:vault",
|
||||
Self::Beehive(_) => "minecraft:beehive",
|
||||
Self::CommandBlock(_) => "minecraft:command_block",
|
||||
Self::Skull(_) => "minecraft:skull",
|
||||
}
|
||||
}
|
||||
pub fn contents(&self) -> Vec<ItemStack> {
|
||||
@@ -298,7 +356,8 @@ impl BlockEntity {
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Vault(_)
|
||||
| Self::Beehive(_)
|
||||
| Self::CommandBlock(_) => Vec::new(),
|
||||
| Self::CommandBlock(_)
|
||||
| Self::Skull(_) => Vec::new(),
|
||||
Self::Lectern(l) => l.book.iter().cloned().collect(),
|
||||
Self::Sculk(_) => Vec::new(),
|
||||
Self::Banner(_) => Vec::new(),
|
||||
@@ -315,7 +374,8 @@ impl BlockEntity {
|
||||
| Self::Beacon(_)
|
||||
| Self::Lectern(_)
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_) => &[],
|
||||
| Self::Banner(_)
|
||||
| Self::Skull(_) => &[],
|
||||
Self::Crafter(c) => &c.items,
|
||||
Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
@@ -335,7 +395,8 @@ impl BlockEntity {
|
||||
| Self::Beacon(_)
|
||||
| Self::Lectern(_)
|
||||
| Self::Sculk(_)
|
||||
| Self::Banner(_) => &mut [],
|
||||
| Self::Banner(_)
|
||||
| Self::Skull(_) => &mut [],
|
||||
Self::Crafter(c) => &mut c.items,
|
||||
Self::CreakingHeart(_)
|
||||
| Self::Spawner(_)
|
||||
|
||||
@@ -0,0 +1,794 @@
|
||||
//! Server dialogs (`net.minecraft.server.dialog`): what `Dialog.DIRECT_CODEC`
|
||||
//! decodes from a `show_dialog` packet, the values its inputs hold, and the
|
||||
//! click event an action makes of them (`Action.createAction`).
|
||||
use crate::text::Text;
|
||||
use horizon_world::nbt::Tag;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// `CommonDialogData` and the type's own fields.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Dialog {
|
||||
pub kind: Kind,
|
||||
pub title: Text,
|
||||
pub external_title: Option<Text>,
|
||||
pub can_close_with_escape: bool,
|
||||
pub pause: bool,
|
||||
pub after_action: AfterAction,
|
||||
pub body: Vec<Body>,
|
||||
pub inputs: Vec<Input>,
|
||||
}
|
||||
|
||||
/// The dialog types (`DialogTypes`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Kind {
|
||||
/// `NoticeDialog`: one button, "OK" when the server names none.
|
||||
Notice(Button),
|
||||
Confirmation {
|
||||
yes: Button,
|
||||
no: Button,
|
||||
},
|
||||
MultiAction {
|
||||
actions: Vec<Button>,
|
||||
exit: Option<Button>,
|
||||
columns: i32,
|
||||
},
|
||||
ServerLinks {
|
||||
exit: Option<Button>,
|
||||
columns: i32,
|
||||
button_width: i32,
|
||||
},
|
||||
/// `DialogListDialog`: its dialogs as sent (ids, a tag or inline dialogs).
|
||||
DialogList {
|
||||
dialogs: Tag,
|
||||
exit: Option<Button>,
|
||||
columns: i32,
|
||||
button_width: i32,
|
||||
},
|
||||
}
|
||||
|
||||
/// `DialogAction`: the screen after an action runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AfterAction {
|
||||
Close,
|
||||
None,
|
||||
WaitForResponse,
|
||||
}
|
||||
|
||||
/// `ActionButton`: `CommonButtonData` and what it does.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Button {
|
||||
pub label: Text,
|
||||
pub tooltip: Option<Text>,
|
||||
pub width: i32,
|
||||
pub action: Option<Action>,
|
||||
}
|
||||
|
||||
/// `Action`: a fixed click event, or one made from the inputs' values.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Action {
|
||||
/// `StaticAction`: a click event as it is.
|
||||
Static(Click),
|
||||
/// `CommandTemplate`: a command with `$(key)` replaced by input values.
|
||||
RunCommand(String),
|
||||
/// `CustomAll`: a custom click event whose payload is `additions` plus
|
||||
/// every input's value under its key.
|
||||
Custom { id: String, additions: Option<Tag> },
|
||||
}
|
||||
|
||||
/// `ClickEvent`, the kinds a server may send (`isAllowedFromServer`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Click {
|
||||
OpenUrl(String),
|
||||
RunCommand(String),
|
||||
SuggestCommand(String),
|
||||
/// The dialog: an id of the `minecraft:dialog` registry or the dialog itself.
|
||||
ShowDialog(Tag),
|
||||
ChangePage(i32),
|
||||
CopyToClipboard(String),
|
||||
Custom {
|
||||
id: String,
|
||||
payload: Option<Tag>,
|
||||
},
|
||||
}
|
||||
|
||||
/// `DialogBody`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Body {
|
||||
/// `PlainMessage`: centred text wrapped to `width`.
|
||||
Message { contents: Text, width: i32 },
|
||||
/// `ItemBody`: the item as `ItemStackTemplate` sent it.
|
||||
Item {
|
||||
item: Tag,
|
||||
description: Option<(Text, i32)>,
|
||||
show_decorations: bool,
|
||||
show_tooltip: bool,
|
||||
width: i32,
|
||||
height: i32,
|
||||
},
|
||||
}
|
||||
|
||||
/// `Input`: the key its value goes by, and its control.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Input {
|
||||
pub key: String,
|
||||
pub control: Control,
|
||||
}
|
||||
|
||||
/// `InputControl`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Control {
|
||||
Text {
|
||||
width: i32,
|
||||
label: Text,
|
||||
label_visible: bool,
|
||||
initial: String,
|
||||
max_length: i32,
|
||||
/// `MultilineOptions`: the most lines and the height, when set.
|
||||
multiline: Option<(Option<i32>, Option<i32>)>,
|
||||
},
|
||||
Boolean {
|
||||
label: Text,
|
||||
initial: bool,
|
||||
on_true: String,
|
||||
on_false: String,
|
||||
},
|
||||
SingleOption {
|
||||
width: i32,
|
||||
/// Each option's id, its label and whether it is the initial one.
|
||||
options: Vec<(String, Option<Text>, bool)>,
|
||||
label: Text,
|
||||
label_visible: bool,
|
||||
},
|
||||
NumberRange {
|
||||
width: i32,
|
||||
label: Text,
|
||||
label_format: String,
|
||||
start: f32,
|
||||
end: f32,
|
||||
initial: Option<f32>,
|
||||
step: Option<f32>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What an input holds while the dialog is open.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum InputValue {
|
||||
Text(String),
|
||||
Bool(bool),
|
||||
/// The chosen option's index.
|
||||
Option(usize),
|
||||
/// The slider's position, 0 to 1.
|
||||
Slider(f32),
|
||||
}
|
||||
|
||||
fn text(t: &Tag) -> Text {
|
||||
crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t))
|
||||
}
|
||||
fn string(t: Option<&Tag>) -> Option<String> {
|
||||
match t? {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn number(t: Option<&Tag>) -> Option<f64> {
|
||||
Some(match t? {
|
||||
Tag::Byte(v) => f64::from(*v),
|
||||
Tag::Short(v) => f64::from(*v),
|
||||
Tag::Int(v) => f64::from(*v),
|
||||
Tag::Long(v) => *v as f64,
|
||||
Tag::Float(v) => f64::from(f32::from_bits(*v)),
|
||||
Tag::Double(v) => f64::from_bits(*v),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn int(t: &Tag, key: &str, default: i32) -> i32 {
|
||||
number(t.get(key)).map_or(default, |v| v as i32)
|
||||
}
|
||||
fn boolean(t: &Tag, key: &str, default: bool) -> bool {
|
||||
number(t.get(key)).map_or(default, |v| v != 0.0)
|
||||
}
|
||||
fn list(t: Option<&Tag>) -> &[Tag] {
|
||||
match t {
|
||||
Some(Tag::List(items)) => items,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
/// A registry name without its default namespace.
|
||||
fn path(id: &str) -> &str {
|
||||
id.strip_prefix("minecraft:").unwrap_or(id)
|
||||
}
|
||||
|
||||
impl Button {
|
||||
/// `ActionButton.CODEC`.
|
||||
fn parse(t: &Tag) -> Option<Self> {
|
||||
Some(Self {
|
||||
label: text(t.get("label")?),
|
||||
tooltip: t.get("tooltip").map(text),
|
||||
width: int(t, "width", 150),
|
||||
action: t.get("action").and_then(Action::parse),
|
||||
})
|
||||
}
|
||||
/// `NoticeDialog.DEFAULT_ACTION`.
|
||||
fn ok() -> Self {
|
||||
Self {
|
||||
label: Text::translate("gui.ok", &[]),
|
||||
tooltip: None,
|
||||
width: 150,
|
||||
action: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Click {
|
||||
/// `ClickEvent.CODEC`, from its `action` (a click event in a component)
|
||||
/// or `type` (an action) field.
|
||||
pub fn parse(t: &Tag, kind: &str) -> Option<Self> {
|
||||
let s = |key| string(t.get(key));
|
||||
Some(match path(kind) {
|
||||
"open_url" => Self::OpenUrl(s("url")?),
|
||||
"run_command" => Self::RunCommand(s("command")?),
|
||||
"suggest_command" => Self::SuggestCommand(s("command")?),
|
||||
"show_dialog" => Self::ShowDialog(t.get("dialog")?.clone()),
|
||||
"change_page" => Self::ChangePage(int(t, "page", 1)),
|
||||
"copy_to_clipboard" => Self::CopyToClipboard(s("value")?),
|
||||
"custom" => Self::Custom {
|
||||
id: s("id")?,
|
||||
payload: t.get("payload").cloned(),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Action {
|
||||
/// `Action.CODEC`, dispatched on `type`.
|
||||
fn parse(t: &Tag) -> Option<Self> {
|
||||
let kind = string(t.get("type"))?;
|
||||
Some(match path(&kind) {
|
||||
"dynamic/run_command" => Self::RunCommand(string(t.get("template"))?),
|
||||
"dynamic/custom" => Self::Custom {
|
||||
id: string(t.get("id"))?,
|
||||
additions: t.get("additions").cloned(),
|
||||
},
|
||||
other => Self::Static(Click::parse(t, other)?),
|
||||
})
|
||||
}
|
||||
/// `createAction`: the click event, given each input's key, control and value.
|
||||
pub fn click(&self, inputs: &[Input], values: &[InputValue]) -> Option<Click> {
|
||||
let values = || inputs.iter().zip(values);
|
||||
Some(match self {
|
||||
Self::Static(click) => click.clone(),
|
||||
Self::RunCommand(template) => Click::RunCommand(substitute(template, &|key| {
|
||||
values()
|
||||
.find(|(i, _)| i.key == key)
|
||||
.map(|(i, v)| i.control.substitution(v))
|
||||
})),
|
||||
Self::Custom { id, additions } => {
|
||||
let mut tag = match additions {
|
||||
Some(t @ Tag::Compound(_)) => t.clone(),
|
||||
_ => Tag::Compound(Default::default()),
|
||||
};
|
||||
for (input, value) in values() {
|
||||
if let Tag::Compound(map) = &mut tag {
|
||||
map.insert(input.key.as_str().into(), input.control.tag(value));
|
||||
}
|
||||
}
|
||||
Click::Custom {
|
||||
id: id.clone(),
|
||||
payload: Some(tag),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `ParsedTemplate.instantiate`: each `$(key)` replaced by its value, or by
|
||||
/// nothing for a key no input has.
|
||||
fn substitute(template: &str, value: &dyn Fn(&str) -> Option<String>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = template;
|
||||
while let Some(at) = rest.find("$(") {
|
||||
let Some(end) = rest[at..].find(')') else {
|
||||
break;
|
||||
};
|
||||
out.push_str(&rest[..at]);
|
||||
out.push_str(&value(&rest[at + 2..at + end]).unwrap_or_default());
|
||||
rest = &rest[at + end + 1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// `StringTag.escapeWithoutQuotes`.
|
||||
fn escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' | '\'' | '\\' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
'\u{8}' => out.push_str("\\b"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\u{c}' => out.push_str("\\f"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
c if c < ' ' => out.push_str(&format!("\\x{:02x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Control {
|
||||
/// `InputControl.MAP_CODEC`, dispatched on `type`.
|
||||
fn parse(t: &Tag) -> Option<Self> {
|
||||
let label = || t.get("label").map(text);
|
||||
Some(match path(&string(t.get("type"))?) {
|
||||
"text" => Self::Text {
|
||||
width: int(t, "width", 200),
|
||||
label: label()?,
|
||||
label_visible: boolean(t, "label_visible", true),
|
||||
initial: string(t.get("initial")).unwrap_or_default(),
|
||||
max_length: int(t, "max_length", 32),
|
||||
multiline: t.get("multiline").map(|m| {
|
||||
let get = |key| number(m.get(key)).map(|v| v as i32);
|
||||
(get("max_lines"), get("height"))
|
||||
}),
|
||||
},
|
||||
"boolean" => Self::Boolean {
|
||||
label: label()?,
|
||||
initial: boolean(t, "initial", false),
|
||||
on_true: string(t.get("on_true")).unwrap_or_else(|| "true".into()),
|
||||
on_false: string(t.get("on_false")).unwrap_or_else(|| "false".into()),
|
||||
},
|
||||
"single_option" => Self::SingleOption {
|
||||
width: int(t, "width", 200),
|
||||
// SingleOptionInput.Entry.CODEC: a full entry or just its id.
|
||||
options: list(t.get("options"))
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
Tag::String(id) => Some((id.to_string_lossy(), None, false)),
|
||||
o => Some((
|
||||
string(o.get("id"))?,
|
||||
o.get("display").map(text),
|
||||
boolean(o, "initial", false),
|
||||
)),
|
||||
})
|
||||
.collect(),
|
||||
label: label()?,
|
||||
label_visible: boolean(t, "label_visible", true),
|
||||
},
|
||||
"number_range" => {
|
||||
let float = |key| number(t.get(key)).map(|v| v as f32);
|
||||
Self::NumberRange {
|
||||
width: int(t, "width", 200),
|
||||
label: label()?,
|
||||
label_format: string(t.get("label_format"))
|
||||
.unwrap_or_else(|| "options.generic_value".into()),
|
||||
start: float("start")?,
|
||||
end: float("end")?,
|
||||
initial: float("initial"),
|
||||
step: float("step"),
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// The value it starts with.
|
||||
pub fn initial(&self) -> InputValue {
|
||||
match self {
|
||||
Self::Text { initial, .. } => InputValue::Text(initial.clone()),
|
||||
Self::Boolean { initial, .. } => InputValue::Bool(*initial),
|
||||
Self::SingleOption { options, .. } => {
|
||||
InputValue::Option(options.iter().position(|o| o.2).unwrap_or(0))
|
||||
}
|
||||
Self::NumberRange {
|
||||
start,
|
||||
end,
|
||||
initial,
|
||||
..
|
||||
} => InputValue::Slider(to_slider(
|
||||
initial.unwrap_or((start + end) / 2.0),
|
||||
*start,
|
||||
*end,
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// `ValueGetter.asTemplateSubstitution`.
|
||||
pub fn substitution(&self, value: &InputValue) -> String {
|
||||
match (self, value) {
|
||||
(Self::Text { .. }, InputValue::Text(s)) => escape(s),
|
||||
(
|
||||
Self::Boolean {
|
||||
on_true, on_false, ..
|
||||
},
|
||||
InputValue::Bool(b),
|
||||
) => if *b { on_true } else { on_false }.clone(),
|
||||
(Self::SingleOption { options, .. }, InputValue::Option(i)) => {
|
||||
options.get(*i).map(|o| o.0.clone()).unwrap_or_default()
|
||||
}
|
||||
(Self::NumberRange { .. }, InputValue::Slider(_)) => {
|
||||
number_string(self.scaled(value).unwrap_or(0.0))
|
||||
}
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
/// `ValueGetter.asTag`.
|
||||
pub fn tag(&self, value: &InputValue) -> Tag {
|
||||
match (self, value) {
|
||||
(Self::Boolean { .. }, InputValue::Bool(b)) => Tag::Byte(i8::from(*b)),
|
||||
(Self::NumberRange { .. }, _) => {
|
||||
Tag::Float(self.scaled(value).unwrap_or(0.0).to_bits())
|
||||
}
|
||||
(Self::Text { .. }, InputValue::Text(s)) => Tag::String(s.as_str().into()),
|
||||
_ => Tag::String(self.substitution(value).as_str().into()),
|
||||
}
|
||||
}
|
||||
/// `RangeInfo.computeScaledValue`: a number range's value at its slider position.
|
||||
pub fn scaled(&self, value: &InputValue) -> Option<f32> {
|
||||
let (
|
||||
Self::NumberRange {
|
||||
start,
|
||||
end,
|
||||
initial,
|
||||
step,
|
||||
..
|
||||
},
|
||||
InputValue::Slider(slider),
|
||||
) = (self, value)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let (start, end) = (*start, *end);
|
||||
let in_range = start + slider * (end - start);
|
||||
let Some(step) = step else {
|
||||
return Some(in_range);
|
||||
};
|
||||
let first = initial.unwrap_or((start + end) / 2.0);
|
||||
// Math.round: half up.
|
||||
let steps = ((in_range - first) / step + 0.5).floor() as i32;
|
||||
let result = first + steps as f32 * step;
|
||||
let position = to_slider(result, start, end);
|
||||
if (0.0..=1.0).contains(&position) {
|
||||
return Some(result);
|
||||
}
|
||||
Some(first + (steps - steps.signum()) as f32 * step)
|
||||
}
|
||||
}
|
||||
|
||||
/// `RangeInfo.scaledValueToSlider`.
|
||||
fn to_slider(value: f32, start: f32, end: f32) -> f32 {
|
||||
if start == end {
|
||||
0.5
|
||||
} else {
|
||||
(value - start) / (end - start)
|
||||
}
|
||||
}
|
||||
|
||||
/// `SliderImpl.valueToString`: whole numbers without a fraction, the rest as
|
||||
/// Java's `Float.toString`.
|
||||
pub fn number_string(v: f32) -> String {
|
||||
if v == (v as i32) as f32 {
|
||||
(v as i32).to_string()
|
||||
} else {
|
||||
crate::snbt::java_float(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl Body {
|
||||
/// `DialogBody.DIALOG_BODY_CODEC`.
|
||||
fn parse(t: &Tag) -> Option<Self> {
|
||||
let message = |t: &Tag| -> Option<(Text, i32)> {
|
||||
// PlainMessage.CODEC: the full form or just its contents.
|
||||
match t {
|
||||
Tag::Compound(_) if t.get("contents").is_some() => {
|
||||
Some((text(t.get("contents")?), int(t, "width", 200)))
|
||||
}
|
||||
t => Some((text(t), 200)),
|
||||
}
|
||||
};
|
||||
Some(match path(&string(t.get("type"))?) {
|
||||
"plain_message" => {
|
||||
let (contents, width) = message(t)?;
|
||||
Self::Message { contents, width }
|
||||
}
|
||||
"item" => Self::Item {
|
||||
item: t.get("item")?.clone(),
|
||||
description: t.get("description").and_then(message),
|
||||
show_decorations: boolean(t, "show_decorations", true),
|
||||
show_tooltip: boolean(t, "show_tooltip", true),
|
||||
width: int(t, "width", 16),
|
||||
height: int(t, "height", 16),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Dialog {
|
||||
/// `Dialog.DIRECT_CODEC`; `None` for a type or field it can't read
|
||||
/// (vanilla fails the whole packet then).
|
||||
pub fn parse(t: &Tag) -> Option<Self> {
|
||||
let button = |key: &str| t.get(key).and_then(Button::parse);
|
||||
let kind = match path(&string(t.get("type"))?) {
|
||||
"notice" => Kind::Notice(match t.get("action") {
|
||||
Some(b) => Button::parse(b)?,
|
||||
None => Button::ok(),
|
||||
}),
|
||||
"confirmation" => Kind::Confirmation {
|
||||
yes: button("yes")?,
|
||||
no: button("no")?,
|
||||
},
|
||||
"multi_action" => Kind::MultiAction {
|
||||
actions: list(t.get("actions"))
|
||||
.iter()
|
||||
.map(Button::parse)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.filter(|a| !a.is_empty())?,
|
||||
exit: button("exit_action"),
|
||||
columns: int(t, "columns", 2),
|
||||
},
|
||||
"server_links" => Kind::ServerLinks {
|
||||
exit: button("exit_action"),
|
||||
columns: int(t, "columns", 2),
|
||||
button_width: int(t, "button_width", 150),
|
||||
},
|
||||
"dialog_list" => Kind::DialogList {
|
||||
dialogs: t.get("dialogs")?.clone(),
|
||||
exit: button("exit_action"),
|
||||
columns: int(t, "columns", 2),
|
||||
button_width: int(t, "button_width", 150),
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
// DialogBody.COMPACT_LIST_CODEC: one body, or a list of them.
|
||||
let body = match t.get("body") {
|
||||
Some(Tag::List(items)) => items.iter().filter_map(Body::parse).collect(),
|
||||
Some(one) => Body::parse(one).into_iter().collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let inputs = list(t.get("inputs"))
|
||||
.iter()
|
||||
.filter_map(|i| {
|
||||
Some(Input {
|
||||
key: string(i.get("key"))?,
|
||||
control: Control::parse(i)?,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(Self {
|
||||
kind,
|
||||
title: text(t.get("title")?),
|
||||
external_title: t.get("external_title").map(text),
|
||||
can_close_with_escape: boolean(t, "can_close_with_escape", true),
|
||||
pause: boolean(t, "pause", true),
|
||||
after_action: match string(t.get("after_action")).as_deref() {
|
||||
Some("none") => AfterAction::None,
|
||||
Some("wait_for_response") => AfterAction::WaitForResponse,
|
||||
_ => AfterAction::Close,
|
||||
},
|
||||
body,
|
||||
inputs,
|
||||
})
|
||||
}
|
||||
/// `onCancel`: what Escape (or closing it) does.
|
||||
pub fn on_cancel(&self) -> Option<&Action> {
|
||||
match &self.kind {
|
||||
Kind::Notice(b) => b.action.as_ref(),
|
||||
Kind::Confirmation { no, .. } => no.action.as_ref(),
|
||||
Kind::MultiAction { exit, .. }
|
||||
| Kind::ServerLinks { exit, .. }
|
||||
| Kind::DialogList { exit, .. } => exit.as_ref().and_then(|b| b.action.as_ref()),
|
||||
}
|
||||
}
|
||||
/// The buttons it draws, in order: the list, then the footer's.
|
||||
pub fn buttons(&self) -> Vec<&Button> {
|
||||
match &self.kind {
|
||||
Kind::Notice(b) => vec![b],
|
||||
Kind::Confirmation { yes, no } => vec![yes, no],
|
||||
Kind::MultiAction { actions, exit, .. } => actions.iter().chain(exit).collect(),
|
||||
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => exit.iter().collect(),
|
||||
}
|
||||
}
|
||||
/// What `status` reports of it.
|
||||
pub fn json(&self, values: &[InputValue]) -> Value {
|
||||
let kind = match &self.kind {
|
||||
Kind::Notice(_) => "notice",
|
||||
Kind::Confirmation { .. } => "confirmation",
|
||||
Kind::MultiAction { .. } => "multi_action",
|
||||
Kind::ServerLinks { .. } => "server_links",
|
||||
Kind::DialogList { .. } => "dialog_list",
|
||||
};
|
||||
let inputs: Vec<Value> = self
|
||||
.inputs
|
||||
.iter()
|
||||
.zip(values)
|
||||
.map(|(i, v)| {
|
||||
let kind = match i.control {
|
||||
Control::Text { .. } => "text",
|
||||
Control::Boolean { .. } => "boolean",
|
||||
Control::SingleOption { .. } => "single_option",
|
||||
Control::NumberRange { .. } => "number_range",
|
||||
};
|
||||
json!({"key": i.key, "type": kind, "value": i.control.substitution(v)})
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"type": kind,
|
||||
"title": self.title.plain(),
|
||||
"body": self.body.iter().map(|b| match b {
|
||||
Body::Message { contents, .. } => contents.plain(),
|
||||
Body::Item { item, .. } => string(item.get("id")).unwrap_or_default(),
|
||||
}).collect::<Vec<_>>(),
|
||||
"inputs": inputs,
|
||||
"buttons": self.buttons().iter().map(|b| b.label.plain()).collect::<Vec<_>>(),
|
||||
"can_close_with_escape": self.can_close_with_escape,
|
||||
"after_action": match self.after_action {
|
||||
AfterAction::Close => "close",
|
||||
AfterAction::None => "none",
|
||||
AfterAction::WaitForResponse => "wait_for_response",
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn s(v: &str) -> Tag {
|
||||
Tag::String(v.into())
|
||||
}
|
||||
|
||||
/// The register dialog AuthMe 6 sends in configuration (the shape its
|
||||
/// `show_dialog` packet has on the test bed).
|
||||
fn register() -> Tag {
|
||||
Tag::compound([
|
||||
("type", s("minecraft:multi_action")),
|
||||
("title", s("Register")),
|
||||
("can_close_with_escape", Tag::Byte(0)),
|
||||
("after_action", s("wait_for_response")),
|
||||
(
|
||||
"body",
|
||||
Tag::compound([
|
||||
("type", s("minecraft:plain_message")),
|
||||
("contents", s("Choose a password")),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"inputs",
|
||||
Tag::List(vec![Tag::compound([
|
||||
("type", s("minecraft:text")),
|
||||
("key", s("password")),
|
||||
("label", s("Password")),
|
||||
])]),
|
||||
),
|
||||
(
|
||||
"actions",
|
||||
Tag::List(vec![
|
||||
Tag::compound([
|
||||
("label", s("Register")),
|
||||
(
|
||||
"action",
|
||||
Tag::compound([
|
||||
("type", s("minecraft:dynamic/custom")),
|
||||
("id", s("authme:prejoin-register/submit")),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
Tag::compound([
|
||||
("label", s("Cancel")),
|
||||
(
|
||||
"action",
|
||||
Tag::compound([
|
||||
("type", s("minecraft:dynamic/run_command")),
|
||||
("template", s("say $(password) $(missing)!")),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_a_multi_action_dialog_with_defaults() {
|
||||
let d = Dialog::parse(®ister()).unwrap();
|
||||
assert_eq!(d.title.plain(), "Register");
|
||||
assert!(!d.can_close_with_escape);
|
||||
assert!(d.pause);
|
||||
assert_eq!(d.after_action, AfterAction::WaitForResponse);
|
||||
assert!(matches!(&d.body[..], [Body::Message { width: 200, .. }]));
|
||||
let Kind::MultiAction {
|
||||
actions,
|
||||
exit,
|
||||
columns,
|
||||
} = &d.kind
|
||||
else {
|
||||
panic!("{:?}", d.kind)
|
||||
};
|
||||
assert_eq!((actions.len(), exit.is_none(), *columns), (2, true, 2));
|
||||
assert_eq!(actions[0].width, 150);
|
||||
assert!(d.on_cancel().is_none());
|
||||
let [
|
||||
Input {
|
||||
key,
|
||||
control:
|
||||
Control::Text {
|
||||
max_length: 32,
|
||||
width: 200,
|
||||
..
|
||||
},
|
||||
},
|
||||
] = &d.inputs[..]
|
||||
else {
|
||||
panic!("{:?}", d.inputs)
|
||||
};
|
||||
assert_eq!(key, "password");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actions_carry_the_input_values() {
|
||||
let d = Dialog::parse(®ister()).unwrap();
|
||||
let values = [InputValue::Text("p\"w".into())];
|
||||
let Kind::MultiAction { actions, .. } = &d.kind else {
|
||||
unreachable!()
|
||||
};
|
||||
let custom = actions[0]
|
||||
.action
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.click(&d.inputs, &values);
|
||||
assert_eq!(
|
||||
custom,
|
||||
Some(Click::Custom {
|
||||
id: "authme:prejoin-register/submit".into(),
|
||||
payload: Some(Tag::compound([("password", s("p\"w"))])),
|
||||
})
|
||||
);
|
||||
// The template escapes the text; a key no input has becomes nothing.
|
||||
let command = actions[1]
|
||||
.action
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.click(&d.inputs, &values);
|
||||
assert_eq!(command, Some(Click::RunCommand("say p\\\"w !".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_notice_without_an_action_has_ok() {
|
||||
let d = Dialog::parse(&Tag::compound([("type", s("notice")), ("title", s("Hi"))])).unwrap();
|
||||
let Kind::Notice(b) = &d.kind else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(b.label, Text::translate("gui.ok", &[]));
|
||||
// Without a title, or with an unknown type, there is no dialog.
|
||||
assert!(Dialog::parse(&Tag::compound([("type", s("notice"))])).is_none());
|
||||
assert!(Dialog::parse(&Tag::compound([("type", s("x")), ("title", s("Hi"))])).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_ranges_snap_to_their_step() {
|
||||
let mut range = Control::NumberRange {
|
||||
width: 200,
|
||||
label: Text::literal("n"),
|
||||
label_format: "options.generic_value".into(),
|
||||
start: 0.0,
|
||||
end: 10.0,
|
||||
initial: Some(4.0),
|
||||
step: Some(3.0),
|
||||
};
|
||||
assert_eq!(range.initial(), InputValue::Slider(0.4));
|
||||
assert_eq!(range.scaled(&InputValue::Slider(0.62)), Some(7.0));
|
||||
assert_eq!(range.scaled(&InputValue::Slider(1.0)), Some(10.0));
|
||||
let Control::NumberRange { step, .. } = &mut range else {
|
||||
unreachable!()
|
||||
};
|
||||
*step = Some(4.0);
|
||||
// 12 is out of range: one step less.
|
||||
assert_eq!(range.scaled(&InputValue::Slider(1.0)), Some(8.0));
|
||||
assert_eq!(range.substitution(&InputValue::Slider(0.0)), "0");
|
||||
assert_eq!(number_string(2.5), "2.5");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! `DialogScreen` and its kinds (`SimpleDialogScreen`, `MultiButtonDialogScreen`):
|
||||
//! where a server dialog's title, body and buttons go in a
|
||||
//! `HeaderAndFooterLayout` (a 33 high header, the body in a `ScrollableLayout`,
|
||||
//! the footer), and the `WaitingForResponseScreen` an answer can leave open.
|
||||
use crate::{
|
||||
dialog::{Body, Dialog, Kind},
|
||||
font::Font,
|
||||
text::Text,
|
||||
};
|
||||
|
||||
/// `HeaderAndFooterLayout.DEFAULT_HEADER_AND_FOOTER_HEIGHT`.
|
||||
const BAR: f32 = 33.0;
|
||||
/// `DialogScreen.WARNING_BUTTON_SPRITES`: normal, disabled, highlighted.
|
||||
pub const WARNING_SPRITES: [&str; 3] = [
|
||||
"gui/sprites/dialog/warning_button",
|
||||
"gui/sprites/dialog/warning_button_disabled",
|
||||
"gui/sprites/dialog/warning_button_highlighted",
|
||||
];
|
||||
|
||||
/// One drawn piece; `y` is from the top of the body (before it scrolls) for
|
||||
/// the body's parts, from the top of the screen for the footer's.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Part {
|
||||
/// A line of text and where it starts.
|
||||
Line(Text, f32, f32),
|
||||
/// A button of `Dialog::buttons`.
|
||||
Button { index: usize, rect: [f32; 4] },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Layout {
|
||||
/// The title and where it is drawn.
|
||||
pub title: (f32, f32),
|
||||
pub warning: [f32; 4],
|
||||
/// The body's visible area (`ScrollableLayout`'s container): x, y, w, h.
|
||||
pub area: [f32; 4],
|
||||
/// The body's full height: more than the area's scrolls.
|
||||
pub content: f32,
|
||||
pub body: Vec<Part>,
|
||||
pub footer: Vec<Part>,
|
||||
}
|
||||
|
||||
/// A laid-out element of a `LinearLayout` before it is placed.
|
||||
struct Element {
|
||||
w: f32,
|
||||
h: f32,
|
||||
parts: Vec<Part>,
|
||||
}
|
||||
impl Element {
|
||||
/// Its parts moved to `(x, y)`.
|
||||
fn at(self, x: f32, y: f32) -> impl Iterator<Item = Part> {
|
||||
self.parts.into_iter().map(move |p| match p {
|
||||
Part::Line(t, px, py) => Part::Line(t, px + x, py + y),
|
||||
Part::Button { index, rect } => Part::Button {
|
||||
index,
|
||||
rect: shift(rect, x, y),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
fn shift([x, y, w, h]: [f32; 4], dx: f32, dy: f32) -> [f32; 4] {
|
||||
[x + dx, y + dy, w, h]
|
||||
}
|
||||
/// `FrameLayout.alignInDimension` at 0.5: the offset that centres `inner`.
|
||||
fn centre(outer: f32, inner: f32) -> f32 {
|
||||
((outer - inner) * 0.5).trunc()
|
||||
}
|
||||
|
||||
/// `FocusableTextWidget` with the body's settings: `width` wide, the text
|
||||
/// wrapped to `width - 8` and centred, 4 of padding all round.
|
||||
fn message(font: &Font, contents: &Text, width: f32) -> Element {
|
||||
let lines = font.split_lines(contents, width - 8.0);
|
||||
let mid = (width / 2.0).trunc();
|
||||
let parts = lines
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (line, _))| {
|
||||
let x = mid - (font.width_text(&line) / 2.0).trunc();
|
||||
Part::Line(line, x, 4.0 + 9.0 * i as f32)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Element {
|
||||
w: width,
|
||||
h: 9.0 * parts.len() as f32 + 8.0,
|
||||
parts,
|
||||
}
|
||||
}
|
||||
|
||||
/// `DialogScreen.packControlsIntoColumns`: full rows in a grid 2 apart, what
|
||||
/// is left in a centred row under them.
|
||||
fn columns(widths: &[f32], columns: usize, first: usize) -> Element {
|
||||
let columns = columns.max(1);
|
||||
let full = widths.len() / columns * columns;
|
||||
let row_width = |ws: &[f32]| ws.iter().sum::<f32>() + 2.0 * (ws.len().max(1) - 1) as f32;
|
||||
let mut col = vec![0.0f32; columns];
|
||||
for (i, w) in widths[..full].iter().enumerate() {
|
||||
col[i % columns] = col[i % columns].max(*w);
|
||||
}
|
||||
let last = &widths[full..];
|
||||
if !last.is_empty() {
|
||||
// GridLayout spreads a cell over every column it spans (Divisor).
|
||||
let spread = row_width(last) - 2.0 * (columns - 1) as f32;
|
||||
let (each, extra) = ((spread / columns as f32).floor(), spread % columns as f32);
|
||||
for (c, w) in col.iter_mut().enumerate() {
|
||||
*w = w.max(each + f32::from(u8::from((c as f32) < extra)));
|
||||
}
|
||||
}
|
||||
let x_of = |c: usize| col[..c].iter().sum::<f32>() + 2.0 * c as f32;
|
||||
let mut parts = Vec::new();
|
||||
for (i, w) in widths[..full].iter().enumerate() {
|
||||
let (r, c) = (i / columns, i % columns);
|
||||
parts.push(Part::Button {
|
||||
index: first + i,
|
||||
rect: [x_of(c) + centre(col[c], *w), 22.0 * r as f32, *w, 20.0],
|
||||
});
|
||||
}
|
||||
let width = x_of(columns - 1) + col[columns - 1];
|
||||
if !last.is_empty() {
|
||||
let y = 22.0 * (full / columns) as f32;
|
||||
let mut x = centre(width, row_width(last));
|
||||
for (i, w) in last.iter().enumerate() {
|
||||
parts.push(Part::Button {
|
||||
index: first + full + i,
|
||||
rect: [x, y, *w, 20.0],
|
||||
});
|
||||
x += w + 2.0;
|
||||
}
|
||||
}
|
||||
let rows = full / columns + usize::from(!last.is_empty());
|
||||
Element {
|
||||
w: width,
|
||||
h: (22.0 * rows as f32 - 2.0).max(0.0),
|
||||
parts,
|
||||
}
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// `DialogScreen.init` and `repositionElements` on a `w` by `h` screen.
|
||||
pub fn new(dialog: &Dialog, font: &Font, (w, h): (f32, f32)) -> Self {
|
||||
// The header: the title, 10 right of it the warning button, both
|
||||
// centred together.
|
||||
let tw = font.width_text(&dialog.title);
|
||||
let (hx, hy) = (centre(w, tw + 30.0), centre(BAR, 20.0));
|
||||
let title = (hx, hy + centre(20.0, 9.0));
|
||||
let warning = [hx + tw + 10.0, hy, 20.0, 20.0];
|
||||
|
||||
let mut elements: Vec<Element> = dialog
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| match b {
|
||||
Body::Message { contents, width } => Some(message(font, contents, *width as f32)),
|
||||
Body::Item { .. } => None,
|
||||
})
|
||||
.collect();
|
||||
let buttons = dialog.buttons();
|
||||
let (listed, footer_buttons, footer_h) = match &dialog.kind {
|
||||
Kind::MultiAction {
|
||||
actions,
|
||||
exit,
|
||||
columns: n,
|
||||
} => {
|
||||
let widths: Vec<f32> = actions.iter().map(|b| b.width as f32).collect();
|
||||
elements.push(columns(&widths, *n as usize, 0));
|
||||
// ButtonListDialogScreen: the exit button in the footer, else a 5 high one.
|
||||
let footer = exit.as_ref().map(|_| actions.len()).into_iter().collect();
|
||||
(
|
||||
actions.len(),
|
||||
footer,
|
||||
if exit.is_some() { BAR } else { 5.0 },
|
||||
)
|
||||
}
|
||||
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => {
|
||||
let footer = exit.as_ref().map(|_| 0).into_iter().collect();
|
||||
(0, footer, if exit.is_some() { BAR } else { 5.0 })
|
||||
}
|
||||
// SimpleDialogScreen: the buttons side by side, 8 apart.
|
||||
Kind::Notice(_) | Kind::Confirmation { .. } => {
|
||||
(0, (0..buttons.len()).collect::<Vec<_>>(), BAR)
|
||||
}
|
||||
};
|
||||
debug_assert!(listed + footer_buttons.len() <= buttons.len());
|
||||
|
||||
// The body: a column 10 apart, each element centred in it.
|
||||
let body_w = elements.iter().map(|e| e.w).fold(0.0, f32::max);
|
||||
let content = elements.iter().map(|e| e.h).sum::<f32>()
|
||||
+ 10.0 * elements.len().saturating_sub(1) as f32;
|
||||
// ScrollableLayout: 10 each side for the scrollbar (ReserveStrategy.BOTH),
|
||||
// no higher than what the header and footer leave.
|
||||
let area_w = body_w + 20.0;
|
||||
let area_h = content.min(h - BAR - footer_h).max(0.0);
|
||||
let area_y = (BAR + 30.0).min(h - footer_h - area_h);
|
||||
let area_x = centre(w, area_w);
|
||||
let mut body = Vec::new();
|
||||
let mut y = 0.0;
|
||||
for e in elements {
|
||||
let (x, eh) = (area_x + 10.0 + centre(body_w, e.w), e.h);
|
||||
body.extend(e.at(x, y));
|
||||
y += eh + 10.0;
|
||||
}
|
||||
|
||||
let widths: Vec<f32> = footer_buttons
|
||||
.iter()
|
||||
.map(|&i| buttons[i].width as f32)
|
||||
.collect();
|
||||
let row = widths.iter().sum::<f32>() + 8.0 * widths.len().saturating_sub(1) as f32;
|
||||
let (mut x, fy) = (centre(w, row), h - footer_h + centre(footer_h, 20.0));
|
||||
let mut footer = Vec::new();
|
||||
for (&i, bw) in footer_buttons.iter().zip(&widths) {
|
||||
footer.push(Part::Button {
|
||||
index: i,
|
||||
rect: [x, fy, *bw, 20.0],
|
||||
});
|
||||
x += bw + 8.0;
|
||||
}
|
||||
Self {
|
||||
title,
|
||||
warning: Self::in_bounds(warning, w, h),
|
||||
area: [area_x, area_y, area_w, area_h],
|
||||
content,
|
||||
body,
|
||||
footer,
|
||||
}
|
||||
}
|
||||
/// `makeSureWarningButtonIsInBounds`.
|
||||
fn in_bounds(r: [f32; 4], w: f32, h: f32) -> [f32; 4] {
|
||||
if r[0] < 0.0 || r[1] < 0.0 || r[0] > w - 20.0 || r[1] > h - 20.0 {
|
||||
[(w - 40.0).max(0.0), 5.0f32.min(h), 20.0, 20.0]
|
||||
} else {
|
||||
r
|
||||
}
|
||||
}
|
||||
/// Every part where it is drawn with the body scrolled by `scroll`, and
|
||||
/// whether it is in the body (clipped to its area).
|
||||
pub fn placed(&self, scroll: f32) -> impl Iterator<Item = (Part, bool)> + '_ {
|
||||
let dy = self.area[1] - scroll;
|
||||
let body = self.body.iter().map(move |p| {
|
||||
let p = match p.clone() {
|
||||
Part::Line(t, x, y) => Part::Line(t, x, y + dy),
|
||||
Part::Button { index, rect } => Part::Button {
|
||||
index,
|
||||
rect: shift(rect, 0.0, dy),
|
||||
},
|
||||
};
|
||||
(p, true)
|
||||
});
|
||||
body.chain(self.footer.iter().map(|p| (p.clone(), false)))
|
||||
}
|
||||
}
|
||||
|
||||
/// `WaitingForResponseScreen`: its Back button's label after `ticks`, and
|
||||
/// whether it shows and works (it shows after a second, works after five).
|
||||
pub fn waiting_button(ticks: u32) -> (Text, bool, bool) {
|
||||
let seconds = (ticks / 20).min(5);
|
||||
let label = match seconds {
|
||||
0 => Text::literal(""),
|
||||
5 => Text::translate("gui.back", &[]),
|
||||
s => Text::translate(
|
||||
"gui.waitingForResponse.button.inactive",
|
||||
&[Text::literal((5 - s).to_string())],
|
||||
),
|
||||
};
|
||||
(label, seconds >= 1, seconds == 5)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn grids_pack_full_rows_and_centre_the_rest() {
|
||||
// AuthMe's two buttons: one row, 2 apart.
|
||||
let two = columns(&[150.0, 150.0], 2, 0);
|
||||
assert_eq!((two.w, two.h), (302.0, 20.0));
|
||||
// Three in two columns: the third alone, centred under them.
|
||||
let three = columns(&[150.0, 150.0, 150.0], 2, 0);
|
||||
assert_eq!((three.w, three.h), (302.0, 42.0));
|
||||
assert_eq!(
|
||||
three.parts[2],
|
||||
Part::Button {
|
||||
index: 2,
|
||||
rect: [76.0, 22.0, 150.0, 20.0]
|
||||
}
|
||||
);
|
||||
// One in two columns spreads over both.
|
||||
let one = columns(&[100.0], 2, 0);
|
||||
assert_eq!(one.w, 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_waiting_screens_button_counts_down() {
|
||||
assert!(!waiting_button(0).1);
|
||||
assert_eq!(
|
||||
waiting_button(20).0,
|
||||
Text::translate(
|
||||
"gui.waitingForResponse.button.inactive",
|
||||
&[Text::literal("4")]
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
waiting_button(100),
|
||||
(Text::translate("gui.back", &[]), true, true)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,11 @@ impl Cost {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Enchantment {
|
||||
pub id: Arc<str>,
|
||||
/// The name the pinned English map gave at load: the fallback for a
|
||||
/// language that has no entry for the key below.
|
||||
pub description: String,
|
||||
/// `description`'s translation key (`enchantment.minecraft.<name>`).
|
||||
pub description_key: String,
|
||||
pub max_level: u32,
|
||||
pub weight: u32,
|
||||
pub anvil_cost: u32,
|
||||
@@ -224,6 +228,7 @@ impl Enchantments {
|
||||
.get(key)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| id.trim_start_matches("minecraft:").replace('_', " ")),
|
||||
description_key: key.to_owned(),
|
||||
max_level: v["max_level"].as_u64().unwrap_or(1) as u32,
|
||||
weight: v["weight"].as_u64().unwrap_or(1) as u32,
|
||||
anvil_cost: v["anvil_cost"].as_u64().unwrap_or(0) as u32,
|
||||
@@ -329,16 +334,26 @@ impl Enchantments {
|
||||
}
|
||||
/// `Enchantment.getFullname` as plain text and whether it is a curse (red).
|
||||
pub fn full_name(&self, id: &str, level: u32) -> (String, bool) {
|
||||
let language = crate::lang::current();
|
||||
self.full_name_in(language.as_deref(), id, level)
|
||||
}
|
||||
/// `full_name` against `language`; `None` (no language loaded: a
|
||||
/// dedicated server, the probes) keeps the English names loaded above.
|
||||
pub fn full_name_in(
|
||||
&self,
|
||||
language: Option<&crate::lang::Language>,
|
||||
id: &str,
|
||||
level: u32,
|
||||
) -> (String, bool) {
|
||||
let tr = |key: &str| language.and_then(|l| l.get(key).map(str::to_owned));
|
||||
let Some(e) = self.get(id) else {
|
||||
return (format!("{id} {}", level_name(level)), false);
|
||||
};
|
||||
let mut name = e.description.clone();
|
||||
let mut name = tr(&e.description_key).unwrap_or_else(|| e.description.clone());
|
||||
if level != 1 || e.max_level != 1 {
|
||||
name.push(' ');
|
||||
name.push_str(
|
||||
self.lang
|
||||
.get(&format!("enchantment.level.{level}"))
|
||||
.map_or(&level_name(level), |s| s),
|
||||
&tr(&format!("enchantment.level.{level}")).unwrap_or_else(|| level_name(level)),
|
||||
);
|
||||
}
|
||||
(name, self.is_curse(id))
|
||||
@@ -771,7 +786,7 @@ pub(crate) mod tests {
|
||||
let defs = [
|
||||
(
|
||||
"minecraft:sharpness",
|
||||
json!({"anvil_cost":1,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}),
|
||||
json!({"anvil_cost":1,"description":{"translate":"enchantment.minecraft.sharpness"},"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}),
|
||||
),
|
||||
(
|
||||
"minecraft:smite",
|
||||
@@ -795,6 +810,7 @@ pub(crate) mod tests {
|
||||
.map(|(id, v)| Enchantment {
|
||||
id: Arc::from(*id),
|
||||
description: id.trim_start_matches("minecraft:").into(),
|
||||
description_key: v["description"]["translate"].as_str().unwrap_or("").into(),
|
||||
max_level: v["max_level"].as_u64().unwrap() as u32,
|
||||
weight: v["weight"].as_u64().unwrap() as u32,
|
||||
anvil_cost: v["anvil_cost"].as_u64().unwrap() as u32,
|
||||
@@ -1088,4 +1104,33 @@ pub(crate) mod tests {
|
||||
assert!(!e.compatible("minecraft:sharpness", "minecraft:smite"));
|
||||
assert!(e.compatible("minecraft:sharpness", "minecraft:unbreaking"));
|
||||
}
|
||||
|
||||
/// The enchantment's name and its level come from the selected language,
|
||||
/// with the English name loaded above as the fallback.
|
||||
#[test]
|
||||
fn names_follow_the_language() {
|
||||
struct Mem(HashMap<String, Vec<u8>>);
|
||||
impl crate::lang::ResourceSource for Mem {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
self.0.get(path).cloned()
|
||||
}
|
||||
}
|
||||
let ru = Mem(HashMap::from([(
|
||||
"assets/minecraft/lang/ru_ru.json".to_owned(),
|
||||
r#"{"enchantment.minecraft.sharpness":"Острота","enchantment.level.5":"V"}"#
|
||||
.as_bytes()
|
||||
.to_vec(),
|
||||
)]));
|
||||
let ru = crate::lang::Language::load(&[&ru], "ru_ru");
|
||||
let e = sample();
|
||||
assert_eq!(
|
||||
e.full_name_in(Some(&ru), "minecraft:sharpness", 5).0,
|
||||
"Острота V"
|
||||
);
|
||||
// mending carries no key in the fixture: the English name stays.
|
||||
assert_eq!(
|
||||
e.full_name_in(Some(&ru), "minecraft:mending", 1).0,
|
||||
"mending"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ mod bossbars;
|
||||
mod breezes;
|
||||
mod cartography;
|
||||
mod chat;
|
||||
mod client_ambient;
|
||||
mod clipboard;
|
||||
mod combat;
|
||||
mod command_blocks;
|
||||
@@ -36,6 +37,7 @@ mod debug_keys;
|
||||
mod decorated_pot;
|
||||
mod dedicated;
|
||||
mod deflect;
|
||||
mod dialogs;
|
||||
mod discord;
|
||||
mod dispense_fixture;
|
||||
mod dispenser;
|
||||
@@ -96,6 +98,8 @@ mod maps;
|
||||
mod minecarts;
|
||||
mod mob_blocks;
|
||||
mod mob_gear;
|
||||
mod mod_input;
|
||||
mod mod_render;
|
||||
mod mods;
|
||||
mod mount_menu;
|
||||
mod mounts;
|
||||
@@ -357,7 +361,7 @@ impl Options {
|
||||
match arg.as_str() {
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
|
||||
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
|
||||
horizon_core::VANILLA_VERSION
|
||||
);
|
||||
return Ok(None);
|
||||
@@ -374,6 +378,8 @@ impl Options {
|
||||
"--control" => o.control = Some(horizon_client::control::default_path()),
|
||||
"--server-thread" => o.server_thread = true,
|
||||
"--in-frame" | "--no-server-thread" => o.server_thread = false,
|
||||
// Horizon's own commands (/pregen), off by default as on vanilla.
|
||||
"--pregen" => horizon_client::command::vanilla::set_horizon_commands(true),
|
||||
_ => {
|
||||
let value = args
|
||||
.next()
|
||||
@@ -1137,6 +1143,7 @@ struct Game<'a> {
|
||||
pending_pack_reload: bool,
|
||||
/// A server's resource packs (game/server_packs.rs).
|
||||
server_packs: server_packs::ServerPackState,
|
||||
dialogs: dialogs::DialogState,
|
||||
world_renderer_ready: bool,
|
||||
collision: &'a BlockCollisionRegistry<'a>,
|
||||
motion: &'a MotionResources,
|
||||
@@ -1236,6 +1243,11 @@ struct Game<'a> {
|
||||
luminance: Option<horizon_client::dynamic_light::Luminance>,
|
||||
/// Name tags drawn over everything (`RenderPipelines.TEXT_SEE_THROUGH`).
|
||||
see_through_vertices: Vec<Vertex>,
|
||||
/// Runs of `entity_vertices` by entity, for a shader pack's per-entity draws; recorded only
|
||||
/// while `pack_ids` is set (game/shader_packs.rs).
|
||||
entity_spans: std::cell::RefCell<Vec<horizon_client::gfx::pack_draw::EntitySpan>>,
|
||||
/// The shader pack's entity and block entity ids, while one draws entities.
|
||||
pack_ids: Option<shader_packs::PackIds>,
|
||||
started: Instant,
|
||||
previous: Instant,
|
||||
/// FramerateLimitTracker.latestInputTime.
|
||||
@@ -1548,6 +1560,8 @@ struct Game<'a> {
|
||||
/// position) for the guests.
|
||||
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
|
||||
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
|
||||
/// Global level events for every guest (`ServerLevel.globalLevelEvent`).
|
||||
lan_global_events: Vec<(i32, [i32; 3], i32)>,
|
||||
/// `ContainerOpenersCounter`: how many players (the host and the guests)
|
||||
/// have each chest open.
|
||||
lid_openers: HashMap<(i32, i32, i32), i32>,
|
||||
@@ -2761,7 +2775,13 @@ impl Game<'_> {
|
||||
}
|
||||
_ => 1.0,
|
||||
};
|
||||
self.audio.play(name, c, volume, pitch);
|
||||
if matches!(id, 1029 | 1030) {
|
||||
// Clients play the anvil sound from its level event;
|
||||
// capturing it also sends a duplicate sound packet.
|
||||
self.audio.play_unshared(name, c, volume, pitch);
|
||||
} else {
|
||||
self.audio.play(name, c, volume, pitch);
|
||||
}
|
||||
}
|
||||
}
|
||||
LevelEvent::Sound {
|
||||
@@ -4478,6 +4498,7 @@ impl Game<'_> {
|
||||
self.tick_block_entity_anims()
|
||||
});
|
||||
horizon_client::spans::time("tick_particles", || self.tick_particles());
|
||||
self.tick_client_ambient();
|
||||
}
|
||||
// ServerBossEvent broadcasts, after this level's entities have ticked.
|
||||
self.publish_boss_bars();
|
||||
@@ -4819,11 +4840,14 @@ impl Game<'_> {
|
||||
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
|
||||
// The pack prompt replaces the connecting screen (setScreen), but
|
||||
// in game it opens over the world.
|
||||
let mut batch = if self.server_packs.prompt.is_some() && self.player.is_none() {
|
||||
let mut batch = if (self.server_packs.prompt.is_some() || self.dialog_open())
|
||||
&& self.player.is_none()
|
||||
{
|
||||
HudBatch::new(size)
|
||||
} else {
|
||||
self.hud_layers(size)
|
||||
};
|
||||
self.draw_dialog(&mut batch);
|
||||
self.draw_pack_prompt(&mut batch);
|
||||
// Gui.extractRenderState: the debug overlay comes after the screen
|
||||
// and the toasts, so it is over everything, menus included.
|
||||
@@ -4922,6 +4946,7 @@ impl Game<'_> {
|
||||
// Hud: the action bar and titles draw over the hotbar (nextStratum).
|
||||
self.draw_boss_bars(&mut batch);
|
||||
self.draw_extras(&mut batch);
|
||||
self.draw_mod_shapes(&mut batch);
|
||||
}
|
||||
if show_hud {
|
||||
// Hud.nextContextualInfoState: the jump bar, the experience bar or
|
||||
@@ -5136,7 +5161,8 @@ impl Game<'_> {
|
||||
| BlockEntity::TrialSpawner(_)
|
||||
| BlockEntity::Vault(_)
|
||||
| BlockEntity::Beehive(_)
|
||||
| BlockEntity::CommandBlock(_),
|
||||
| BlockEntity::CommandBlock(_)
|
||||
| BlockEntity::Skull(_),
|
||||
) => {}
|
||||
None => {
|
||||
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
|
||||
@@ -5405,7 +5431,8 @@ impl Game<'_> {
|
||||
| BlockEntity::TrialSpawner(_)
|
||||
| BlockEntity::Vault(_)
|
||||
| BlockEntity::Beehive(_)
|
||||
| BlockEntity::CommandBlock(_),
|
||||
| BlockEntity::CommandBlock(_)
|
||||
| BlockEntity::Skull(_),
|
||||
) => {}
|
||||
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
|
||||
None => {
|
||||
@@ -6743,8 +6770,10 @@ impl Game<'_> {
|
||||
alpha: f64,
|
||||
mut out: Vec<Vertex>,
|
||||
) -> Vec<Vertex> {
|
||||
self.entity_spans.borrow_mut().clear();
|
||||
self.prepare_entity_culling(camera);
|
||||
self.prepare_trims();
|
||||
self.mark_entity(out.len(), "minecraft:entity_flame");
|
||||
let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront {
|
||||
self.yaw + 180.0
|
||||
} else {
|
||||
@@ -6836,14 +6865,19 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
// `ItemEntityRenderer`.
|
||||
self.mark_entity(out.len(), "minecraft:item");
|
||||
self.dropped_item_geometry(camera, alpha, &mut out);
|
||||
// `VaultRenderer`.
|
||||
self.mark_entity(out.len(), "");
|
||||
self.vault_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:ominous_item_spawner");
|
||||
self.ominous_item_spawner_geometry(camera, alpha, &mut out);
|
||||
// Mobs and their projectiles.
|
||||
// Mobs and their projectiles (a span each).
|
||||
self.mob_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:player");
|
||||
self.player_model_geometry(camera, self.clock.camera_fraction(), &mut out);
|
||||
self.guest_model_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:evoker_fangs");
|
||||
self.fangs_geometry(camera, alpha, &mut out);
|
||||
let mut see_through = std::mem::take(&mut self.see_through_vertices);
|
||||
see_through.clear();
|
||||
@@ -6851,6 +6885,7 @@ impl Game<'_> {
|
||||
self.text_display_geometry(camera, alpha, &mut out, &mut see_through);
|
||||
self.see_through_vertices = see_through;
|
||||
// Entity shadows (EntityRenderer.extractShadow).
|
||||
self.mark_translucent_entity(out.len(), "minecraft:entity_shadow");
|
||||
if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() {
|
||||
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
|
||||
let darken = self.sky_darken();
|
||||
@@ -6914,6 +6949,7 @@ impl Game<'_> {
|
||||
_ => None,
|
||||
},
|
||||
banner: &|p| self.banner_layers_at(p),
|
||||
skull: &|p| self.skull_skin_at(p),
|
||||
glyph: &|c| self.gui.atlas.glyph_cell(c),
|
||||
};
|
||||
// Block entities outside the view frustum are skipped (with a
|
||||
@@ -6944,13 +6980,14 @@ impl Game<'_> {
|
||||
v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0))
|
||||
})
|
||||
});
|
||||
if self.entity_culler.is_some() {
|
||||
if self.entity_culler.is_some() || self.pack_ids.is_some() {
|
||||
for block in visible {
|
||||
let start = out.len();
|
||||
self.mark_block_entity(start, block.1);
|
||||
self.res
|
||||
.block_entity_render()
|
||||
.render(&scene, std::iter::once(block), &mut out);
|
||||
if !off_screen(block.1) {
|
||||
if !off_screen(block.1) && self.entity_culler.is_some() {
|
||||
self.cull_entity_vertices(&mut out, start);
|
||||
}
|
||||
}
|
||||
@@ -6959,6 +6996,7 @@ impl Game<'_> {
|
||||
.block_entity_render()
|
||||
.render(&scene, visible, &mut out);
|
||||
}
|
||||
self.mark_stage(out.len(), "DESTROY");
|
||||
for (pos, stage) in self.cracks(camera) {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
self.res
|
||||
@@ -6967,6 +7005,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
// Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet.
|
||||
self.mark_entity(out.len(), "minecraft:experience_orb");
|
||||
if let Some(r) = self
|
||||
.gui
|
||||
.atlas
|
||||
@@ -7030,6 +7069,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
// Falling blocks use their baked model, including non-cubic shapes.
|
||||
self.mark_entity(out.len(), "minecraft:falling_block");
|
||||
for f in &self.falling {
|
||||
let Some((_, tint)) = self.block_face_sprite(f.state) else {
|
||||
continue;
|
||||
@@ -7060,20 +7100,35 @@ impl Game<'_> {
|
||||
vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint);
|
||||
}
|
||||
}
|
||||
self.mark_entity(out.len(), "");
|
||||
self.moving_piston_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:tnt");
|
||||
self.tnt_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:painting");
|
||||
self.painting_geometry(camera, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:item_frame");
|
||||
self.frame_geometry(camera, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:armor_stand");
|
||||
self.armor_stand_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:oak_boat");
|
||||
self.boat_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:minecart");
|
||||
self.cart_geometry(camera, alpha, &mut out);
|
||||
// Beams: `gbuffers_beaconbeam`, not a block entity's program (5.4 has no stage for them).
|
||||
self.mark_stage(out.len(), "NONE");
|
||||
self.beacon_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:fishing_bobber");
|
||||
self.fishing_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:leash_knot");
|
||||
self.leash_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:trident");
|
||||
self.trident_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:firework_rocket");
|
||||
self.rocket_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:splash_potion");
|
||||
self.thrown_potion_geometry(camera, alpha, &mut out);
|
||||
// Particles (ParticleEngine.extract): camera-facing quads.
|
||||
self.mark_stage(out.len(), "PARTICLES");
|
||||
let world = &self.world;
|
||||
self.particles.render(
|
||||
camera,
|
||||
@@ -7084,6 +7139,7 @@ impl Game<'_> {
|
||||
&mut out,
|
||||
);
|
||||
// Breaking progress overlays (destroy_stage_0..9): ours and the other players'.
|
||||
self.mark_stage(out.len(), "DESTROY");
|
||||
for (pos, stage) in self.cracks(camera) {
|
||||
let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]))
|
||||
- camera)
|
||||
@@ -8396,6 +8452,8 @@ impl Game<'_> {
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
// ItemStack.useOn: a use that acted counts as one of the item.
|
||||
self.stats.add("used", &stack.item, 1);
|
||||
self.damage_held(damage);
|
||||
self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), Some(new));
|
||||
Ok(true)
|
||||
@@ -8600,6 +8658,14 @@ impl Game<'_> {
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
// HoneycombItem.useOn's game event, and ItemStack.useOn's used statistic.
|
||||
self.post_block_game_event(
|
||||
"minecraft:block_change",
|
||||
hit.pos,
|
||||
self.sculk_actor(),
|
||||
Some(state),
|
||||
);
|
||||
self.stats.add("used", &stack.item, 1);
|
||||
if !self.creative {
|
||||
self.consume_held();
|
||||
}
|
||||
@@ -9191,10 +9257,6 @@ impl Game<'_> {
|
||||
)
|
||||
}
|
||||
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;
|
||||
// Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves:
|
||||
// LevelExtractor.allChanged when they change.
|
||||
@@ -9957,6 +10019,7 @@ impl Game<'_> {
|
||||
self.pitch,
|
||||
),
|
||||
};
|
||||
let (view_yaw, view_pitch) = self.shaken_view(view_yaw, view_pitch);
|
||||
self.audio
|
||||
.set_listener([camera.x, camera.y, camera.z], view_yaw, view_pitch);
|
||||
let block = [
|
||||
@@ -10188,6 +10251,7 @@ impl Game<'_> {
|
||||
} else {
|
||||
self.shader_pack_inputs(camera, alpha as f32)
|
||||
};
|
||||
let entity_spans = std::mem::take(self.entity_spans.get_mut());
|
||||
let frame = Frame {
|
||||
weather: &weather,
|
||||
weather_time: horizon_client::weather::Time::new(self.world.game_time, alpha as f32),
|
||||
@@ -10252,6 +10316,7 @@ impl Game<'_> {
|
||||
color: sky.cloud_color,
|
||||
}),
|
||||
entities: &entities,
|
||||
entity_spans: &entity_spans,
|
||||
dynamic_lights: &self.dynamic_lights,
|
||||
lightning: horizon_client::gfx::lightning::Input {
|
||||
bolts: &bolts,
|
||||
@@ -10303,6 +10368,7 @@ impl Game<'_> {
|
||||
};
|
||||
// Restore storage even when rendering fails (for example, a lost surface).
|
||||
self.entity_vertices = entities;
|
||||
*self.entity_spans.get_mut() = entity_spans;
|
||||
self.see_through_vertices = see_through;
|
||||
result
|
||||
}
|
||||
@@ -10374,6 +10440,7 @@ impl Game<'_> {
|
||||
|| (self.title.is_none()
|
||||
&& self.player.is_some()
|
||||
&& (self.screen.blurs_background(self.pause_menu)
|
||||
|| self.dialog_open()
|
||||
|| (self.screen == Screen::Win && self.win_screen_pauses())));
|
||||
let radius = self.settings.menu_blur as f32;
|
||||
(blurred && radius >= 1.0).then_some(radius)
|
||||
@@ -10568,6 +10635,10 @@ impl Game<'_> {
|
||||
}
|
||||
/// A mouse button while playing (window or control socket).
|
||||
fn play_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
|
||||
// A mod's claimed item takes the use button (capability `input`).
|
||||
if self.mod_use(button, pressed) {
|
||||
return Ok(());
|
||||
}
|
||||
if self.sleeping.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -10687,6 +10758,7 @@ impl Game<'_> {
|
||||
// The loading screen's chunk map fills ring by ring, as vanilla's.
|
||||
self.streaming.loading =
|
||||
self.options.execution_role.is_client() && self.loading_reason().is_some();
|
||||
self.tick_pregen();
|
||||
let (uploads, unloaded) =
|
||||
horizon_client::spans::time("streaming", || self.streaming.update(&mut self.world));
|
||||
if let Some(lod) = &mut self.lod {
|
||||
@@ -11029,6 +11101,12 @@ impl ApplicationHandler for Game<'_> {
|
||||
if self.screen == Screen::Advancements {
|
||||
self.advancements_drag();
|
||||
}
|
||||
if self.screen == Screen::Stats {
|
||||
self.stats_drag();
|
||||
}
|
||||
if self.screen == Screen::WorldOptions {
|
||||
self.world_options_drag();
|
||||
}
|
||||
if self.screen == Screen::Creative {
|
||||
let (_, oy) = Self::creative_origin(&b);
|
||||
self.creative_screen.drag_scrollbar(self.cursor.1 - oy);
|
||||
@@ -11065,7 +11143,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
}) * wheel_sensitivity
|
||||
};
|
||||
let d = scaled(raw_y) as f32;
|
||||
if let Some(title) = &mut self.title
|
||||
if self.dialog_open() {
|
||||
self.dialog_scroll(d);
|
||||
} else if let Some(title) = &mut self.title
|
||||
&& self.screen != Screen::Win
|
||||
{
|
||||
let size = self
|
||||
@@ -11135,6 +11215,11 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.pack_prompt_click()?;
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } if self.dialog_open() => {
|
||||
if state == ElementState::Pressed && button == MouseButton::Left {
|
||||
self.dialog_click()?;
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { .. } if self.screen == Screen::Win => {}
|
||||
WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => {
|
||||
if self.options_waiting_for_key() && state == ElementState::Pressed {
|
||||
@@ -11308,6 +11393,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
Screen::WorldOptions if pressed && button == MouseButton::Left => {
|
||||
self.world_options_click()
|
||||
}
|
||||
Screen::WorldOptions if button == MouseButton::Left => {
|
||||
self.world_options_release()
|
||||
}
|
||||
Screen::Friends if pressed && button == MouseButton::Left => {
|
||||
self.friends_screen_click()
|
||||
}
|
||||
@@ -11331,6 +11419,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
.map_or([1, 1], |r| [r.config.width, r.config.height]);
|
||||
self.stats_click(size);
|
||||
}
|
||||
Screen::Stats if button == MouseButton::Left => self.stats_release(),
|
||||
Screen::Mod if pressed && button == MouseButton::Left => {
|
||||
self.mod_screen_click()
|
||||
}
|
||||
@@ -11345,6 +11434,13 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.answer_pack_prompt(false)?;
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } if self.dialog_open() => {
|
||||
if event.state == ElementState::Pressed
|
||||
&& let PhysicalKey::Code(key) = event.physical_key
|
||||
{
|
||||
self.dialog_key(key)?
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if self.screen == Screen::Chat && self.title.is_none() =>
|
||||
{
|
||||
@@ -11475,6 +11571,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
return Ok(());
|
||||
};
|
||||
self.extras_key(key, event.state == ElementState::Pressed, event.repeat);
|
||||
self.mod_key(key, event.state == ElementState::Pressed, event.repeat);
|
||||
// key.smoothCamera toggles the cinematic camera.
|
||||
if self.screen == Screen::Playing
|
||||
&& event.state == ElementState::Pressed
|
||||
@@ -11825,6 +11922,7 @@ impl<'a> Game<'a> {
|
||||
world_loader: None,
|
||||
pending_pack_reload: false,
|
||||
server_packs: Default::default(),
|
||||
dialogs: Default::default(),
|
||||
world_renderer_ready: false,
|
||||
collision: res.collision(),
|
||||
motion: res.motion(),
|
||||
@@ -11897,6 +11995,8 @@ impl<'a> Game<'a> {
|
||||
dynamic_lights: Vec::new(),
|
||||
luminance: None,
|
||||
see_through_vertices: Vec::new(),
|
||||
entity_spans: Default::default(),
|
||||
pack_ids: None,
|
||||
health_hud: hud_layout::HealthHud::default(),
|
||||
started: now,
|
||||
previous: now,
|
||||
@@ -12099,6 +12199,7 @@ impl<'a> Game<'a> {
|
||||
lan_events: Vec::new(),
|
||||
lan_block_events: Vec::new(),
|
||||
lan_entity_events: Vec::new(),
|
||||
lan_global_events: Vec::new(),
|
||||
lid_openers: HashMap::new(),
|
||||
lan_acting: None,
|
||||
guest_packets: Vec::new(),
|
||||
@@ -12831,6 +12932,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
|
||||
hud,
|
||||
nether_lighting: false,
|
||||
entities: &[],
|
||||
entity_spans: &[],
|
||||
dynamic_lights: &[],
|
||||
clouds: None,
|
||||
lightning: Default::default(),
|
||||
@@ -13090,10 +13192,6 @@ impl Loading {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(r) = &self.renderer {
|
||||
self.settings
|
||||
.clamp_gui_scale([r.config.width as i32, r.config.height as i32]);
|
||||
}
|
||||
horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed);
|
||||
self.window = Some(window);
|
||||
}
|
||||
@@ -13132,8 +13230,6 @@ impl Loading {
|
||||
self.settings.horizon.api,
|
||||
) {
|
||||
Ok(r) => {
|
||||
self.settings
|
||||
.clamp_gui_scale([r.config.width as i32, r.config.height as i32]);
|
||||
horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed);
|
||||
self.renderer = Some(r);
|
||||
}
|
||||
|
||||
@@ -390,6 +390,9 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn screen_label(&self) -> &'static str {
|
||||
if self.dialog_open() {
|
||||
return "dialog";
|
||||
}
|
||||
if self.title.is_some() {
|
||||
return "title";
|
||||
}
|
||||
@@ -485,6 +488,7 @@ impl Game<'_> {
|
||||
})
|
||||
});
|
||||
json!({
|
||||
"dialog": self.dialog_status(),
|
||||
"screen": self.screen_label(),
|
||||
"menu": self.title.as_ref().map(|_| self.title_value()),
|
||||
"world": (self.title.is_none()).then(|| match &self.integrated {
|
||||
|
||||
@@ -8,8 +8,10 @@ use horizon_client::{
|
||||
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
|
||||
block_entity_render::BlockAnim,
|
||||
collisions::{SceneCollisions, no_collision_empty},
|
||||
containers::BlockEntity,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
save::number,
|
||||
skins,
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
use horizon_world::nbt::Tag;
|
||||
@@ -392,4 +394,25 @@ impl Game<'_> {
|
||||
pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 {
|
||||
self.be_anims.lid(pos, partial)
|
||||
}
|
||||
/// `SkullBlockRenderer.getPlayerSkin`: the skin sprite of the profile of
|
||||
/// the player head at `pos`. The skin download is started here; while it
|
||||
/// is in flight (or when it cannot be got) the profile's default skin
|
||||
/// stands in. A head with no profile answers None: `SKIN_BY_TYPE`.
|
||||
pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<&str> {
|
||||
let Some(BlockEntity::Skull(skull)) =
|
||||
self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let skin = skull.skin.as_ref()?;
|
||||
if let Some((url, location)) = &skin.download {
|
||||
self.skin_downloads
|
||||
.borrow_mut()
|
||||
.state(skins::Kind::Skin, url);
|
||||
if self.gui.atlas.sprites.contains_key(location) {
|
||||
return Some(location);
|
||||
}
|
||||
}
|
||||
Some(skin.fallback)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ fn chat_tree<'a>(
|
||||
mods: &'a super::mods::ModsState,
|
||||
) -> &'a horizon_client::command::Dispatcher {
|
||||
match remote.as_ref().and_then(|r| r.commands.as_ref()) {
|
||||
Some(tree) => tree,
|
||||
Some(tree) => mods.remote_dispatcher().unwrap_or(tree),
|
||||
None => mods.dispatcher(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! The window's own ambient effects of entities, which a client makes for
|
||||
//! itself (`level().isClientSide()` branches): endermen's and endermites'
|
||||
//! portal particles, blazes' smoke and burn, eyes of ender's trail. They run
|
||||
//! on the game that has the window, in-frame or following a server, never on
|
||||
//! a server: nothing of them goes over the network.
|
||||
use super::Game;
|
||||
use horizon_client::mobs::{MobEvent, ambient};
|
||||
use horizon_client::particles::{ParticleOptions, ParticleType};
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn tick_client_ambient(&mut self) {
|
||||
if self.serving.is_some() || self.options.dedicated.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut events = Vec::new();
|
||||
for m in self.mobs.iter_mut().filter(|m| !m.removed) {
|
||||
ambient::client_ai_step(m, &mut events);
|
||||
}
|
||||
for event in events {
|
||||
match event {
|
||||
MobEvent::ParticleAt { kind, at, velocity } => {
|
||||
if let Some(ty) = ParticleType::from_name(kind) {
|
||||
self.particles
|
||||
.add(&ParticleOptions::simple(ty), at, velocity);
|
||||
}
|
||||
}
|
||||
// Each guest of a LAN host makes its own.
|
||||
MobEvent::LocalSound(name, at, volume, pitch) => {
|
||||
self.audio
|
||||
.play_unshared(&format!("minecraft:{name}"), Some(at), volume, pitch)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.eye_particles();
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ mod items;
|
||||
mod misc;
|
||||
mod place;
|
||||
mod players;
|
||||
pub(super) mod pregen;
|
||||
mod raid;
|
||||
mod terrain_cmds;
|
||||
mod text_commands;
|
||||
@@ -759,6 +760,7 @@ impl Game<'_> {
|
||||
"ride.mount" | "ride.dismount" => self.cmd_ride(id, ctx),
|
||||
"spreadplayers" => self.cmd_spreadplayers(ctx),
|
||||
id if id.starts_with("forceload.") => self.cmd_forceload(id, ctx),
|
||||
id if id.starts_with("pregen.") => self.cmd_pregen(id, ctx),
|
||||
"fillbiome" => self.cmd_fillbiome(ctx),
|
||||
id if id.starts_with("worldborder.") => self.cmd_worldborder(id, ctx),
|
||||
id if id.starts_with("loot.") => self.cmd_loot(id, ctx),
|
||||
@@ -2500,12 +2502,14 @@ impl Game<'_> {
|
||||
};
|
||||
let max = Self::int(ctx, "maxCount").unwrap_or(-1);
|
||||
let counting = max == 0;
|
||||
// Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried.
|
||||
// Inventory slots 0..40: main, armor feet to head, off hand;
|
||||
// then clearOrCountMatchingItems visits the crafting grid and carried stack.
|
||||
let mut removed = 0i32;
|
||||
let mut budget = if max < 0 { i32::MAX } else { max };
|
||||
let all = |g: &Self| -> Vec<Option<ItemStack>> {
|
||||
let mut v: Vec<Option<ItemStack>> = g.inventory.clone();
|
||||
v.extend(g.armor.iter().cloned());
|
||||
v.extend(g.armor.iter().rev().cloned());
|
||||
v.push(g.offhand.clone());
|
||||
v.extend(g.craft_grid.iter().cloned());
|
||||
v.push(g.carried.clone());
|
||||
v
|
||||
@@ -2519,7 +2523,8 @@ impl Game<'_> {
|
||||
.collect();
|
||||
let mut slots: Vec<&mut Option<ItemStack>> = Vec::new();
|
||||
slots.extend(self.inventory.iter_mut());
|
||||
slots.extend(self.armor.iter_mut());
|
||||
slots.extend(self.armor.iter_mut().rev());
|
||||
slots.push(&mut self.offhand);
|
||||
slots.extend(self.craft_grid.iter_mut());
|
||||
slots.push(&mut self.carried);
|
||||
for (slot, matches) in slots.into_iter().zip(matching) {
|
||||
|
||||
@@ -57,6 +57,8 @@ pub(in crate::game) struct CommandExtras {
|
||||
/// The `CommandResultCallback` results of the outermost source, when a
|
||||
/// harness records them.
|
||||
pub results: Option<Vec<(bool, i32)>>,
|
||||
/// The running `/pregen` task.
|
||||
pub pregen: Option<super::pregen::PregenTask>,
|
||||
}
|
||||
|
||||
use horizon_core::version::{BUILD_TIME, DATA_VERSION, STABLE, VANILLA_VERSION, VERSION_ID};
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
//! `/pregen`, Horizon's own command: generate, light and save every chunk of a
|
||||
//! square or a circle ahead of the players (docs/pregeneration.md). The task
|
||||
//! lives on the server and hands its band to the level's streaming, whose
|
||||
//! workers do the work; chunks behind the band unload and are saved as any
|
||||
//! chunk the players leave.
|
||||
use super::{CommandError, Context, Dim, Game, R};
|
||||
use horizon_client::{
|
||||
lan::data::component_nbt,
|
||||
pregen::{Pregen, Shape},
|
||||
text::{self, Text},
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How often the progress is reported.
|
||||
const REPORT_EVERY: Duration = Duration::from_secs(5);
|
||||
/// How long the band may stay put before the task looks for what holds it.
|
||||
const STALL: Duration = Duration::from_secs(30);
|
||||
|
||||
pub(in crate::game) struct PregenTask {
|
||||
pregen: Pregen,
|
||||
dim: Dim,
|
||||
paused: bool,
|
||||
/// Time spent running, up to the last pause, and when it last resumed.
|
||||
ran: Duration,
|
||||
resumed: Instant,
|
||||
reported: Instant,
|
||||
/// When the band last moved, to notice a task that stopped advancing.
|
||||
moved: Instant,
|
||||
/// The player who started it, told the progress too (a guest's connection).
|
||||
owner: Option<u32>,
|
||||
}
|
||||
|
||||
impl PregenTask {
|
||||
fn running_for(&self) -> Duration {
|
||||
if self.paused {
|
||||
self.ran
|
||||
} else {
|
||||
self.ran + self.resumed.elapsed()
|
||||
}
|
||||
}
|
||||
fn progress(&self) -> Text {
|
||||
let p = &self.pregen;
|
||||
let seconds = self.running_for().as_secs_f64();
|
||||
let rate = p.done as f64 / seconds.max(1e-3);
|
||||
let left = p.total - p.done;
|
||||
let eta = if rate > 0.0 {
|
||||
duration(left as f64 / rate)
|
||||
} else {
|
||||
"unknown".into()
|
||||
};
|
||||
Text::literal(format!(
|
||||
"Pregenerating {}: {} of {} chunks ({:.1}%), {rate:.1} chunks/s, {} left",
|
||||
self.dim.id(),
|
||||
p.done,
|
||||
p.total,
|
||||
100.0 * p.done as f64 / p.total.max(1) as f64,
|
||||
if p.done == p.total {
|
||||
"nothing".into()
|
||||
} else {
|
||||
eta
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(message: &str) -> CommandError {
|
||||
CommandError::new(Text::literal(message))
|
||||
}
|
||||
|
||||
/// `1h 02m 03s`.
|
||||
fn duration(seconds: f64) -> String {
|
||||
let s = seconds.round() as u64;
|
||||
match (s / 3600, s / 60 % 60, s % 60) {
|
||||
(0, 0, s) => format!("{s}s"),
|
||||
(0, m, s) => format!("{m}m {s:02}s"),
|
||||
(h, m, s) => format!("{h}h {m:02}m {s:02}s"),
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn cmd_pregen(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
match id {
|
||||
"pregen.start" => {
|
||||
if self.cmds.pregen.is_some() {
|
||||
return Err(failure(
|
||||
"Pregeneration is already running: /pregen cancel stops it",
|
||||
));
|
||||
}
|
||||
let radius = Self::int(ctx, "radius").unwrap_or(0);
|
||||
let shape = if ctx.literals.iter().any(|l| l == "circle") {
|
||||
Shape::Circle
|
||||
} else {
|
||||
Shape::Square
|
||||
};
|
||||
let [x, z] = if ctx.get("center").is_some() {
|
||||
self.column_arg(ctx, "center")?
|
||||
} else {
|
||||
let p = self.source_position();
|
||||
[p[0].floor() as i32, p[2].floor() as i32]
|
||||
};
|
||||
let pregen = Pregen::new((x >> 4, z >> 4), radius >> 4, shape);
|
||||
let now = Instant::now();
|
||||
let total = pregen.total;
|
||||
self.feedback(Text::literal(format!(
|
||||
"Pregenerating {total} chunks of {}: a {} of radius {radius} around {x} {z}",
|
||||
self.dim.id(),
|
||||
match shape {
|
||||
Shape::Square => "square",
|
||||
Shape::Circle => "circle",
|
||||
},
|
||||
)));
|
||||
self.cmds.pregen = Some(PregenTask {
|
||||
pregen,
|
||||
dim: self.dim,
|
||||
paused: false,
|
||||
ran: Duration::ZERO,
|
||||
resumed: now,
|
||||
reported: now,
|
||||
moved: now,
|
||||
owner: self.lan_acting,
|
||||
});
|
||||
Ok(total as i32)
|
||||
}
|
||||
"pregen.pause" | "pregen.continue" => {
|
||||
let pause = id == "pregen.pause";
|
||||
let task = self
|
||||
.cmds
|
||||
.pregen
|
||||
.as_mut()
|
||||
.ok_or_else(|| failure("No pregeneration is running"))?;
|
||||
if task.paused != pause {
|
||||
task.paused = pause;
|
||||
if pause {
|
||||
task.ran += task.resumed.elapsed();
|
||||
} else {
|
||||
task.resumed = Instant::now();
|
||||
}
|
||||
}
|
||||
let (progress, dim) = (task.progress(), task.dim);
|
||||
if pause && self.dim == dim {
|
||||
self.streaming.set_band(None);
|
||||
}
|
||||
self.feedback(
|
||||
Text::literal(if pause { "Paused. " } else { "Continuing. " }).append(progress),
|
||||
);
|
||||
Ok(1)
|
||||
}
|
||||
"pregen.cancel" => {
|
||||
let task = self
|
||||
.cmds
|
||||
.pregen
|
||||
.take()
|
||||
.ok_or_else(|| failure("No pregeneration is running"))?;
|
||||
if self.dim == task.dim {
|
||||
self.streaming.set_band(None);
|
||||
}
|
||||
self.feedback(Text::literal("Cancelled. ").append(task.progress()));
|
||||
Ok(task.pregen.done as i32)
|
||||
}
|
||||
_ => {
|
||||
let task = self
|
||||
.cmds
|
||||
.pregen
|
||||
.as_ref()
|
||||
.ok_or_else(|| failure("No pregeneration is running"))?;
|
||||
let progress = task.progress();
|
||||
let done = task.pregen.done as i32;
|
||||
self.feedback(progress);
|
||||
Ok(done)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the task's band past the rows that are lit and hand it to the
|
||||
/// level's streaming, and report the progress now and then. Runs before
|
||||
/// each streaming update of the level in place.
|
||||
pub(in crate::game) fn tick_pregen(&mut self) {
|
||||
let Some(task) = self.cmds.pregen.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if task.dim != self.dim || task.paused {
|
||||
return;
|
||||
}
|
||||
// A row is done once its chunks are lit and post-processed
|
||||
// (`postprocess_chunks`, on the tick), as vanilla's are by the time
|
||||
// they are FULL: then they may unload and be saved.
|
||||
let (streaming, chunks) = (&mut self.streaming, &self.world.chunks);
|
||||
if task.pregen.advance(|x, z| {
|
||||
streaming.is_lit(x, z)
|
||||
&& chunks
|
||||
.get(&(x, z))
|
||||
.is_some_and(|c| c.postprocess.is_empty())
|
||||
}) {
|
||||
task.moved = Instant::now();
|
||||
}
|
||||
streaming.set_band(task.pregen.band());
|
||||
if task.moved.elapsed() >= STALL {
|
||||
// Nothing advanced for a while: say what the first row waits
|
||||
// for, and queue light again for chunks that lost their job.
|
||||
task.moved = Instant::now();
|
||||
let row = task.pregen.first_row();
|
||||
let waiting = row
|
||||
.iter()
|
||||
.filter(|k| chunks.get(k).is_some_and(|c| !c.postprocess.is_empty()))
|
||||
.count();
|
||||
let [missing, lighting, unlit] = streaming.unstick_light(&mut self.world, &row);
|
||||
log::warn!(
|
||||
"Horizon: pregeneration waits on row {:?}: {missing} not loaded, {lighting} being lit, \
|
||||
{unlit} unlit with no light job (queued again), {waiting} not post-processed; {:?}",
|
||||
row.first(),
|
||||
streaming.stages()
|
||||
);
|
||||
}
|
||||
let finished = task.pregen.finished();
|
||||
if finished || task.reported.elapsed() >= REPORT_EVERY {
|
||||
task.reported = Instant::now();
|
||||
let (owner, mut message) = (task.owner, task.progress());
|
||||
if finished {
|
||||
message = Text::literal("Done. ")
|
||||
.append(message)
|
||||
.with_color(text::GREEN);
|
||||
self.cmds.pregen = None;
|
||||
}
|
||||
self.pregen_report(owner, message);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the level in place has a running task, which the server pumps
|
||||
/// between its ticks (`pump_pregen`).
|
||||
pub(in crate::game) fn pregen_runs_here(&self) -> bool {
|
||||
self.cmds
|
||||
.pregen
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.dim == self.dim && !t.paused)
|
||||
}
|
||||
|
||||
/// The level a running task needs ticked, whoever is in it.
|
||||
pub(in crate::game) fn pregen_level(&self) -> Option<Dim> {
|
||||
self.cmds.pregen.as_ref().map(|t| t.dim)
|
||||
}
|
||||
|
||||
/// Keep the workers fed until `until`: collect what they finished and
|
||||
/// hand them the next jobs as soon as each one is done, rather than once
|
||||
/// a tick.
|
||||
pub(in crate::game) fn pump_pregen(&mut self, until: Instant) {
|
||||
while self.pregen_runs_here() {
|
||||
let now = Instant::now();
|
||||
if now >= until {
|
||||
break;
|
||||
}
|
||||
self.streaming
|
||||
.wait((until - now).min(Duration::from_millis(5)));
|
||||
self.update_world();
|
||||
}
|
||||
}
|
||||
|
||||
/// The console and the player who started the task get the progress.
|
||||
fn pregen_report(&mut self, owner: Option<u32>, message: Text) {
|
||||
if self.options.dedicated.is_some() {
|
||||
super::super::dedicated::log("INFO", &message.plain());
|
||||
} else {
|
||||
log::info!("{}", message.plain());
|
||||
}
|
||||
if let Some(host) = &self.lan {
|
||||
if let Some(g) = owner.and_then(|c| host.hub.guest(c)) {
|
||||
g.send(&C::SystemChat(play::SystemChat {
|
||||
content: component_nbt(&message.component()),
|
||||
overlay: false,
|
||||
}));
|
||||
}
|
||||
} else if self.options.dedicated.is_none() {
|
||||
self.system_message(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ fn ticks_to_seconds(ticks: i64) -> String {
|
||||
impl Game<'_> {
|
||||
// ---- /forceload ----------------------------------------------------------
|
||||
|
||||
fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> {
|
||||
pub(super) fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> {
|
||||
let c = self
|
||||
.coords(ctx, name)
|
||||
.ok_or_else(|| err("argument.pos2d.incomplete", &[]))?;
|
||||
|
||||
@@ -241,6 +241,13 @@ impl Game<'_> {
|
||||
"pad" => Ok(Some(self.pad_command(&words)?)),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
// A server's dialog takes the keys, in configuration too.
|
||||
if self.dialog_open() {
|
||||
if arg(2)? != "up" {
|
||||
self.dialog_key(key)?;
|
||||
}
|
||||
return ok();
|
||||
}
|
||||
self.require_world()?;
|
||||
// The sign editor takes raw presses (Enter, arrows, Backspace, Escape).
|
||||
if self.sign_edit.is_some() {
|
||||
@@ -294,6 +301,11 @@ impl Game<'_> {
|
||||
if action == "tap" {
|
||||
self.extras_key(physical, false, false);
|
||||
}
|
||||
// So do mods' keys (capability `input`).
|
||||
self.mod_key(physical, action != "up", action == "repeat");
|
||||
if action == "tap" {
|
||||
self.mod_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" {
|
||||
|
||||
@@ -3031,6 +3031,7 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
self.mark_entity(entity_start, &mob.kind.id);
|
||||
let light = self.world.light(
|
||||
mob.position.x.floor() as i32,
|
||||
(mob.position.y + mob.eye_height()).floor() as i32,
|
||||
|
||||
@@ -155,6 +155,14 @@ pub(super) fn preflight(options: &mut Options) -> Result<bool> {
|
||||
for w in &props.warnings {
|
||||
log("WARN", w);
|
||||
}
|
||||
// Horizon's own commands are the owner's choice, off as on vanilla.
|
||||
if props
|
||||
.raw
|
||||
.get(horizon_client::command::vanilla::PREGEN_PROPERTY)
|
||||
.is_some_and(|v| v.trim().eq_ignore_ascii_case("true"))
|
||||
{
|
||||
horizon_client::command::vanilla::set_horizon_commands(true);
|
||||
}
|
||||
props.store(&settings)?;
|
||||
let eula_file = PathBuf::from("eula.txt");
|
||||
let agreed = match eula::agreed(&eula_file) {
|
||||
@@ -667,7 +675,9 @@ impl Game<'_> {
|
||||
self.poll_server_control(&mut state);
|
||||
let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len());
|
||||
if pause_after > 0 {
|
||||
if players == 0 {
|
||||
// A `/pregen` task keeps the server busy as a player would:
|
||||
// paused, nothing would post-process its chunks.
|
||||
if players == 0 && self.pregen_level().is_none() {
|
||||
state.empty_ticks += 1;
|
||||
} else {
|
||||
state.empty_ticks = 0;
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
//! A server's dialogs bound to the game (`ClientCommonPacketListenerImpl.
|
||||
//! showDialog` and `clearDialog`, `DialogScreen`, its `WarningScreen` and the
|
||||
//! `WaitingForResponseScreen`): the screen over whatever is open (the
|
||||
//! connecting screen in configuration), its inputs, and the actions its
|
||||
//! buttons send back.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
confirm_screen::Confirm,
|
||||
dialog::{AfterAction, Click, Dialog, InputValue},
|
||||
dialog_screen::{Layout, Part, WARNING_SPRITES, waiting_button},
|
||||
hud::{HudBatch, rgba},
|
||||
text::Text,
|
||||
ui,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::time::Instant;
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
/// An open `DialogScreen`.
|
||||
struct Open {
|
||||
dialog: Dialog,
|
||||
values: Vec<InputValue>,
|
||||
scroll: ui::Scroll,
|
||||
}
|
||||
|
||||
/// The dialog screens a server can open.
|
||||
#[derive(Default)]
|
||||
pub(super) struct DialogState {
|
||||
open: Option<Open>,
|
||||
/// `WaitingForResponseScreen`, since when.
|
||||
waiting: Option<Instant>,
|
||||
/// `DialogScreen.WarningScreen`, over the dialog.
|
||||
warning: bool,
|
||||
}
|
||||
|
||||
fn warning_texts() -> (Text, Text, [Text; 2]) {
|
||||
let t = |key: &str| Text::translate(key, &[]);
|
||||
(
|
||||
t("menu.custom_screen_info.title"),
|
||||
t("menu.custom_screen_info.contents"),
|
||||
[t("menu.disconnect"), t("gui.back")],
|
||||
)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Whether a dialog screen takes the input.
|
||||
pub(super) fn dialog_open(&self) -> bool {
|
||||
let d = &self.dialogs;
|
||||
d.open.is_some() || d.waiting.is_some() || d.warning
|
||||
}
|
||||
|
||||
/// `showDialog`: the dialog replaces an open one (and a waiting screen);
|
||||
/// under the warning screen, it is what Back returns to.
|
||||
pub(super) fn show_dialog(&mut self, tag: &Tag) {
|
||||
let Some(dialog) = Dialog::parse(tag) else {
|
||||
log::warn!("Horizon: failed to show dialog for data {tag:?}");
|
||||
return;
|
||||
};
|
||||
let values = dialog.inputs.iter().map(|i| i.control.initial()).collect();
|
||||
self.dialogs.open = Some(Open {
|
||||
dialog,
|
||||
values,
|
||||
scroll: ui::Scroll::default(),
|
||||
});
|
||||
self.dialogs.waiting = None;
|
||||
self.capture(false);
|
||||
}
|
||||
|
||||
/// `clearDialog`: the dialog closes (under the warning screen, Back then
|
||||
/// returns to what was open before it).
|
||||
pub(super) fn clear_dialog(&mut self) {
|
||||
if self.dialogs.open.take().is_some() && !self.dialog_open() {
|
||||
self.dialog_closed();
|
||||
}
|
||||
}
|
||||
|
||||
/// Every dialog screen goes (a disconnect, or the level loading screen).
|
||||
pub(super) fn close_dialogs(&mut self) {
|
||||
self.dialogs = DialogState::default();
|
||||
}
|
||||
|
||||
fn dialog_closed(&mut self) {
|
||||
if self.player.is_some() && self.screen == super::Screen::Playing && self.title.is_none() {
|
||||
self.capture(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// `DialogScreen.runAction`: the click event, then the screen the dialog's
|
||||
/// `after_action` leaves.
|
||||
fn run_dialog_action(&mut self, click: Option<Click>, after: AfterAction) -> Result<()> {
|
||||
match after {
|
||||
AfterAction::None => {}
|
||||
AfterAction::Close => self.dialogs.open = None,
|
||||
AfterAction::WaitForResponse => {
|
||||
self.dialogs.open = None;
|
||||
self.dialogs.waiting = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
match click {
|
||||
Some(Click::Custom { id, payload }) => {
|
||||
if let Some(r) = &self.remote {
|
||||
r.session.send_custom_click(&id, payload);
|
||||
}
|
||||
}
|
||||
Some(Click::RunCommand(command)) => {
|
||||
// In configuration there is nothing to run it (vanilla warns).
|
||||
if self.player.is_some() {
|
||||
let command = command.strip_prefix('/').unwrap_or(&command);
|
||||
self.send_chat(&format!("/{command}"));
|
||||
} else {
|
||||
log::warn!(
|
||||
"Horizon: commands are not supported in configuration, trying to run '{command}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
Some(Click::ShowDialog(dialog)) => self.show_dialog_ref(&dialog),
|
||||
Some(Click::CopyToClipboard(value)) => {
|
||||
use horizon_client::clipboard::Clipboard;
|
||||
self.clipboard.set(&value);
|
||||
}
|
||||
Some(other) => log::info!("Horizon: dialog action {other:?} is not supported yet"),
|
||||
None => {}
|
||||
}
|
||||
if !self.dialog_open() {
|
||||
self.dialog_closed();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A `show_dialog` click event's dialog: a registry id or the dialog itself.
|
||||
fn show_dialog_ref(&mut self, dialog: &Tag) {
|
||||
match dialog {
|
||||
Tag::String(id) => {
|
||||
let id = id.to_string_lossy();
|
||||
let name = if id.contains(':') {
|
||||
id.clone()
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
};
|
||||
let found = self.remote.as_ref().and_then(|r| {
|
||||
let entries = r.registries.registries.get("minecraft:dialog")?;
|
||||
entries.iter().find(|(n, _)| *n == name)?.1.clone()
|
||||
});
|
||||
match found {
|
||||
Some(tag) => self.show_dialog(&tag),
|
||||
None => log::warn!("Horizon: unknown dialog {id}"),
|
||||
}
|
||||
}
|
||||
tag => self.show_dialog(tag),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ClientboundShowDialogPacket` in play: a registry entry or the dialog.
|
||||
pub(super) fn show_play_dialog(
|
||||
&mut self,
|
||||
dialog: &horizon_protocol::packets::play::DialogHolder,
|
||||
) {
|
||||
use horizon_protocol::packets::play::DialogHolder;
|
||||
match dialog {
|
||||
DialogHolder::Direct(tag) => self.show_dialog(tag),
|
||||
DialogHolder::Registry(id) => {
|
||||
let tag = self
|
||||
.remote
|
||||
.as_ref()
|
||||
.and_then(|r| r.registries.data("minecraft:dialog", *id).cloned());
|
||||
match tag {
|
||||
Some(tag) => self.show_dialog(&tag),
|
||||
None => log::warn!("Horizon: unknown dialog {id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dialog_layout(&self) -> Option<Layout> {
|
||||
let open = self.dialogs.open.as_ref()?;
|
||||
Some(Layout::new(
|
||||
&open.dialog,
|
||||
&self.gui.atlas.font,
|
||||
self.gui_size(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn draw_dialog(&mut self, batch: &mut HudBatch) {
|
||||
if !self.dialog_open() {
|
||||
return;
|
||||
}
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let cursor = self.cursor;
|
||||
let atlas = &self.gui.atlas;
|
||||
if self.player.is_none() {
|
||||
// In place of the connecting screen, on its background.
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255));
|
||||
}
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.player.is_some());
|
||||
if self.dialogs.warning {
|
||||
let (title, message, [disconnect, back]) = warning_texts();
|
||||
Confirm::new(&atlas.font, (w, h), &title, &message).draw(
|
||||
batch,
|
||||
atlas,
|
||||
cursor,
|
||||
[&disconnect, &back],
|
||||
);
|
||||
return;
|
||||
}
|
||||
if let Some(since) = self.dialogs.waiting {
|
||||
// HeaderAndFooterLayout(33, 0) centred: the title, the button 33 below.
|
||||
let ticks = (since.elapsed().as_millis() / 50) as u32;
|
||||
let (label, visible, active) = waiting_button(ticks);
|
||||
let title = Text::translate("gui.waitingForResponse.title", &[]);
|
||||
let top = ((h - 53.0) / 2.0).trunc();
|
||||
let tw = atlas.font.width_text(&title);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&title,
|
||||
((w - tw) / 2.0).trunc(),
|
||||
top + 12.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
if visible {
|
||||
let (bx, by) = (((w - 200.0) / 2.0).trunc(), top + 33.0);
|
||||
let hover = ui::hovered(cursor, bx, by, 200.0, 20.0);
|
||||
ui::button(batch, atlas, bx, by, 200.0, 20.0, &label, active, hover);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(layout) = self.dialog_layout() else {
|
||||
return;
|
||||
};
|
||||
let Some(open) = self.dialogs.open.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.gui.atlas;
|
||||
let [ax, ay, aw, ah] = layout.area;
|
||||
open.scroll.clamp(ay, ay + ah, layout.content);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&open.dialog.title,
|
||||
layout.title.0,
|
||||
layout.title.1,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
let [wx, wy, ww, wh] = layout.warning;
|
||||
let warn_hover = ui::hovered(cursor, wx, wy, ww, wh);
|
||||
horizon_client::widgets::record("warning", layout.warning, true);
|
||||
batch.sprite_scaled(
|
||||
atlas,
|
||||
WARNING_SPRITES[if warn_hover { 2 } else { 0 }],
|
||||
wx,
|
||||
wy,
|
||||
ww,
|
||||
wh,
|
||||
u32::MAX,
|
||||
);
|
||||
let buttons = open.dialog.buttons();
|
||||
let in_area = |y: f32| y >= ay && y < ay + ah;
|
||||
let mut tooltip = None;
|
||||
let mut start = None;
|
||||
for (part, clipped) in layout.placed(open.scroll.amount) {
|
||||
if clipped && start.is_none() {
|
||||
start = Some(batch.vertices.len());
|
||||
} else if !clipped && let Some(s) = start.take() {
|
||||
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
|
||||
}
|
||||
match part {
|
||||
Part::Line(text, x, y) => {
|
||||
batch.text_styled(atlas, &text, x, y, u32::MAX, true);
|
||||
}
|
||||
Part::Button { index, rect } => {
|
||||
let [x, y, bw, bh] = rect;
|
||||
let hover =
|
||||
(!clipped || in_area(cursor.1)) && ui::hovered(cursor, x, y, bw, bh);
|
||||
let b = buttons[index];
|
||||
ui::button(batch, atlas, x, y, bw, bh, &b.label, true, hover);
|
||||
if hover && let Some(t) = &b.tooltip {
|
||||
tooltip = Some(t.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(s) = start {
|
||||
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
|
||||
}
|
||||
if layout.content > ah {
|
||||
ui::scrollbar(
|
||||
batch,
|
||||
atlas,
|
||||
ax + aw - 6.0,
|
||||
ay,
|
||||
ay + ah,
|
||||
layout.content,
|
||||
open.scroll.amount,
|
||||
);
|
||||
}
|
||||
if warn_hover {
|
||||
tooltip = Some(Text::translate("menu.custom_screen_info.tooltip", &[]));
|
||||
}
|
||||
if let Some(t) = tooltip {
|
||||
let lines: Vec<Text> = atlas
|
||||
.font
|
||||
.split_lines(&t, 170.0)
|
||||
.into_iter()
|
||||
.map(|l| l.0)
|
||||
.collect();
|
||||
ui::tooltip(batch, atlas, &lines, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
/// A left click on a dialog screen.
|
||||
pub(super) fn dialog_click(&mut self) -> Result<()> {
|
||||
let cursor = self.cursor;
|
||||
if self.dialogs.warning {
|
||||
let (title, message, _) = warning_texts();
|
||||
let answer = Confirm::new(&self.gui.atlas.font, self.gui_size(), &title, &message)
|
||||
.answer_at(cursor);
|
||||
match answer {
|
||||
Some(true) => {
|
||||
self.audio.play_button_click();
|
||||
let reason = Text::translate("menu.custom_screen_info.disconnect", &[]);
|
||||
return self.leave_server(Some(reason.plain()));
|
||||
}
|
||||
Some(false) => {
|
||||
self.audio.play_button_click();
|
||||
self.dialogs.warning = false;
|
||||
if !self.dialog_open() {
|
||||
self.dialog_closed();
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(since) = self.dialogs.waiting {
|
||||
let (w, h) = self.gui_size();
|
||||
let active = waiting_button((since.elapsed().as_millis() / 50) as u32).2;
|
||||
let (bx, by) = (
|
||||
((w - 200.0) / 2.0).trunc(),
|
||||
((h - 53.0) / 2.0).trunc() + 33.0,
|
||||
);
|
||||
if active && ui::hovered(cursor, bx, by, 200.0, 20.0) {
|
||||
self.audio.play_button_click();
|
||||
self.dialogs.waiting = None;
|
||||
self.dialog_closed();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(layout) = self.dialog_layout() else {
|
||||
return Ok(());
|
||||
};
|
||||
let [wx, wy, ww, wh] = layout.warning;
|
||||
if ui::hovered(cursor, wx, wy, ww, wh) {
|
||||
self.audio.play_button_click();
|
||||
self.dialogs.warning = true;
|
||||
return Ok(());
|
||||
}
|
||||
let Some(open) = self.dialogs.open.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
let [_, ay, _, ah] = layout.area;
|
||||
let mut action = None;
|
||||
for (part, clipped) in layout.placed(open.scroll.amount) {
|
||||
if clipped && !(cursor.1 >= ay && cursor.1 < ay + ah) {
|
||||
continue;
|
||||
}
|
||||
match part {
|
||||
Part::Button {
|
||||
index,
|
||||
rect: [x, y, w, h],
|
||||
} if ui::hovered(cursor, x, y, w, h) => {
|
||||
action = Some(index);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let Some(index) = action else {
|
||||
return Ok(());
|
||||
};
|
||||
self.audio.play_button_click();
|
||||
let d = &open.dialog;
|
||||
let click = d.buttons()[index]
|
||||
.action
|
||||
.as_ref()
|
||||
.and_then(|a| a.click(&d.inputs, &open.values));
|
||||
let after = d.after_action;
|
||||
self.run_dialog_action(click, after)
|
||||
}
|
||||
|
||||
/// The mouse wheel over a dialog: its body scrolls 10 a step.
|
||||
pub(super) fn dialog_scroll(&mut self, delta: f32) {
|
||||
let Some(layout) = self.dialog_layout() else {
|
||||
return;
|
||||
};
|
||||
if let Some(open) = self.dialogs.open.as_mut() {
|
||||
let [_, ay, _, ah] = layout.area;
|
||||
open.scroll.wheel(delta, 10.0, ay, ay + ah, layout.content);
|
||||
}
|
||||
}
|
||||
|
||||
/// A key pressed on a dialog screen: Escape closes what allows it.
|
||||
pub(super) fn dialog_key(&mut self, key: KeyCode) -> Result<()> {
|
||||
let escape = key == KeyCode::Escape;
|
||||
if self.dialogs.warning {
|
||||
if escape {
|
||||
self.dialogs.warning = false;
|
||||
if !self.dialog_open() {
|
||||
self.dialog_closed();
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(since) = self.dialogs.waiting {
|
||||
// shouldCloseOnEsc: once Back works.
|
||||
if escape && waiting_button((since.elapsed().as_millis() / 50) as u32).2 {
|
||||
self.dialogs.waiting = None;
|
||||
self.dialog_closed();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(open) = self.dialogs.open.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
if escape {
|
||||
if !open.dialog.can_close_with_escape {
|
||||
return Ok(());
|
||||
}
|
||||
// onClose: the cancel action, and the screen closes.
|
||||
let d = &open.dialog;
|
||||
let click = d.on_cancel().and_then(|a| a.click(&d.inputs, &open.values));
|
||||
return self.run_dialog_action(click, AfterAction::Close);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What `state` reports: the open dialog and its values, or the waiting
|
||||
/// and warning screens.
|
||||
pub(super) fn dialog_status(&self) -> serde_json::Value {
|
||||
let d = &self.dialogs;
|
||||
let screen = if d.warning {
|
||||
Some("warning")
|
||||
} else if d.waiting.is_some() {
|
||||
Some("waiting_for_response")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let open = d.open.as_ref().map(|open| open.dialog.json(&open.values));
|
||||
serde_json::json!({ "open": open, "screen": screen })
|
||||
}
|
||||
}
|
||||
@@ -1971,9 +1971,10 @@ impl Game<'_> {
|
||||
self.spawn_orbs([p.x, p.y, p.z], (xp as f32 * 0.08) as u32);
|
||||
}
|
||||
if t == 1 {
|
||||
// Level event 1028: the death roar, heard everywhere.
|
||||
self.audio
|
||||
.play("minecraft:entity.ender_dragon.death", None, 5.0, 1.0);
|
||||
// EnderDragon.tickDeath: global level event 1028, the death
|
||||
// roar, heard everywhere.
|
||||
let at = [p.x, p.y, p.z].map(|v| v.floor() as i32);
|
||||
self.global_level_event(1028, at, 0);
|
||||
}
|
||||
if let Some(d) = self.dragon.as_mut() {
|
||||
d.position.y += 0.1;
|
||||
|
||||
@@ -4,7 +4,12 @@
|
||||
//! inactive until the dragon dies.
|
||||
use super::{Dim, Game};
|
||||
use horizon_client::{
|
||||
Result, environment::Environment, items::ItemStack, mesher::Vertex, motion::PlayerMotion,
|
||||
Result,
|
||||
environment::Environment,
|
||||
items::ItemStack,
|
||||
mesher::Vertex,
|
||||
motion::PlayerMotion,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
vanillagen::VanillaTerrain,
|
||||
};
|
||||
use horizon_core::{
|
||||
@@ -311,9 +316,10 @@ impl Game<'_> {
|
||||
)?;
|
||||
}
|
||||
}
|
||||
// Global LevelEvent 1038: END_PORTAL_SPAWN.
|
||||
self.audio
|
||||
.play("minecraft:block.end_portal.spawn", None, 1.0, 1.0);
|
||||
// EnderEyeItem.useOn: global level event 1038 (END_PORTAL_SPAWN),
|
||||
// heard by every player (vanilla places it at the frame's corner
|
||||
// + (1, 0, 1); only its direction matters).
|
||||
self.global_level_event(1038, c, 0);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
@@ -1122,6 +1128,35 @@ impl Game<'_> {
|
||||
self.end.eyes = eyes;
|
||||
}
|
||||
|
||||
/// `EyeOfEnder.tick` on a client: behind each eye (a quarter of its last
|
||||
/// move back), four bubbles in water, else a portal particle.
|
||||
pub(super) fn eye_particles(&mut self) {
|
||||
for i in 0..self.end.eyes.len() {
|
||||
let e = &self.end.eyes[i];
|
||||
let movement = (e.position - e.previous).to_array();
|
||||
let origin = (e.position - (e.position - e.previous) * 0.25).to_array();
|
||||
let block = origin.map(|v| v.floor() as i32);
|
||||
let water = self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(block[0], block[1], block[2]))
|
||||
.fluid
|
||||
== horizon_client::blocks::Fluid::Water;
|
||||
if water {
|
||||
let bubble = ParticleOptions::simple(ParticleType::Bubble);
|
||||
for _ in 0..4 {
|
||||
self.particles.add(&bubble, origin, movement);
|
||||
}
|
||||
} else {
|
||||
let r = self.particles.random();
|
||||
let x = origin[0] + r.next_double() * 0.6 - 0.3;
|
||||
let z = origin[2] + r.next_double() * 0.6 - 0.3;
|
||||
let portal = ParticleOptions::simple(ParticleType::Portal);
|
||||
self.particles
|
||||
.add(&portal, [x, origin[1] - 0.5, z], movement);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// ThrownItemRenderer: the ender eye item facing the camera.
|
||||
fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
|
||||
let Some(r) = self.gui.atlas.sprites.get("item/ender_eye").copied() else {
|
||||
|
||||
@@ -45,7 +45,8 @@ pub(super) struct RulesScreen {
|
||||
initial: GameRules,
|
||||
/// IntegerRuleEntry's boxes, by rule.
|
||||
numbers: Vec<(&'static str, EditBox)>,
|
||||
scroll: f32,
|
||||
/// RuleList's scrolling: the wheel and the held scrollbar.
|
||||
scroll: ui::Scroll,
|
||||
/// ConfirmScreen "Game Rule Changes" in its place.
|
||||
confirm: bool,
|
||||
}
|
||||
@@ -120,7 +121,7 @@ impl RulesScreen {
|
||||
values: rules.clone(),
|
||||
initial: rules.clone(),
|
||||
numbers,
|
||||
scroll: 0.0,
|
||||
scroll: ui::Scroll::default(),
|
||||
confirm: false,
|
||||
}
|
||||
}
|
||||
@@ -156,12 +157,17 @@ impl RulesScreen {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn max_scroll(rows: usize, h: f32) -> f32 {
|
||||
(ROW * rows as f32 + 4.0 - (h - HEADER - FOOTER)).max(0.0)
|
||||
}
|
||||
/// Entry `i`'s top: 2 under the list's top, less the scroll.
|
||||
fn row_top(&self, i: usize) -> f32 {
|
||||
HEADER + 2.0 - self.scroll.trunc() + ROW * i as f32
|
||||
HEADER + 2.0 - self.scroll.amount.trunc() + ROW * i as f32
|
||||
}
|
||||
/// The list's scrollbar column (AbstractSelectionList: 6 pixels right of
|
||||
/// the entries) and the pixels it scrolls.
|
||||
fn bar(w: f32) -> f32 {
|
||||
row_left(w) + ROW_WIDTH + 6.0 + 2.0
|
||||
}
|
||||
fn content(&self) -> f32 {
|
||||
ROW * self.rows().len() as f32 + 4.0
|
||||
}
|
||||
/// getEntryAtPosition: the row under the pointer, inside the list.
|
||||
fn hovered(&self, rows: usize, (x, y): (f32, f32), (w, h): (f32, f32)) -> Option<usize> {
|
||||
@@ -212,10 +218,28 @@ impl RulesScreen {
|
||||
/// The mouse wheel (AbstractSelectionList: half an entry a step).
|
||||
pub(super) fn wheel(&mut self, delta: f32, h: f32) {
|
||||
if !self.confirm {
|
||||
let max = Self::max_scroll(self.rows().len(), h);
|
||||
self.scroll = (self.scroll - delta * ROW / 2.0).clamp(0.0, max);
|
||||
let content = self.content();
|
||||
self.scroll
|
||||
.wheel(delta, ROW / 2.0, HEADER, h - FOOTER, content);
|
||||
}
|
||||
}
|
||||
/// A press on the scrollbar holds it (AbstractSelectionList.updateScrolling).
|
||||
pub(super) fn press_scrollbar(&mut self, cursor: (f32, f32), (w, h): (f32, f32)) -> bool {
|
||||
let content = self.content();
|
||||
self.scroll
|
||||
.press(cursor, Self::bar(w), HEADER, h - FOOTER, content)
|
||||
}
|
||||
/// The pointer moved while the scrollbar is held.
|
||||
pub(super) fn drag(&mut self, y: f32, h: f32) {
|
||||
if self.scroll.held() {
|
||||
let content = self.content();
|
||||
self.scroll.drag(y, HEADER, h - FOOTER, content);
|
||||
}
|
||||
}
|
||||
/// The button came up: the scrollbar lets go.
|
||||
pub(super) fn release(&mut self) {
|
||||
self.scroll.release();
|
||||
}
|
||||
fn focused(&mut self) -> Option<(Option<&'static str>, &mut EditBox)> {
|
||||
if self.search.focused {
|
||||
return Some((None, &mut self.search));
|
||||
@@ -229,7 +253,7 @@ impl RulesScreen {
|
||||
/// number sets its rule when valid (IntegerRuleEntry's responder).
|
||||
fn edited(&mut self, rule: Option<&'static str>) {
|
||||
let Some(name) = rule else {
|
||||
self.scroll = 0.0;
|
||||
self.scroll.amount = 0.0;
|
||||
return;
|
||||
};
|
||||
let Some(r) = gamerules::rule(name) else {
|
||||
@@ -286,6 +310,11 @@ impl RulesScreen {
|
||||
if on(cx, cy, 150.0, 20.0) {
|
||||
return self.close();
|
||||
}
|
||||
// A press on the scrollbar holds it and clicks nothing else.
|
||||
if self.press_scrollbar(cursor, size) {
|
||||
self.unfocus();
|
||||
return None;
|
||||
}
|
||||
// A click moves the focus to the widget under it.
|
||||
let (sx, sy) = search_at(w);
|
||||
if on(sx, sy, SEARCH_WIDTH, 15.0) {
|
||||
@@ -360,7 +389,8 @@ impl RulesScreen {
|
||||
return;
|
||||
}
|
||||
let rows = self.rows();
|
||||
self.scroll = self.scroll.clamp(0.0, Self::max_scroll(rows.len(), h));
|
||||
let content = ROW * rows.len() as f32 + 4.0;
|
||||
self.scroll.clamp(HEADER, h - FOOTER, content);
|
||||
// RuleList: the in-world list background, its entries clipped to it,
|
||||
// then the separators and scrollbar.
|
||||
ui::list_background(batch, atlas, HEADER, h - FOOTER, true);
|
||||
@@ -421,16 +451,14 @@ impl RulesScreen {
|
||||
}
|
||||
batch.clip_since(first, 0.0, HEADER, w, h - FOOTER);
|
||||
ui::separators(batch, atlas, HEADER, h - FOOTER, true);
|
||||
let content = ROW * rows.len() as f32 + 4.0;
|
||||
let bar_x = left + ROW_WIDTH + 6.0 + 2.0;
|
||||
ui::scrollbar(
|
||||
batch,
|
||||
atlas,
|
||||
bar_x,
|
||||
Self::bar(w),
|
||||
HEADER,
|
||||
h - FOOTER,
|
||||
content,
|
||||
self.scroll.trunc(),
|
||||
self.scroll.amount.trunc(),
|
||||
);
|
||||
// The header: the title centred over the search box.
|
||||
let title = Text::translate("editGamerule.title", &[]);
|
||||
@@ -536,6 +564,29 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// AbstractScrollArea: a press on the bar holds it, a drag moves the
|
||||
/// list (to the ends past them), a release lets go.
|
||||
#[test]
|
||||
fn the_scroll_bar_can_be_held_dragged_and_let_go() {
|
||||
let mut s = RulesScreen::new(&GameRules::default());
|
||||
let (w, h) = (427.0, 240.0);
|
||||
let (top, bottom, content) = (HEADER, h - FOOTER, s.content());
|
||||
assert!(
|
||||
content > bottom - top,
|
||||
"the rules overflow a 240-high screen"
|
||||
);
|
||||
let bar = RulesScreen::bar(w);
|
||||
assert!(!s.press_scrollbar((bar - 4.0, top + 5.0), (w, h)));
|
||||
assert!(s.press_scrollbar((bar + 3.0, top + 5.0), (w, h)));
|
||||
s.drag(top + 40.0, h);
|
||||
assert!(s.scroll.amount > 0.0);
|
||||
s.drag(bottom + 10.0, h);
|
||||
assert_eq!(s.scroll.amount, content - (bottom - top));
|
||||
s.release();
|
||||
s.drag(top, h);
|
||||
assert_eq!(s.scroll.amount, content - (bottom - top));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_change_rules_and_bad_numbers_hold_done() {
|
||||
let mut s = RulesScreen::new(&GameRules::default());
|
||||
|
||||
@@ -162,6 +162,13 @@ fn mob_meta(
|
||||
meta.push((3, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
}
|
||||
// LivingEntity.DATA_LIVING_ENTITY_FLAGS: using an item 1, in the off
|
||||
// hand 2 (a skeleton draws its bow, a witch raises her potion).
|
||||
let using = i8::from(m.extra.using_item > 0) | i8::from(m.extra.using_off_hand) << 1;
|
||||
if using != 0 {
|
||||
meta.push((8, serializer::BYTE, Value::Byte(using)));
|
||||
}
|
||||
defaults.push((8, serializer::BYTE, Value::Byte(0)));
|
||||
// LivingEntity.DATA_HEALTH_ID: defined as 1, then set to the max health.
|
||||
let health = m.health.max(0.0);
|
||||
if health != 1.0 {
|
||||
@@ -293,6 +300,21 @@ fn mob_meta(
|
||||
meta.push((18, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
}
|
||||
// Pillager.IS_CHARGING_CROSSBOW: the charge pose and the held
|
||||
// item's loading animation.
|
||||
"minecraft:pillager" => {
|
||||
if e.flag {
|
||||
meta.push((17, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
defaults.push((17, serializer::BOOLEAN, Value::Bool(false)));
|
||||
}
|
||||
// SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose.
|
||||
"minecraft:evoker" | "minecraft:illusioner" => {
|
||||
if e.variant2 != 0 {
|
||||
meta.push((17, serializer::BYTE, Value::Byte(e.variant2 as i8)));
|
||||
}
|
||||
defaults.push((17, serializer::BYTE, Value::Byte(0)));
|
||||
}
|
||||
// Enderman.DATA_CARRY_STATE.
|
||||
"minecraft:enderman" => {
|
||||
if let Some(state) = e.carried {
|
||||
@@ -1114,9 +1136,9 @@ 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, nor bone meal's growth (BoneMealItem.useOn's
|
||||
// levelEvent names no player).
|
||||
let except = if matches!(*id, 2015 | 1505) {
|
||||
// particles, bone meal's growth, or anvil result sounds
|
||||
// (these levelEvent calls name no excluded player).
|
||||
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
|
||||
None
|
||||
} else {
|
||||
self.lan_acting
|
||||
@@ -1155,6 +1177,9 @@ impl Game<'_> {
|
||||
for (id, event, at) in std::mem::take(&mut self.lan_entity_events) {
|
||||
host.hub.entity_event(id, event, at);
|
||||
}
|
||||
for (kind, pos, data) in std::mem::take(&mut self.lan_global_events) {
|
||||
host.hub.global_level_event(kind, pos, data);
|
||||
}
|
||||
self.lan_broadcast_effects(host);
|
||||
if host.hub.guests.is_empty() {
|
||||
host.mob_state.clear();
|
||||
|
||||
@@ -1808,14 +1808,13 @@ impl Game<'_> {
|
||||
g.use_delay -= 1;
|
||||
}
|
||||
});
|
||||
// ServerPlayerGameMode.handleBlockBreakAction: a creative
|
||||
// player's START breaks the block once (destroyAndAck) and
|
||||
// leaves nothing being destroyed; its client sends no STOP.
|
||||
// Kept, the dig broke whatever was put there next, every
|
||||
// destroy delay, for as long as the player broke nothing else.
|
||||
// ServerPlayerGameMode.handleBlockBreakAction: creative and
|
||||
// instant survival STARTs finish without a STOP from the client.
|
||||
// tick_mining clears mining on completion; forget the START too,
|
||||
// so a flower or crop planted here later is not broken again.
|
||||
if digging.is_some()
|
||||
&& host.hub.guests[gi].creative()
|
||||
&& let Some(play) = host.play.get_mut(&conn)
|
||||
&& (host.hub.guests[gi].creative() || play.mining.is_none())
|
||||
{
|
||||
play.digging = None;
|
||||
}
|
||||
|
||||
@@ -161,12 +161,12 @@ impl Game<'_> {
|
||||
+ (self.particles.random().next_float() - self.particles.random().next_float())
|
||||
* 0.2)
|
||||
* 0.7;
|
||||
self.audio.play(
|
||||
"minecraft:entity.generic.explode",
|
||||
Some(p.center),
|
||||
4.0,
|
||||
pitch,
|
||||
);
|
||||
// The packet's explosionSound: a wind charge's burst, a bed's
|
||||
// or anchor's blast, a modded sound.
|
||||
let sound = self
|
||||
.remote_sound_name(&p.sound)
|
||||
.unwrap_or_else(|| "minecraft:entity.generic.explode".to_owned());
|
||||
self.audio.play(&sound, Some(p.center), 4.0, pitch);
|
||||
}
|
||||
if let Some(options) = self.received_particle(&p.particle, p.center) {
|
||||
self.particles.add(&options, p.center, [1.0, 0.0, 0.0]);
|
||||
|
||||
@@ -802,6 +802,27 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer moved while a list's scrollbar is held: the game rules'
|
||||
/// list follows it (AbstractSelectionList.mouseDragged).
|
||||
pub(super) fn world_options_drag(&mut self) {
|
||||
let h = self.gui_size().1;
|
||||
if let Some(o) = self.world_options.as_mut()
|
||||
&& o.view == View::GameRules
|
||||
&& let Some(rules) = o.rules.as_mut()
|
||||
{
|
||||
rules.drag(self.cursor.1, h);
|
||||
}
|
||||
}
|
||||
|
||||
/// The button came up: a held scrollbar lets go (onRelease).
|
||||
pub(super) fn world_options_release(&mut self) {
|
||||
if let Some(o) = self.world_options.as_mut()
|
||||
&& let Some(rules) = o.rules.as_mut()
|
||||
{
|
||||
rules.release();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn world_options_click(&mut self) {
|
||||
let Some(mut o) = self.world_options.take() else {
|
||||
return;
|
||||
|
||||
@@ -79,6 +79,8 @@ impl Game<'_> {
|
||||
if horizon_client::mobs::leash::remove(m).is_none() {
|
||||
return;
|
||||
}
|
||||
// Leashable.tickLeash gates a dying entity's lead drop on entity_drops.
|
||||
let drop = drop && (m.alive() || self.ui.rules.bool("entity_drops"));
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
if sound {
|
||||
self.lead_sound("break", at);
|
||||
|
||||
@@ -101,6 +101,39 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `ServerLevel.globalLevelEvent`: heard by every player on the server
|
||||
/// (an end portal opening, the dragon's death roar): here, and sent to
|
||||
/// every guest whatever their dimension.
|
||||
pub(super) fn global_level_event(&mut self, id: i32, pos: [i32; 3], data: i32) {
|
||||
self.global_level_event_sound(id, pos);
|
||||
if self.audio.capture.is_some() {
|
||||
self.lan_global_events.push((id, pos, data));
|
||||
}
|
||||
}
|
||||
/// `LevelEventHandler.globalLevelEvent`: the sound two blocks from the
|
||||
/// camera towards the event, so it is heard from anywhere.
|
||||
pub(super) fn global_level_event_sound(&mut self, id: i32, pos: [i32; 3]) {
|
||||
let (sound, volume) = match id {
|
||||
1023 => ("minecraft:entity.wither.spawn", 1.0),
|
||||
1028 => ("minecraft:entity.ender_dragon.death", 5.0),
|
||||
1038 => ("minecraft:block.end_portal.spawn", 1.0),
|
||||
_ => return,
|
||||
};
|
||||
let at = self.eye_position().map(|eye| {
|
||||
let d = [
|
||||
f64::from(pos[0]) + 0.5 - eye[0],
|
||||
f64::from(pos[1]) + 0.5 - eye[1],
|
||||
f64::from(pos[2]) + 0.5 - eye[2],
|
||||
];
|
||||
let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
if length < 1.0e-4 {
|
||||
return eye;
|
||||
}
|
||||
[0, 1, 2].map(|k| eye[k] + d[k] / length * 2.0)
|
||||
});
|
||||
// Each guest plays it from the global packet.
|
||||
self.audio.play_unshared(sound, at, volume, 1.0);
|
||||
}
|
||||
/// Queue and play level event `id` at `pos` (`Level.levelEvent`).
|
||||
pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) {
|
||||
self.level_events.push(LevelEvent::LevelEvent {
|
||||
|
||||
@@ -377,7 +377,12 @@ impl Game<'_> {
|
||||
}
|
||||
*next += self.clock.tick_duration();
|
||||
if *next > now {
|
||||
std::thread::sleep(*next - now);
|
||||
// A `/pregen` task keeps the workers fed until the next tick.
|
||||
self.pump_pregen(*next);
|
||||
let now = Instant::now();
|
||||
if *next > now {
|
||||
std::thread::sleep(*next - now);
|
||||
}
|
||||
} else if now - *next > Duration::from_secs(2) {
|
||||
*next = now;
|
||||
}
|
||||
@@ -385,7 +390,7 @@ impl Game<'_> {
|
||||
|
||||
/// The levels this server tick runs, in `MinecraftServer.levels` order
|
||||
/// (the Overworld, the Nether, the End): every level with a player in
|
||||
/// it, or the Overworld while nobody is online.
|
||||
/// it or a `/pregen` task, or the Overworld while nobody is online.
|
||||
pub(super) fn levels_to_tick(&self) -> Vec<Dim> {
|
||||
let guests = self
|
||||
.lan
|
||||
@@ -393,7 +398,9 @@ impl Game<'_> {
|
||||
.map_or(&[][..], |h| h.hub.guests.as_slice());
|
||||
let mut dims: Vec<Dim> = [Dim::Overworld, Dim::Nether, Dim::End]
|
||||
.into_iter()
|
||||
.filter(|d| guests.iter().any(|g| g.dimension == d.id()))
|
||||
.filter(|d| {
|
||||
guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d)
|
||||
})
|
||||
.collect();
|
||||
if dims.is_empty() {
|
||||
dims.push(Dim::Overworld);
|
||||
|
||||
@@ -1463,6 +1463,7 @@ impl Game<'_> {
|
||||
lid: &lid,
|
||||
sign: &|_| None,
|
||||
banner: &|_| Vec::new(),
|
||||
skull: &|_| None,
|
||||
glyph: &|c| self.gui.atlas.glyph_cell(c),
|
||||
};
|
||||
self.res
|
||||
|
||||
@@ -259,7 +259,7 @@ impl Game<'_> {
|
||||
// ItemInHandLayer submits with OverlayTexture.NO_OVERLAY: no hurt tint.
|
||||
for (item, off_hand) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] {
|
||||
let Some(item) = item else { continue };
|
||||
let left = off_hand != mob.extra.main_hand_left;
|
||||
let left = off_hand != mob.main_arm_left();
|
||||
let Some(t) =
|
||||
render::held_item_transform(mob, alpha as f32, camera, self.res.mob_data(), left)
|
||||
else {
|
||||
@@ -305,7 +305,7 @@ impl Game<'_> {
|
||||
.player_model
|
||||
.as_ref()
|
||||
.is_some_and(|p| std::ptr::eq(p, mob));
|
||||
owner.main_arm_left = mob.extra.main_hand_left;
|
||||
owner.main_arm_left = mob.main_arm_left();
|
||||
if off_hand == mob.extra.using_off_hand && mob.extra.using_item > 0 {
|
||||
owner.using_this_item = true;
|
||||
owner.use_duration = 72_000;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Capability `input` (docs/mods.md): the use button on items a mod claims,
|
||||
//! and the mod's own keys. With no mod claiming items or keys, each hook
|
||||
//! here returns after one check.
|
||||
use super::Game;
|
||||
use winit::{event::MouseButton, keyboard::KeyCode};
|
||||
#[cfg(feature = "mods")]
|
||||
use {super::Screen, horizon_mods::HeldItem};
|
||||
|
||||
/// A claimed item's use while the button is down.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) struct ModUse {
|
||||
item: HeldItem,
|
||||
/// `Game::ticks` when it started.
|
||||
since: u64,
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "mods"))]
|
||||
impl Game<'_> {
|
||||
pub(super) fn mod_use(&mut self, _button: MouseButton, _pressed: bool) -> bool {
|
||||
false
|
||||
}
|
||||
pub(super) fn mod_key(&mut self, _key: KeyCode, _pressed: bool, _repeat: bool) {}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mods")]
|
||||
impl Game<'_> {
|
||||
/// The main hand's stack as `input` shows it; none when it is empty.
|
||||
pub(super) fn mod_held(&self) -> Option<HeldItem> {
|
||||
let stack = self.inventory.get(self.selected)?.as_ref()?;
|
||||
Some(HeldItem {
|
||||
id: stack.item.to_string(),
|
||||
count: stack.count,
|
||||
slot: self.selected as u32,
|
||||
})
|
||||
}
|
||||
/// The use button while playing: true when a mod claimed the held item,
|
||||
/// so the game does nothing else with it (no placing, eating, swing).
|
||||
pub(super) fn mod_use(&mut self, button: MouseButton, pressed: bool) -> bool {
|
||||
if button != MouseButton::Right || !self.mods.mods.claims_any() {
|
||||
return false;
|
||||
}
|
||||
if !pressed {
|
||||
return self.stop_mod_use();
|
||||
}
|
||||
let Some(item) = self.mod_held().filter(|h| self.mods.mods.claims(&h.id)) else {
|
||||
return false;
|
||||
};
|
||||
self.mods.mods.use_start(&item);
|
||||
self.mods.using = Some(ModUse {
|
||||
item,
|
||||
since: self.ticks,
|
||||
});
|
||||
true
|
||||
}
|
||||
/// Ends a claimed use: the button came up, the player switched slots,
|
||||
/// or a screen opened. False when none was going.
|
||||
pub(super) fn stop_mod_use(&mut self) -> bool {
|
||||
let Some(u) = self.mods.using.take() else {
|
||||
return false;
|
||||
};
|
||||
let ticks = self.ticks.saturating_sub(u.since).min(u64::from(u32::MAX)) as u32;
|
||||
self.mods.mods.use_stop(&u.item, ticks);
|
||||
true
|
||||
}
|
||||
/// Once a tick: a claimed use stops when its item leaves the hand or a
|
||||
/// screen opens, as vanilla's `releaseUsingItem`.
|
||||
pub(super) fn tick_mod_use(&mut self) {
|
||||
let Some(u) = &self.mods.using else {
|
||||
return;
|
||||
};
|
||||
let still = self
|
||||
.mod_held()
|
||||
.is_some_and(|h| h.id == u.item.id && h.slot == u.item.slot);
|
||||
if !still || self.screen != Screen::Playing {
|
||||
self.stop_mod_use();
|
||||
}
|
||||
}
|
||||
/// A key went down or up: a mod's registered key while playing (no
|
||||
/// screen) is its `key-down` / `key-up`. Vanilla's mapping on the same
|
||||
/// key still runs.
|
||||
pub(super) fn mod_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) {
|
||||
if repeat || !self.mods.mods.has_keys() {
|
||||
return;
|
||||
}
|
||||
if pressed && (self.screen != Screen::Playing || self.title.is_some()) {
|
||||
return;
|
||||
}
|
||||
if let Some(name) = horizon_client::keybinds::key_name(key) {
|
||||
self.mods.mods.key(name, pressed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Capability `render` (docs/mods.md): the shapes mods keep on the HUD,
|
||||
//! drawn by the game's own HUD renderer, and their camera shakes. Mods
|
||||
//! never supply shader code. With no mod drawing, each hook here returns
|
||||
//! after one check.
|
||||
use super::Game;
|
||||
use horizon_client::hud::HudBatch;
|
||||
#[cfg(feature = "mods")]
|
||||
use {
|
||||
horizon_client::{hud::rgba, items::ItemStack, text::Text},
|
||||
horizon_mods::Shape,
|
||||
std::time::Instant,
|
||||
};
|
||||
|
||||
/// The camera's jolts from `render.shake`, while any is fading.
|
||||
#[cfg(feature = "mods")]
|
||||
#[derive(Default)]
|
||||
pub(super) struct Shake {
|
||||
jolts: Vec<Jolt>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "mods")]
|
||||
struct Jolt {
|
||||
start: Instant,
|
||||
strength: f32,
|
||||
seconds: f32,
|
||||
}
|
||||
|
||||
/// The HUD batch's colour (ABGR) from a mod's 0xAARRGGBB.
|
||||
#[cfg(feature = "mods")]
|
||||
fn argb(color: u32) -> u32 {
|
||||
let [a, r, g, b] = color.to_be_bytes();
|
||||
rgba(r, g, b, a)
|
||||
}
|
||||
|
||||
/// The view's turn at full strength, in degrees: yaw, then pitch.
|
||||
#[cfg(feature = "mods")]
|
||||
const SHAKE_DEGREES: (f32, f32) = (3.0, 2.0);
|
||||
|
||||
#[cfg(feature = "mods")]
|
||||
impl Shake {
|
||||
pub(super) fn add(&mut self, strength: f32, seconds: f32) {
|
||||
self.jolts.push(Jolt {
|
||||
start: Instant::now(),
|
||||
strength,
|
||||
seconds,
|
||||
});
|
||||
}
|
||||
/// How far the view turns now (yaw, pitch degrees), `scale` being the
|
||||
/// player's Distortion Effects; fades jolts out and forgets ended ones.
|
||||
fn offset(&mut self, now: Instant, scale: f32) -> (f32, f32) {
|
||||
self.jolts
|
||||
.retain(|j| now.duration_since(j.start).as_secs_f32() < j.seconds);
|
||||
let mut strength = 0.0;
|
||||
for j in &self.jolts {
|
||||
let left = 1.0 - now.duration_since(j.start).as_secs_f32() / j.seconds;
|
||||
strength += j.strength * left * left;
|
||||
}
|
||||
let strength = strength.min(1.0) * scale.clamp(0.0, 1.0);
|
||||
if strength <= 0.0 {
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
// Smooth noise: sines at unrelated rates, so it never repeats visibly.
|
||||
let t = self
|
||||
.jolts
|
||||
.first()
|
||||
.map_or(0.0, |j| now.duration_since(j.start).as_secs_f32());
|
||||
let wave = |a: f32, b: f32, c: f32| {
|
||||
((t * a).sin() * 0.5 + (t * b).sin() * 0.3 + (t * c).sin() * 0.2).clamp(-1.0, 1.0)
|
||||
};
|
||||
(
|
||||
strength * SHAKE_DEGREES.0 * wave(23.0, 37.3, 51.7),
|
||||
strength * SHAKE_DEGREES.1 * wave(29.1, 43.9, 61.3),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "mods"))]
|
||||
impl Game<'_> {
|
||||
pub(super) fn draw_mod_shapes(&self, _batch: &mut HudBatch) {}
|
||||
pub(super) fn shaken_view(&mut self, yaw: f32, pitch: f32) -> (f32, f32) {
|
||||
(yaw, pitch)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mods")]
|
||||
impl Game<'_> {
|
||||
/// The running mods' HUD shapes, in order, over the HUD.
|
||||
pub(super) fn draw_mod_shapes(&self, batch: &mut HudBatch) {
|
||||
let atlas = &self.gui.atlas;
|
||||
for shape in self.mods.mods.hud_shapes() {
|
||||
match shape {
|
||||
Shape::Fill(f) => {
|
||||
let r = f.rect;
|
||||
batch.fill(atlas, r.x, r.y, r.w, r.h, argb(f.color));
|
||||
}
|
||||
Shape::Quad(q) => {
|
||||
let (a, b, c, d) = q.corners;
|
||||
let corners = [[a.x, a.y], [b.x, b.y], [c.x, c.y], [d.x, d.y]];
|
||||
batch.fill_quad(atlas, corners, argb(q.color));
|
||||
}
|
||||
Shape::Sprite(s) => {
|
||||
let r = s.rect;
|
||||
let name = s.sprite.strip_prefix("minecraft:").unwrap_or(&s.sprite);
|
||||
let name = format!("gui/sprites/{name}");
|
||||
batch.sprite_scaled(atlas, &name, r.x, r.y, r.w, r.h, argb(s.color));
|
||||
}
|
||||
Shape::Item(i) => {
|
||||
if self.res.items().get(&i.item).is_none() {
|
||||
continue;
|
||||
}
|
||||
let start = batch.vertices.len();
|
||||
let stack = ItemStack::new(i.item.as_str(), 1);
|
||||
self.draw_item_model(batch, &stack, i.at.x, i.at.y);
|
||||
batch.scale_since(start, i.at.x, i.at.y, i.scale, i.scale);
|
||||
}
|
||||
Shape::Text(t) => {
|
||||
let text = Text::literal(t.text.clone());
|
||||
let x = if t.centered {
|
||||
t.at.x - (HudBatch::text_width(atlas, &t.text) / 2.0).floor()
|
||||
} else {
|
||||
t.at.x
|
||||
};
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&text,
|
||||
x,
|
||||
t.at.y,
|
||||
argb(t.color | 0xFF00_0000),
|
||||
t.shadow,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The view's yaw and pitch after the mods' camera shakes; unchanged
|
||||
/// while none is fading.
|
||||
pub(super) fn shaken_view(&mut self, yaw: f32, pitch: f32) -> (f32, f32) {
|
||||
if self.mods.shake.jolts.is_empty() {
|
||||
return (yaw, pitch);
|
||||
}
|
||||
let scale = self.settings.file.double("screenEffectScale") as f32;
|
||||
let (dy, dp) = self.mods.shake.offset(Instant::now(), scale);
|
||||
(yaw + dy, (pitch + dp).clamp(-90.0, 90.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "mods"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn a_jolt_fades_out_and_distortion_scales_it() {
|
||||
let mut shake = Shake::default();
|
||||
shake.add(1.0, 2.0);
|
||||
let start = shake.jolts[0].start;
|
||||
let at = |s: f32| start + Duration::from_secs_f32(s);
|
||||
let size = |(y, p): (f32, f32)| y.abs() + p.abs();
|
||||
// Off with Distortion Effects at 0, inside the limits otherwise.
|
||||
assert_eq!(shake.offset(at(0.3), 0.0), (0.0, 0.0));
|
||||
let (y, p) = shake.offset(at(0.3), 1.0);
|
||||
assert!(y.abs() <= SHAKE_DEGREES.0 && p.abs() <= SHAKE_DEGREES.1);
|
||||
// Fading: the largest turn over a window shrinks.
|
||||
let mut peak = |from: f32| {
|
||||
(0..50)
|
||||
.map(|i| size(shake.offset(at(from + i as f32 * 0.002), 1.0)))
|
||||
.fold(0.0, f32::max)
|
||||
};
|
||||
let early = peak(0.1);
|
||||
let late = peak(1.6);
|
||||
assert!(late < early, "{late} !< {early}");
|
||||
// Gone once it ends.
|
||||
assert_eq!(shake.offset(at(2.1), 1.0), (0.0, 0.0));
|
||||
assert!(shake.jolts.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,13 @@ use {
|
||||
#[derive(Default)]
|
||||
pub(super) struct ModsState {
|
||||
#[cfg(feature = "mods")]
|
||||
mods: Mods,
|
||||
pub(super) mods: Mods,
|
||||
/// Capability `input`: a claimed item's use while the button is down.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) using: Option<super::mod_input::ModUse>,
|
||||
/// Capability `render`'s camera shakes.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) shake: super::mod_render::Shake,
|
||||
/// `--dev-mod PATH`: always on, reloaded when rebuilt.
|
||||
pub(super) dev: Vec<PathBuf>,
|
||||
/// When dev mods were last checked for a rebuild.
|
||||
@@ -42,6 +48,14 @@ pub(super) struct ModsState {
|
||||
/// The chat's command tree while a running mod owns commands.
|
||||
#[cfg(feature = "mods")]
|
||||
tree: Option<Dispatcher>,
|
||||
/// `command.run` lines for this window's own world, run on the next tick:
|
||||
/// run at once, their chat lines would reach the mods while their output
|
||||
/// is still being shown, and a mod answering its own lines would recurse.
|
||||
#[cfg(feature = "mods")]
|
||||
commands: Vec<String>,
|
||||
/// The server's command tree with the running mods' commands added.
|
||||
#[cfg(feature = "mods")]
|
||||
remote_tree: Option<Dispatcher>,
|
||||
/// A `ui` mod's screen or settings page while it is up.
|
||||
#[cfg(feature = "mods")]
|
||||
screen: Option<ModScreen>,
|
||||
@@ -69,6 +83,14 @@ impl ModsState {
|
||||
}
|
||||
vanilla::game_dispatcher()
|
||||
}
|
||||
/// The server's tree plus the mods' commands, when a mod owns any.
|
||||
pub(super) fn remote_dispatcher(&self) -> Option<&Dispatcher> {
|
||||
#[cfg(feature = "mods")]
|
||||
if let Some(tree) = &self.remote_tree {
|
||||
return Some(tree);
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Whether a mod runs: the chat keeps its lines for them.
|
||||
pub(super) fn running(&self) -> bool {
|
||||
#[cfg(feature = "mods")]
|
||||
@@ -178,6 +200,7 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
pub(super) fn merge_remote_tree(&mut self) {}
|
||||
pub(super) fn sync_mods(&mut self) {}
|
||||
pub(super) fn tick_mods(&mut self) {}
|
||||
pub(super) fn mods_frame(&mut self, _elapsed: Duration) {}
|
||||
@@ -267,7 +290,20 @@ impl Game<'_> {
|
||||
.peek()
|
||||
.is_some()
|
||||
.then(|| vanilla::game_dispatcher().with_mod_commands(names));
|
||||
self.merge_remote_tree();
|
||||
}
|
||||
|
||||
/// The server's command tree with the mods' commands, for the chat.
|
||||
pub(super) fn merge_remote_tree(&mut self) {
|
||||
let names: Vec<String> = self.mods.mods.commands().map(str::to_owned).collect();
|
||||
self.mods.remote_tree = self
|
||||
.remote
|
||||
.as_ref()
|
||||
.and_then(|r| r.commands.as_ref())
|
||||
.filter(|_| !names.is_empty())
|
||||
.map(|t| t.with_mod_commands(names.iter().map(String::as_str)));
|
||||
}
|
||||
|
||||
/// After the options changed: restart the mods if the list of the ones
|
||||
/// turned on did.
|
||||
pub(super) fn sync_mods(&mut self) {
|
||||
@@ -308,13 +344,24 @@ impl Game<'_> {
|
||||
game_time: self.world.game_time.max(0) as u64,
|
||||
day_time: self.world.day_time.max(0) as u64,
|
||||
});
|
||||
Snapshot { player, clock }
|
||||
Snapshot {
|
||||
player,
|
||||
clock,
|
||||
gui_size: self.gui_size(),
|
||||
held: self.mod_held(),
|
||||
}
|
||||
}
|
||||
/// A game tick.
|
||||
pub(super) fn tick_mods(&mut self) {
|
||||
// Here, at the player's level: shown inside a console call (a control
|
||||
// socket command set the hook off), they would run as the console.
|
||||
for line in std::mem::take(&mut self.mods.commands) {
|
||||
self.run_command(&line);
|
||||
}
|
||||
if !self.mods.mods.is_running() {
|
||||
return;
|
||||
}
|
||||
self.tick_mod_use();
|
||||
let snapshot = self.mod_snapshot();
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
self.mods.mods.tick(self.ticks);
|
||||
@@ -371,6 +418,19 @@ impl Game<'_> {
|
||||
}
|
||||
Output::Feedback { text, error: false } => Text::literal(text),
|
||||
Output::Feedback { text, error: true } => Text::literal(text).with_color(text::RED),
|
||||
// Vanilla's commands only: a mod running a mod command could loop.
|
||||
Output::Command { line } => {
|
||||
let name = line.split(' ').next().unwrap_or_default();
|
||||
if !vanilla_command(name) {
|
||||
// Dropped.
|
||||
} else if self.remote.is_some() {
|
||||
// The server checks the player's permissions.
|
||||
self.send_chat(&format!("/{line}"));
|
||||
} else {
|
||||
self.mods.commands.push(line);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Output::Stopped { name, reason } => {
|
||||
// Its screen goes with it: the entry's run is gone, so
|
||||
// `mod_ui_view` finds no widgets and the screen closes.
|
||||
@@ -382,6 +442,10 @@ impl Game<'_> {
|
||||
self.open_mod_screen(owner, false);
|
||||
continue;
|
||||
}
|
||||
Output::Shake { strength, seconds } => {
|
||||
self.mods.shake.add(strength, seconds);
|
||||
continue;
|
||||
}
|
||||
Output::CloseScreen { owner } => {
|
||||
if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) {
|
||||
self.close_mod_screen(false);
|
||||
@@ -425,30 +489,28 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
/// A `ui` screen's title and widgets as the mod last pushed them; None
|
||||
/// when the surface is gone (the mod stopped or closed it).
|
||||
fn mod_ui_view(&self) -> Option<(String, Vec<UiWidget>)> {
|
||||
let ms = self.mods.screen.as_ref()?;
|
||||
/// when the surface is gone (the mod stopped or closed it). Borrows
|
||||
/// `mods` only, so `self.mods.screen` may stay borrowed for the scrolls.
|
||||
fn mod_ui_view<'a>(mods: &'a Mods, ms: &ModScreen) -> Option<(&'a str, &'a [UiWidget])> {
|
||||
if ms.settings {
|
||||
let widgets = self.mods.mods.settings_widgets(ms.owner);
|
||||
let widgets = mods.settings_widgets(ms.owner);
|
||||
if widgets.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let name = self
|
||||
.mods
|
||||
.mods
|
||||
let name = mods
|
||||
.entries()
|
||||
.get(ms.owner)
|
||||
.and_then(|e| e.manifest.as_ref())
|
||||
.map_or("Mod", |m| m.name.as_str());
|
||||
Some((name.to_string(), widgets.to_vec()))
|
||||
Some((name, widgets))
|
||||
} else {
|
||||
let s: &UiScreen = self.mods.mods.screen(ms.owner)?;
|
||||
Some((s.title.clone(), s.widgets.clone()))
|
||||
let s: &UiScreen = mods.screen(ms.owner)?;
|
||||
Some((s.title.as_str(), s.widgets.as_slice()))
|
||||
}
|
||||
}
|
||||
/// The layout the mod screen's widgets get at `h`: (widget, top,
|
||||
/// height), the column being `COLUMN` wide down the middle.
|
||||
fn mod_ui_layout(&self, h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> {
|
||||
fn mod_ui_layout(h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> {
|
||||
let mut out = Vec::with_capacity(widgets.len());
|
||||
let mut y = MOD_UI_TOP;
|
||||
for w in widgets {
|
||||
@@ -513,13 +575,19 @@ impl Game<'_> {
|
||||
/// The mod's screen or settings page: its title over widgets stacked
|
||||
/// down the middle, a Done button, Esc to leave (vanilla's menus).
|
||||
pub(super) fn draw_mod_screen(&mut self, batch: &mut HudBatch) {
|
||||
if self.mods.screen.is_none() {
|
||||
let Some(ms) = self.mods.screen.as_mut() else {
|
||||
// The screen was dropped while it was up: back to the world,
|
||||
// mouse held again like any return to Playing.
|
||||
self.screen = Screen::Playing;
|
||||
if self.player.is_some() {
|
||||
self.capture(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some((title, widgets)) = self.mod_ui_view() else {
|
||||
self.mods.screen = None;
|
||||
self.screen = Screen::Playing;
|
||||
};
|
||||
let Some((title, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else {
|
||||
// The mod's surface is gone (it stopped or cleared it): leave
|
||||
// the screen like Done did, without `closed` — the mod ended it.
|
||||
self.close_mod_screen(false);
|
||||
return;
|
||||
};
|
||||
// Item icons draw in a second pass: `draw_item` needs `&mut self`,
|
||||
@@ -539,7 +607,7 @@ impl Game<'_> {
|
||||
);
|
||||
let cx = (batch.width / 2.0).floor();
|
||||
let x = cx - MOD_UI_COLUMN / 2.0;
|
||||
let layout = self.mod_ui_layout(batch.height, &widgets);
|
||||
let layout = Self::mod_ui_layout(batch.height, widgets);
|
||||
let mut list_i = 0usize;
|
||||
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
|
||||
match w {
|
||||
@@ -580,11 +648,8 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
UiWidget::List(l) => {
|
||||
let scroll = {
|
||||
let ms = self.mods.screen.as_mut().expect("checked");
|
||||
ms.scrolls.resize_with(list_i + 1, ui::Scroll::default);
|
||||
ms.scrolls[list_i]
|
||||
};
|
||||
ms.scrolls.resize_with(list_i + 1, ui::Scroll::default);
|
||||
let scroll = ms.scrolls[list_i];
|
||||
list_i += 1;
|
||||
let rows_top = wy + 4.0;
|
||||
let rows_bottom = wy + wh - 4.0;
|
||||
@@ -655,53 +720,53 @@ impl Game<'_> {
|
||||
self.close_mod_screen(true);
|
||||
return;
|
||||
}
|
||||
let Some((_, widgets)) = self.mod_ui_view() else {
|
||||
let Some(ms) = self.mods.screen.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let Some((_, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else {
|
||||
return;
|
||||
};
|
||||
let owner = ms.owner;
|
||||
let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0;
|
||||
let layout = self.mod_ui_layout(h, &widgets);
|
||||
let layout = Self::mod_ui_layout(h, widgets);
|
||||
let mut list_i = 0usize;
|
||||
// The `ui_select` call needs `&mut`: find the pick first.
|
||||
let mut hit = None;
|
||||
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
|
||||
let UiWidget::List(l) = w else { continue };
|
||||
let scroll = self
|
||||
.mods
|
||||
.screen
|
||||
.as_ref()
|
||||
.and_then(|ms| ms.scrolls.get(list_i).copied())
|
||||
.unwrap_or_default();
|
||||
let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default();
|
||||
list_i += 1;
|
||||
let row = ((cursor.1 - (wy + 4.0) + scroll.amount) / 12.0) as i64;
|
||||
if ui::hovered(cursor, x + 1.0, wy + 1.0, MOD_UI_COLUMN - 7.0, wh - 2.0)
|
||||
&& row >= 0
|
||||
&& (row as usize) < l.rows.len()
|
||||
{
|
||||
self.audio.play_button_click();
|
||||
self.mods.mods.ui_select(
|
||||
self.mods.screen.as_ref().map_or(0, |ms| ms.owner),
|
||||
l.id,
|
||||
row as u32,
|
||||
);
|
||||
self.show_mod_output();
|
||||
return;
|
||||
hit = Some((l.id, row as u32));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some((id, row)) = hit {
|
||||
self.audio.play_button_click();
|
||||
self.mods.mods.ui_select(owner, id, row);
|
||||
self.show_mod_output();
|
||||
}
|
||||
}
|
||||
/// The wheel over a `list` scrolls it.
|
||||
pub(super) fn mod_screen_scroll(&mut self, delta: f32) {
|
||||
let (w, h) = self.gui_size();
|
||||
let cursor = self.cursor;
|
||||
let Some((_, widgets)) = self.mod_ui_view() else {
|
||||
let Some(ms) = self.mods.screen.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some((_, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else {
|
||||
return;
|
||||
};
|
||||
let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0;
|
||||
let layout = self.mod_ui_layout(h, &widgets);
|
||||
let layout = Self::mod_ui_layout(h, widgets);
|
||||
let mut list_i = 0usize;
|
||||
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
|
||||
let UiWidget::List(l) = w else { continue };
|
||||
let over = ui::hovered(cursor, x, wy, MOD_UI_COLUMN, wh);
|
||||
let Some(ms) = self.mods.screen.as_mut() else {
|
||||
return;
|
||||
};
|
||||
ms.scrolls.resize_with(list_i + 1, ui::Scroll::default);
|
||||
if over {
|
||||
let content = l.rows.len() as f32 * 12.0;
|
||||
|
||||
@@ -240,6 +240,42 @@ impl Game<'_> {
|
||||
discrete: false,
|
||||
});
|
||||
}
|
||||
// ItemFrameRenderer.shouldShowName/getNameTag: only the targeted
|
||||
// frame's custom-named item, with the HUD visible (also glow frames).
|
||||
if !self.ui.hide_gui
|
||||
&& let Some((i, distance)) = self.frame_hit()
|
||||
&& self.before_block(distance)
|
||||
&& self.mob_hit().is_none_or(|(_, d)| d > distance)
|
||||
&& let Some(name) = self.item_frames[i]
|
||||
.item
|
||||
.as_ref()
|
||||
.and_then(|item| item.custom_name())
|
||||
{
|
||||
let frame = &self.item_frames[i];
|
||||
let (lo, hi) = frame.bounds();
|
||||
let center = glam::DVec3::from_array(std::array::from_fn(|a| (lo[a] + hi[a]) / 2.0));
|
||||
if center.distance_squared(camera) < 64.0 * 64.0 {
|
||||
// NAME_TAG is at the entity height (0.5), then the name
|
||||
// submitter lifts it 0.5. ItemFrameRenderer offsets rendering
|
||||
// 0.3 toward its facing and -0.25 vertically.
|
||||
let step = frame.step();
|
||||
tags.push(NameTag {
|
||||
at: center
|
||||
+ glam::DVec3::new(
|
||||
f64::from(step[0] as f32 * 0.3),
|
||||
0.75,
|
||||
f64::from(step[2] as f32 * 0.3),
|
||||
),
|
||||
lines: vec![(Text::literal(name).resolve_legacy(), 0.0)],
|
||||
light: self.world.light(
|
||||
center.x.floor() as i32,
|
||||
center.y.floor() as i32,
|
||||
center.z.floor() as i32,
|
||||
),
|
||||
discrete: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
tags
|
||||
}
|
||||
/// `SubmitNodeCollection.submitNameTag`: a discrete name is drawn once,
|
||||
@@ -257,12 +293,16 @@ impl Game<'_> {
|
||||
const FADED: u32 = 0x7F;
|
||||
for tag in self.name_tags(camera, alpha) {
|
||||
let o = tag.at - camera;
|
||||
// `gbuffers_entities` draws name tag text (2.3); a sneaking player's faded tag, on its
|
||||
// background, blends.
|
||||
if tag.discrete {
|
||||
self.mark_translucent_entity(out.len(), "minecraft:name_tag");
|
||||
self.name_tag_quads(o, &tag.lines, FADED, true, 0, vertex_light(tag.light), out);
|
||||
continue;
|
||||
}
|
||||
// LightCoordsUtil.lightCoordsWithEmission(lightCoords, 2).
|
||||
let lit = (tag.light >> 4).max(2) << 4 | (tag.light & 15).max(2);
|
||||
self.mark_entity(out.len(), "minecraft:name_tag");
|
||||
self.name_tag_quads(o, &tag.lines, 0xFF, false, 0, vertex_light(lit), out);
|
||||
// RenderPipelines.TEXT_SEE_THROUGH: no depth test, no lightmap.
|
||||
self.name_tag_quads(o, &tag.lines, FADED, true, 2, 0, see_through);
|
||||
|
||||
@@ -142,6 +142,8 @@ impl Game<'_> {
|
||||
}
|
||||
let server = &self.server_packs.active;
|
||||
let root = startup_root(&vanilla, &self.settings.resource_packs, server)?;
|
||||
let root =
|
||||
super::mods::content_root(&root, &self.settings.mods.enabled, &self.options.dev_mods);
|
||||
self.reload_resources(&root)
|
||||
}
|
||||
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
|
||||
@@ -192,6 +194,10 @@ impl Game<'_> {
|
||||
let context = pack.context.clone();
|
||||
self.pack = pack;
|
||||
self.gui = gui;
|
||||
// The atlas's sprites moved: the particle engine re-reads every rect
|
||||
// and the packs' sprite sets, or every particle draws a stale region.
|
||||
self.particles
|
||||
.reload(root, &self.gui.atlas.sprites, &self.gui.atlas.translucent);
|
||||
horizon_client::ui_theme::reset_atlas();
|
||||
// Villager hats come from the pack's texture metadata (shared data, swapped in place).
|
||||
*self
|
||||
|
||||
@@ -234,6 +234,22 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// A `Holder<SoundEvent>` off the wire: an inline event's location, or
|
||||
/// the name of a registered one.
|
||||
pub(super) fn remote_sound_name(
|
||||
&self,
|
||||
sound: &(i32, Option<(String, Option<f32>)>),
|
||||
) -> Option<String> {
|
||||
match &sound.1 {
|
||||
Some((location, _)) => Some(location.clone()),
|
||||
None => self.remote.as_ref().and_then(|r| {
|
||||
r.builtin
|
||||
.get("minecraft:sound_event")?
|
||||
.name(sound.0)
|
||||
.map(str::to_owned)
|
||||
}),
|
||||
}
|
||||
}
|
||||
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
|
||||
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
|
||||
self.connect_server_with_cookies(address, name, None)
|
||||
@@ -473,6 +489,7 @@ impl Game<'_> {
|
||||
r.session.disconnect();
|
||||
}
|
||||
self.server_packs_disconnect();
|
||||
self.close_dialogs();
|
||||
// Single player's server thread saves the world before the title shows.
|
||||
let single_player = match self.integrated.take() {
|
||||
Some(server) => {
|
||||
@@ -737,6 +754,8 @@ impl Game<'_> {
|
||||
} => {
|
||||
self.set_registries(registries);
|
||||
self.extras_joined();
|
||||
// handleLogin: the level loading screen replaces any dialog.
|
||||
self.close_dialogs();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.joined = true;
|
||||
r.profile = uuid;
|
||||
@@ -765,6 +784,8 @@ impl Game<'_> {
|
||||
}
|
||||
Event::PackPush(p) => self.handle_pack_push(p),
|
||||
Event::PackPop(id) => self.handle_pack_pop(id),
|
||||
Event::ShowDialog(dialog) => self.show_dialog(&dialog),
|
||||
Event::ClearDialog => self.clear_dialog(),
|
||||
Event::DecodeError(e) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.decode_errors += 1;
|
||||
@@ -1727,20 +1748,14 @@ impl Game<'_> {
|
||||
// ClientLevel.levelEvent: LevelEventHandler, as this client's own
|
||||
// level plays them (particles and sounds: a spawner's burst, bone
|
||||
// meal, waxing, a block broken by someone else).
|
||||
// ClientPacketListener.handleLevelEvent: a global one is heard
|
||||
// from anywhere (ClientLevel.globalLevelEvent).
|
||||
C::LevelEvent(p) if p.global => self.global_level_event_sound(p.kind, p.pos),
|
||||
C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data),
|
||||
C::LevelParticles(p) => self.remote_level_particles(&p),
|
||||
C::Explode(p) => self.remote_explode(&p),
|
||||
C::Sound(p) => {
|
||||
let name = match &p.sound.1 {
|
||||
Some((location, _)) => Some(location.clone()),
|
||||
None => self.remote.as_ref().and_then(|r| {
|
||||
r.builtin
|
||||
.get("minecraft:sound_event")?
|
||||
.name(p.sound.0)
|
||||
.map(str::to_owned)
|
||||
}),
|
||||
};
|
||||
if let Some(name) = name {
|
||||
if let Some(name) = self.remote_sound_name(&p.sound) {
|
||||
let at = [
|
||||
f64::from(p.x) / 8.0,
|
||||
f64::from(p.y) / 8.0,
|
||||
@@ -1921,25 +1936,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS):
|
||||
// another player starts using the item in a hand (eating, a
|
||||
// bow drawn, a shield up), or stops.
|
||||
// LivingEntity.DATA_LIVING_ENTITY_FLAGS: for another player
|
||||
// too, remote_mob_data's apply reads index 8 above.
|
||||
let other = self
|
||||
.remote
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.level_players.contains_key(&p.id) && r.entity_id != p.id);
|
||||
if other && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
|
||||
for (index, _, value) in &p.values {
|
||||
if let (8, Value::Byte(flags)) = (index, value) {
|
||||
m.extra.using_off_hand = flags & 2 != 0;
|
||||
if flags & 1 == 0 {
|
||||
m.extra.using_item = 0;
|
||||
} else if m.extra.using_item == 0 {
|
||||
m.extra.using_item = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): another
|
||||
// player lies down in their bed (drawn lying in it), or gets up.
|
||||
if other {
|
||||
@@ -2395,6 +2397,7 @@ impl Game<'_> {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.commands = Some(tree);
|
||||
}
|
||||
self.merge_remote_tree();
|
||||
}
|
||||
C::SystemChat(p) => {
|
||||
// The component as sent, translated in the client's own
|
||||
@@ -2633,6 +2636,9 @@ impl Game<'_> {
|
||||
C::SetTitleText(p) => self.titles.set_title(remote_text(&p.text)),
|
||||
C::SetSubtitleText(p) => self.titles.set_subtitle(remote_text(&p.text)),
|
||||
C::SetTitlesAnimation(p) => self.titles.set_times(p.fade_in, p.stay, p.fade_out),
|
||||
// ClientCommonPacketListenerImpl.handleShowDialog / handleClearDialog.
|
||||
C::ShowDialog(p) => self.show_play_dialog(&p.dialog),
|
||||
C::ClearDialog(_) => self.clear_dialog(),
|
||||
C::ClearTitles(p) => {
|
||||
self.titles.clear();
|
||||
if p.value {
|
||||
@@ -3089,6 +3095,7 @@ impl Game<'_> {
|
||||
self.tick_block_entity_anims();
|
||||
self.tick_hand();
|
||||
self.tick_particles();
|
||||
self.tick_client_ambient();
|
||||
self.tick_client_effects();
|
||||
// Player.tick's sleep counter (the darkening and the wake-up fade).
|
||||
self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some());
|
||||
@@ -3422,25 +3429,32 @@ impl Game<'_> {
|
||||
m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32;
|
||||
*steps -= 1;
|
||||
}
|
||||
// LivingEntity.updatingUsingItem for another player: the ticks the
|
||||
// item has been used before this one.
|
||||
if player && m.extra.using_item > 0 {
|
||||
let item = if m.extra.using_off_hand {
|
||||
m.extra.off_hand.clone()
|
||||
} else {
|
||||
m.extra.main_hand.clone()
|
||||
};
|
||||
if let Some(item) = item {
|
||||
let eye = if m.extra.crouching { 1.27 } else { 1.62 };
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
using.push((
|
||||
item,
|
||||
m.extra.using_item as u32 - 1,
|
||||
at,
|
||||
eye,
|
||||
m.head_pitch,
|
||||
m.yaw,
|
||||
));
|
||||
// Chicken.aiStep: the wings follow the server's on-ground flag.
|
||||
if m.species() == horizon_client::mobs::Species::Chicken {
|
||||
horizon_client::mobs::farm::chicken_flap(m);
|
||||
}
|
||||
// LivingEntity.updatingUsingItem: the ticks the item has been
|
||||
// used before this one. Another player's use particles; a mob's
|
||||
// drawn bow only needs the count (its pull follows it).
|
||||
if m.extra.using_item > 0 {
|
||||
if player {
|
||||
let item = if m.extra.using_off_hand {
|
||||
m.extra.off_hand.clone()
|
||||
} else {
|
||||
m.extra.main_hand.clone()
|
||||
};
|
||||
if let Some(item) = item {
|
||||
let eye = if m.extra.crouching { 1.27 } else { 1.62 };
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
using.push((
|
||||
item,
|
||||
m.extra.using_item as u32 - 1,
|
||||
at,
|
||||
eye,
|
||||
m.head_pitch,
|
||||
m.yaw,
|
||||
));
|
||||
}
|
||||
}
|
||||
m.extra.using_item += 1;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,17 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
|
||||
// client, which draws the flames. A client doesn't count the
|
||||
// fire down: the flag goes off when the server's fire is out.
|
||||
(0, Value::Byte(flags)) => m.fire_ticks = i32::from(flags & 1),
|
||||
// LivingEntity.DATA_LIVING_ENTITY_FLAGS: using an item 1, in the
|
||||
// off hand 2. The flag starts and stops the use; the client ticks
|
||||
// the count itself (a bow's pull follows it).
|
||||
(8, Value::Byte(flags)) => {
|
||||
m.extra.using_off_hand = flags & 2 != 0;
|
||||
if flags & 1 == 0 {
|
||||
m.extra.using_item = 0;
|
||||
} else if m.extra.using_item == 0 {
|
||||
m.extra.using_item = 1;
|
||||
}
|
||||
}
|
||||
// LivingEntity.DATA_HEALTH_ID: the boss bars and the death
|
||||
// animation follow it.
|
||||
(9, Value::Float(health)) => m.health = *health,
|
||||
@@ -53,6 +64,13 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
|
||||
(Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => {
|
||||
m.extra.size = (*size).clamp(1, 127);
|
||||
}
|
||||
// Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's
|
||||
// IS_CELEBRATING takes 16).
|
||||
(Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging,
|
||||
// SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose.
|
||||
(Species::Evoker | Species::Illusioner, 17, Value::Byte(spell)) => {
|
||||
m.extra.variant2 = (*spell).max(0) as u8;
|
||||
}
|
||||
// Villager.DATA_VILLAGER_DATA and ZombieVillager's (after
|
||||
// Zombie's three): what VillagerProfessionLayer draws.
|
||||
(Species::Villager, 19, Value::Ids(data))
|
||||
@@ -239,4 +257,42 @@ mod tests {
|
||||
);
|
||||
assert_eq!(name(&z), ("desert", "farmer", 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mob_flags_drive_the_aggressive_poses() {
|
||||
let Some(mut m) = mob("minecraft:skeleton") else {
|
||||
return;
|
||||
};
|
||||
apply(&mut m, &[(15, s::BYTE, Value::Byte(2 | 4))]);
|
||||
assert!(m.ai.aggressive && m.extra.left_handed && !m.no_ai);
|
||||
apply(&mut m, &[(15, s::BYTE, Value::Byte(0))]);
|
||||
assert!(!m.ai.aggressive && !m.extra.left_handed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_living_flags_start_and_stop_a_mob_using_an_item() {
|
||||
let Some(mut m) = mob("minecraft:skeleton") else {
|
||||
return;
|
||||
};
|
||||
apply(&mut m, &[(8, s::BYTE, Value::Byte(1))]);
|
||||
assert_eq!(m.extra.using_item, 1);
|
||||
assert!(!m.extra.using_off_hand);
|
||||
// Using in the off hand.
|
||||
apply(&mut m, &[(8, s::BYTE, Value::Byte(3))]);
|
||||
assert!(m.extra.using_off_hand);
|
||||
apply(&mut m, &[(8, s::BYTE, Value::Byte(0))]);
|
||||
assert_eq!(m.extra.using_item, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pillager_charges_and_a_spellcaster_casts() {
|
||||
let Some(mut p) = mob("minecraft:pillager") else {
|
||||
return;
|
||||
};
|
||||
apply(&mut p, &[(17, s::BOOLEAN, Value::Bool(true))]);
|
||||
assert!(p.extra.flag);
|
||||
let mut e = mob("minecraft:evoker").unwrap();
|
||||
apply(&mut e, &[(17, s::BYTE, Value::Byte(2))]);
|
||||
assert_eq!(e.extra.variant2, 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -718,17 +718,24 @@ impl Game<'_> {
|
||||
})
|
||||
};
|
||||
// The ticking ones in the index's order, with whether the chunks
|
||||
// around them tick too.
|
||||
// around them tick too. Most sensors and catalysts wait for a
|
||||
// vibration or a death: their tick would change nothing, so they
|
||||
// are passed over here (a vibration scheduled during these ticks is
|
||||
// chosen on the next tick at the earliest, as in vanilla).
|
||||
let entities = &self.world.block_entities;
|
||||
let due: Vec<((i32, i32, i32), bool)> = self
|
||||
.sculk
|
||||
.index
|
||||
.iter()
|
||||
.filter_map(|&key| {
|
||||
let (cx, cz) = (key.0 >> 4, key.2 >> 4);
|
||||
ticks(cx, cz).then(|| {
|
||||
let adjacent = (-1..=1).all(|dx| (-1..=1).all(|dz| ticks(cx + dx, cz + dz)));
|
||||
(key, adjacent)
|
||||
})
|
||||
if !ticks(cx, cz)
|
||||
|| matches!(entities.get(&key), Some(BlockEntity::Sculk(e)) if e.idle())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let adjacent = (-1..=1).all(|dx| (-1..=1).all(|dz| ticks(cx + dx, cz + dz)));
|
||||
Some((key, adjacent))
|
||||
})
|
||||
.collect();
|
||||
for (key, adjacent) in due {
|
||||
|
||||
@@ -4,9 +4,30 @@
|
||||
|
||||
use horizon_client::camera::CameraFluid;
|
||||
use horizon_client::gfx::pack_uniforms::PackInputs;
|
||||
use horizon_shaders::{Macros, Pack, Properties, dimension_folder, load_post};
|
||||
use horizon_shaders::{BlockIds, Macros, Pack, Properties, dimension_folder, load_post};
|
||||
|
||||
use super::{Dim, Game};
|
||||
use horizon_client::gfx::pack_draw::EntitySpan;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The ids a pack gives entities and block entities (4.1, 5.3), for the spans of the entity
|
||||
/// geometry.
|
||||
pub(super) struct PackIds {
|
||||
entities: HashMap<String, i32>,
|
||||
blocks: BlockIds,
|
||||
/// `blockEntityId` by block state, filled as states are drawn.
|
||||
block_states: RefCell<HashMap<u32, i32>>,
|
||||
/// The id of a name the file lacks: 65535, or 0 without the file.
|
||||
missing_entity: i32,
|
||||
missing_block: i32,
|
||||
/// `item.properties` (4.1) and the id of a held item the file lacks, or of an empty hand:
|
||||
/// −1, or 0 without the file (5.3).
|
||||
items: HashMap<String, i32>,
|
||||
missing_item: i32,
|
||||
/// `oldHandLight` (3.2): the first held item and light are those of the brighter hand.
|
||||
old_hand_light: bool,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Loads the pack for the current dimension when it changed, and returns this frame's
|
||||
@@ -42,8 +63,49 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
let folder = dimension_folder(&pack, dimension);
|
||||
let post = load_post(&pack, &folder, &properties, ¯os, None);
|
||||
if let Some((programs, notes)) = renderer.set_shader_pack(dimension, Some(post))
|
||||
let inputs = renderer.pack_inputs();
|
||||
let mut post = load_post(&pack, &folder, &properties, ¯os, &inputs);
|
||||
let biomes = self.res.biomes();
|
||||
let names: Vec<&str> = biomes.list.iter().map(|b| b.name.as_str()).collect();
|
||||
post.custom.set_biomes(&names);
|
||||
let text = pack.read_text("block.properties").unwrap_or_default();
|
||||
let ids = BlockIds::parse(&Properties::parse(&text, ¯os));
|
||||
for note in &ids.notes {
|
||||
log::warn!("shader pack {name}: block.properties: {note}");
|
||||
}
|
||||
let text = pack.read_text("entity.properties");
|
||||
let entities = BlockIds::parse_kind(
|
||||
&Properties::parse(text.as_deref().unwrap_or_default(), ¯os),
|
||||
"entity",
|
||||
);
|
||||
let text = pack.read_text("item.properties");
|
||||
let items = BlockIds::parse_kind(
|
||||
&Properties::parse(text.as_deref().unwrap_or_default(), ¯os),
|
||||
"item",
|
||||
);
|
||||
self.pack_ids = Some(PackIds {
|
||||
items: items.plain(),
|
||||
missing_item: if text.is_some() { -1 } else { 0 },
|
||||
// OQ-21: on unless the pack turns it off.
|
||||
old_hand_light: properties
|
||||
.get("oldHandLight")
|
||||
.is_none_or(|v| v.trim() != "false"),
|
||||
entities: entities.plain(),
|
||||
missing_entity: if text.is_some() { 65535 } else { 0 },
|
||||
missing_block: if ids.is_empty() { 0 } else { 65535 },
|
||||
blocks: ids.clone(),
|
||||
block_states: RefCell::default(),
|
||||
});
|
||||
let started_ids = std::time::Instant::now();
|
||||
let table = block_id_table(&self.pack, &ids);
|
||||
log::info!(
|
||||
"shader pack {name}: mc_Entity for {} of {} block sprites in {} ms",
|
||||
table.chunks(2).filter(|p| p[0] != -1).count(),
|
||||
table.len() / 2,
|
||||
started_ids.elapsed().as_millis()
|
||||
);
|
||||
if let Some((programs, notes)) =
|
||||
renderer.set_shader_pack(dimension, Some(post), &table)
|
||||
{
|
||||
for note in notes {
|
||||
log::warn!("shader pack {name}: {note}");
|
||||
@@ -57,14 +119,22 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
self.pack_ids = None;
|
||||
log::warn!("shader pack {name}: {e}");
|
||||
renderer.set_shader_pack(dimension, None);
|
||||
renderer.set_shader_pack(dimension, None, &[]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let lerp = |(old, new): (f32, f32)| old + (new - old) * partial;
|
||||
let at = camera.floor().as_ivec3();
|
||||
let light = self.world.light(at.x, at.y, at.z);
|
||||
let biome = self
|
||||
.world
|
||||
.chunks
|
||||
.get(&(at.x >> 4, at.z >> 4))
|
||||
.map(|c| c.biome(at.x, at.y, at.z));
|
||||
let (held_items, held_light) = self.held_for_pack();
|
||||
let info = biome.map(|b| self.res.biomes().get(b));
|
||||
PackInputs {
|
||||
day_time: self.world.day_time,
|
||||
rain: lerp(self.world.weather.rain_level),
|
||||
@@ -79,6 +149,191 @@ impl Game<'_> {
|
||||
eye_light: [i32::from(light & 15), i32::from(light >> 4)],
|
||||
hide_gui: self.ui.hide_gui,
|
||||
brightness: self.settings.gamma,
|
||||
biome: biome.map_or(-1, i32::from),
|
||||
biome_category: info.map_or(0, |b| horizon_shaders::biome_category(&b.name)),
|
||||
biome_precipitation: info.map_or(0, |b| {
|
||||
horizon_shaders::biome_precipitation(b.precipitation, b.temperature)
|
||||
}),
|
||||
temperature: info.map_or(0.0, |b| b.temperature),
|
||||
rainfall: info.map_or(0.0, |b| b.downfall),
|
||||
held_items,
|
||||
held_light,
|
||||
}
|
||||
}
|
||||
|
||||
/// `heldItemId(2)` and `heldBlockLightValue(2)`: main hand, then off hand (5.2, 5.3).
|
||||
fn held_for_pack(&mut self) -> ([i32; 2], [i32; 2]) {
|
||||
if self.pack_ids.is_none() {
|
||||
return ([0; 2], [0; 2]);
|
||||
}
|
||||
if self.luminance.is_none() {
|
||||
self.luminance = Some(horizon_client::dynamic_light::Luminance::new(
|
||||
self.res.facts(),
|
||||
self.pack.assets.registry,
|
||||
));
|
||||
}
|
||||
let (Some(ids), Some(lum)) = (&self.pack_ids, &self.luminance) else {
|
||||
return ([0; 2], [0; 2]);
|
||||
};
|
||||
let hands = [self.selected, super::shield::OFFHAND_SLOT].map(|slot| {
|
||||
let item = self.stack_in(slot).map(|s| &*s.item);
|
||||
let id = item.and_then(|i| ids.items.get(i).copied());
|
||||
(
|
||||
id.unwrap_or(ids.missing_item),
|
||||
item.map_or(0, |i| i32::from(lum.of(i))),
|
||||
)
|
||||
});
|
||||
let first = if ids.old_hand_light && hands[1].1 > hands[0].1 {
|
||||
hands[1]
|
||||
} else {
|
||||
hands[0]
|
||||
};
|
||||
([first.0, hands[1].0], [first.1, hands[1].1])
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Starts a span of the entity geometry at vertex `start` for entity type `name`
|
||||
/// (`minecraft:zombie`; "" for one the pack cannot name). Nothing without a pack.
|
||||
pub(super) fn mark_entity(&self, start: usize, name: &str) {
|
||||
self.mark_entity_part(start, name, false);
|
||||
}
|
||||
|
||||
/// Starts a span for entity geometry that blends (name tags, shadows).
|
||||
pub(super) fn mark_translucent_entity(&self, start: usize, name: &str) {
|
||||
self.mark_entity_part(start, name, true);
|
||||
}
|
||||
|
||||
fn mark_entity_part(&self, start: usize, name: &str, translucent: bool) {
|
||||
if let Some(ids) = &self.pack_ids {
|
||||
let id = ids.entities.get(name).copied();
|
||||
self.push_span(start, "ENTITIES", id.unwrap_or(ids.missing_entity));
|
||||
if let Some(last) = self.entity_spans.borrow_mut().last_mut() {
|
||||
last.translucent = translucent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a span for the block entity of block state `state`.
|
||||
pub(super) fn mark_block_entity(&self, start: usize, state: u32) {
|
||||
let Some(ids) = &self.pack_ids else { return };
|
||||
let id = *ids
|
||||
.block_states
|
||||
.borrow_mut()
|
||||
.entry(state)
|
||||
.or_insert_with(|| {
|
||||
let registry = self.pack.assets.registry;
|
||||
registry
|
||||
.state(horizon_world::registry::BlockStateId(state))
|
||||
.and_then(|s| {
|
||||
ids.blocks
|
||||
.id(&s.name, |k| s.properties.get(k).map(String::as_str))
|
||||
})
|
||||
.unwrap_or(ids.missing_block)
|
||||
});
|
||||
self.push_span(start, "BLOCK_ENTITIES", id);
|
||||
}
|
||||
|
||||
/// Starts a span of geometry that is not an entity (`PARTICLES`, `DESTROY`...).
|
||||
pub(super) fn mark_stage(&self, start: usize, stage: &str) {
|
||||
if self.pack_ids.is_some() {
|
||||
self.push_span(start, stage, 0);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_span(&self, start: usize, stage: &str, id: i32) {
|
||||
let mut spans = self.entity_spans.borrow_mut();
|
||||
let span = EntitySpan {
|
||||
start: start as u32,
|
||||
stage: horizon_shaders::render_stage(stage),
|
||||
id,
|
||||
translucent: false,
|
||||
};
|
||||
// A span that drew nothing gives way to the next.
|
||||
match spans.last_mut() {
|
||||
Some(last) if last.start == span.start => *last = span,
|
||||
_ => spans.push(span),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `mc_Entity` (x, y) of each block sprite layer, as (id, fluid) pairs: terrain vertices carry
|
||||
/// their sprite layer, not their block. A layer takes the id of the block named like its sprite
|
||||
/// (`block/oak_leaves` for `oak_leaves`), else the id most blocks drawing it share (ties: the
|
||||
/// lowest); -1 when no block drawing it has one. y is 1 for the fluid sprites, -1 otherwise.
|
||||
fn block_id_table(pack: &super::PackResources, ids: &BlockIds) -> Vec<i32> {
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
let layers = pack
|
||||
.render
|
||||
.sprite_layers
|
||||
.values()
|
||||
.max()
|
||||
.map_or(0, |l| l + 1) as usize;
|
||||
let mut table = vec![-1; layers * 2];
|
||||
if ids.is_empty() {
|
||||
return table;
|
||||
}
|
||||
let registry = pack.assets.registry;
|
||||
let catalog = &pack.render.model_catalog;
|
||||
let sprite = |name: &str| pack.render.sprite_layers.get(name).copied();
|
||||
// (layer, id) -> (a block named like the sprite, the blocks).
|
||||
let mut votes: BTreeMap<(u32, i32), (bool, BTreeSet<&str>)> = BTreeMap::new();
|
||||
for i in 0..registry.len() {
|
||||
let state_id = horizon_world::registry::BlockStateId(i as u32);
|
||||
let Some(state) = registry.state(state_id) else {
|
||||
continue;
|
||||
};
|
||||
let Some(id) = ids.id(&state.name, |k| state.properties.get(k).map(String::as_str)) else {
|
||||
continue;
|
||||
};
|
||||
let block = state.name.strip_prefix("minecraft:").unwrap_or(&state.name);
|
||||
let mut vote = |layer: u32| {
|
||||
let named = pack
|
||||
.layer_names
|
||||
.get(&layer)
|
||||
.and_then(|n| n.strip_prefix("block/"))
|
||||
== Some(block);
|
||||
let v = votes.entry((layer, id)).or_default();
|
||||
v.0 |= named;
|
||||
v.1.insert(&state.name);
|
||||
};
|
||||
// Fluids draw from their own sprites.
|
||||
let fluid = match block {
|
||||
"water" => ["water_still", "water_flow"],
|
||||
"lava" => ["lava_still", "lava_flow"],
|
||||
_ => ["", ""],
|
||||
};
|
||||
for f in fluid.iter().filter(|f| !f.is_empty()) {
|
||||
if let Some(l) = sprite(&format!("minecraft:block/{f}")) {
|
||||
vote(l);
|
||||
}
|
||||
}
|
||||
let origin = horizon_core::position::BlockPos::new(0, 0, 0);
|
||||
for (_, model) in catalog.collect(state_id, origin).unwrap_or_default() {
|
||||
for face in &model.faces {
|
||||
vote(face.layer);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut best: BTreeMap<u32, (bool, usize, i32)> = BTreeMap::new();
|
||||
for ((layer, id), (named, blocks)) in votes {
|
||||
let candidate = (named, blocks.len(), -id);
|
||||
let b = best.entry(layer).or_insert(candidate);
|
||||
if candidate > *b {
|
||||
*b = candidate;
|
||||
}
|
||||
}
|
||||
for (layer, (_, _, id)) in best {
|
||||
if let Some(slot) = table.get_mut(layer as usize * 2) {
|
||||
*slot = -id;
|
||||
}
|
||||
}
|
||||
for f in ["water_still", "water_flow", "lava_still", "lava_flow"] {
|
||||
if let Some(l) = sprite(&format!("minecraft:block/{f}"))
|
||||
&& let Some(slot) = table.get_mut(l as usize * 2 + 1)
|
||||
{
|
||||
*slot = 1;
|
||||
}
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
@@ -272,8 +272,6 @@ impl Loading {
|
||||
}
|
||||
pub(super) fn apply_menu_settings(&mut self) {
|
||||
if let Some(renderer) = &mut self.renderer {
|
||||
self.settings
|
||||
.clamp_gui_scale([renderer.config.width as i32, renderer.config.height as i32]);
|
||||
renderer.gamma = self.settings.gamma;
|
||||
renderer.set_present_mode(self.settings.vsync, self.settings.horizon.present_mode);
|
||||
}
|
||||
|
||||
@@ -158,7 +158,8 @@ const COLUMNS: [(&str, &str); 6] = [
|
||||
#[derive(Default)]
|
||||
pub(super) struct StatsUi {
|
||||
tab: usize,
|
||||
scroll: f32,
|
||||
/// The list's scrolling: the wheel and the held scrollbar.
|
||||
scroll: horizon_client::ui::Scroll,
|
||||
sort: Option<(usize, i32)>,
|
||||
}
|
||||
/// `MenuTabBar` geometry: three tabs over at most 400 pixels.
|
||||
@@ -182,6 +183,15 @@ impl Game<'_> {
|
||||
self.stats_ui = StatsUi::default();
|
||||
self.screen = Screen::Stats;
|
||||
}
|
||||
/// The list's scrollbar column (right of the 280 pixel list) and the
|
||||
/// pixels it scrolls.
|
||||
fn stats_bar(w: f32) -> f32 {
|
||||
((w - 280.0) / 2.0).floor() + 280.0 + 6.0
|
||||
}
|
||||
fn stats_content(&self) -> f32 {
|
||||
let (row_h, rows) = self.stats_rows();
|
||||
row_h * rows as f32 + 4.0
|
||||
}
|
||||
fn stats_rows(&self) -> (f32, usize) {
|
||||
match self.stats_ui.tab {
|
||||
0 => (14.0, CUSTOM.len()),
|
||||
@@ -260,10 +270,9 @@ impl Game<'_> {
|
||||
// The list.
|
||||
let (row_h, rows) = self.stats_rows();
|
||||
let content = row_h * rows as f32 + 4.0;
|
||||
let max_scroll = (content - (bottom - top)).max(0.0);
|
||||
self.stats_ui.scroll = self.stats_ui.scroll.clamp(0.0, max_scroll);
|
||||
self.stats_ui.scroll.clamp(top, bottom, content);
|
||||
let left = ((w - 280.0) / 2.0).floor();
|
||||
let scroll = self.stats_ui.scroll;
|
||||
let scroll = self.stats_ui.scroll.amount;
|
||||
let row_y = |i: usize| top + 4.0 + i as f32 * row_h - scroll;
|
||||
let visible = |y: f32| y >= top && y + row_h <= bottom;
|
||||
match self.stats_ui.tab {
|
||||
@@ -408,11 +417,11 @@ impl Game<'_> {
|
||||
ui::scrollbar(
|
||||
batch,
|
||||
atlas,
|
||||
left + 280.0 + 6.0,
|
||||
Self::stats_bar(w),
|
||||
top,
|
||||
bottom,
|
||||
content,
|
||||
self.stats_ui.scroll,
|
||||
self.stats_ui.scroll.amount,
|
||||
);
|
||||
self.draw_stats_footer(batch, w, h);
|
||||
}
|
||||
@@ -433,6 +442,10 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
pub(super) fn stats_click(&mut self, size: [u32; 2]) {
|
||||
// A press on the scrollbar holds it and clicks nothing else.
|
||||
if self.stats_press_scrollbar(size) {
|
||||
return;
|
||||
}
|
||||
let b = HudBatch::new(size);
|
||||
let (w, h) = (b.width, b.height);
|
||||
let (x0, tw) = tabs(w);
|
||||
@@ -441,7 +454,7 @@ impl Game<'_> {
|
||||
&& self.stats_ui.tab != i
|
||||
{
|
||||
self.stats_ui.tab = i;
|
||||
self.stats_ui.scroll = 0.0;
|
||||
self.stats_ui.scroll.amount = 0.0;
|
||||
self.audio
|
||||
.play("minecraft:ui.button.click", None, 0.25, 1.0);
|
||||
return;
|
||||
@@ -461,7 +474,7 @@ impl Game<'_> {
|
||||
}
|
||||
if self.stats_ui.tab == 1 {
|
||||
let left = ((w - 280.0) / 2.0).floor();
|
||||
let y = TAB_H + 4.0 - self.stats_ui.scroll;
|
||||
let y = TAB_H + 4.0 - self.stats_ui.scroll.amount;
|
||||
for c in 0..COLUMNS.len() {
|
||||
let x = left + 75.0 + 40.0 * c as f32 - 18.0;
|
||||
if ui::hovered(self.cursor, x, y + 1.0, 18.0, 18.0) {
|
||||
@@ -479,6 +492,35 @@ impl Game<'_> {
|
||||
}
|
||||
pub(super) fn stats_scroll(&mut self, amount: f32) {
|
||||
let (row_h, _) = self.stats_rows();
|
||||
self.stats_ui.scroll -= amount * row_h / 2.0;
|
||||
let h = self.gui_size().1;
|
||||
let content = self.stats_content();
|
||||
self.stats_ui
|
||||
.scroll
|
||||
.wheel(amount, row_h / 2.0, TAB_H, h - FOOTER, content);
|
||||
}
|
||||
/// A press on the statistics list's scrollbar holds it
|
||||
/// (`AbstractSelectionList.updateScrolling`).
|
||||
pub(super) fn stats_press_scrollbar(&mut self, size: [u32; 2]) -> bool {
|
||||
let b = HudBatch::new(size);
|
||||
let (w, h) = (b.width, b.height);
|
||||
let content = self.stats_content();
|
||||
self.stats_ui
|
||||
.scroll
|
||||
.press(self.cursor, Self::stats_bar(w), TAB_H, h - FOOTER, content)
|
||||
}
|
||||
/// The pointer moved while the scrollbar is held.
|
||||
pub(super) fn stats_drag(&mut self) {
|
||||
if !self.stats_ui.scroll.held() {
|
||||
return;
|
||||
}
|
||||
let h = self.gui_size().1;
|
||||
let content = self.stats_content();
|
||||
self.stats_ui
|
||||
.scroll
|
||||
.drag(self.cursor.1, TAB_H, h - FOOTER, content);
|
||||
}
|
||||
/// The button came up: the scrollbar lets go.
|
||||
pub(super) fn stats_release(&mut self) {
|
||||
self.stats_ui.scroll.release();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,6 +246,9 @@ pub(super) fn make_streaming(
|
||||
let inner = Arc::new(VanillaTerrain::for_world(&options.resources.join("worldgen"), pack.assets.registry, res.biomes(), seed, dim.id(), structures).map_err(|e| {
|
||||
format!("{e}\nPrepare the worldgen bundle with the launcher, or: horizon-prepare --prepare")
|
||||
})?);
|
||||
if dim == Dim::Overworld && structures {
|
||||
inner.search_rings_behind();
|
||||
}
|
||||
locator = Some(inner.clone());
|
||||
Streaming::new(
|
||||
Arc::new(Persistent {
|
||||
|
||||
@@ -69,8 +69,15 @@ pub mod lightning;
|
||||
mod lod;
|
||||
mod occlusion;
|
||||
mod pack_atlas;
|
||||
pub mod pack_draw;
|
||||
mod pack_entities;
|
||||
mod pack_hand;
|
||||
mod pack_post;
|
||||
mod pack_shadow;
|
||||
mod pack_sky;
|
||||
mod pack_timing;
|
||||
pub mod pack_uniforms;
|
||||
mod pack_weather;
|
||||
mod page_runs;
|
||||
pub mod panorama;
|
||||
mod resident;
|
||||
@@ -86,6 +93,19 @@ const COMPLETE_COLUMN: u32 = (1 << (crate::chunk::HEIGHT / 16)) - 1;
|
||||
/// its fixed-point UVs (`terrain.wgsl`'s `terrain_uv`).
|
||||
/// The world pass again after occlusion culling's test: it loads both
|
||||
/// targets (phase 2 draws over phase 1, reading the test's results).
|
||||
/// LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks).
|
||||
fn sky_open(frame: &Frame) -> bool {
|
||||
match frame.fog {
|
||||
Some(f) => f.sky_end > 2.0,
|
||||
None => !frame.underwater,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Overworld-style sky (disc, sunset, stars, void) draws this frame.
|
||||
fn sky_visible(frame: &Frame) -> bool {
|
||||
!frame.title && frame.skybox && sky_open(frame)
|
||||
}
|
||||
|
||||
fn world_pass_after_culling<'e>(
|
||||
encoder: &'e mut wgpu::CommandEncoder,
|
||||
view: &wgpu::TextureView,
|
||||
@@ -232,6 +252,8 @@ pub struct Frame<'a> {
|
||||
pub nether_lighting: bool,
|
||||
/// Camera-relative entity geometry textured from the shared atlas.
|
||||
pub entities: &'a [Vertex],
|
||||
/// Runs of `entities` by entity, while a shader pack draws them (`pack_draw::EntitySpan`).
|
||||
pub entity_spans: &'a [pack_draw::EntitySpan],
|
||||
pub weather: &'a [crate::weather::Vertex],
|
||||
pub weather_time: crate::weather::Time,
|
||||
/// Horizon Extras' dynamic lights, nearest first (`dynamic_light::select`); empty when off.
|
||||
@@ -449,6 +471,8 @@ pub struct Renderer {
|
||||
/// Per-frame scratch, kept to avoid allocating every frame.
|
||||
visible: Vec<resident::Visible>,
|
||||
visible_lods: Vec<lod::Visible>,
|
||||
/// The sections a shader pack's shadow camera sees (`pack_post::ShadowView`).
|
||||
shadow_visible: Vec<resident::Visible>,
|
||||
translucent_draws: Vec<(u64, usize, [u32; 5], (u32, Option<u32>))>,
|
||||
origins: Vec<[f32; 4]>,
|
||||
/// `DrawIndexedIndirectArgs` words: index count, instance count, first
|
||||
@@ -463,6 +487,8 @@ pub struct Renderer {
|
||||
/// Each section's solid draws, to group them by arena page.
|
||||
solid_runs: page_runs::PageRuns,
|
||||
phase2_runs: page_runs::PageRuns,
|
||||
/// The shadow camera's draws by page, in bands of distance from the light.
|
||||
shadow_runs: page_runs::PageRuns,
|
||||
/// Block-entity blocks per meshed section (world position, state id).
|
||||
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
|
||||
/// Changes whenever `block_entities` does (unique across renderers).
|
||||
@@ -473,8 +499,16 @@ pub struct Renderer {
|
||||
world_post: world_post::Post,
|
||||
/// The shader pack's post-processing, and the dimension (legacy id) it was loaded for.
|
||||
pack_post: Option<(i32, Option<pack_post::PackPost>)>,
|
||||
/// The entity vertices Horizon draws itself while a shader pack draws the others.
|
||||
pack_entity_rest: Vec<Vertex>,
|
||||
/// Set 1 of the cloud pipeline, for a shader pack's `gbuffers_clouds`.
|
||||
cloud_bindings: wgpu::BindGroupLayout,
|
||||
/// Rain and snow handed to a shader pack's `gbuffers_weather`, once a pack draws them.
|
||||
pack_weather: Option<pack_weather::PackWeather>,
|
||||
/// The block sprites as one atlas, while a shader pack is loaded.
|
||||
pack_atlas: Option<pack_atlas::PackAtlas>,
|
||||
/// The pack's terrain program reads flat draws' vertices (`pack_terrain_inputs`).
|
||||
pack_terrain_flat: bool,
|
||||
pub hud: HudRenderer,
|
||||
/// Vanilla's menu background blur, made on first use.
|
||||
menu_blur: Option<crate::menu_blur::MenuBlur>,
|
||||
@@ -842,12 +876,17 @@ async fn open_device(
|
||||
continue;
|
||||
}
|
||||
// Mappable primary buffers: section pages that no longer fit in
|
||||
// video memory go to system memory.
|
||||
// video memory go to system memory. Shader packs' 16-bit normalized buffers (render
|
||||
// targets with the adapter's own format features) and R11F_G11F_B10F: a float
|
||||
// stand-in neither clamps nor drops NaN.
|
||||
let features = timing::GpuTimer::features(&adapter)
|
||||
| cull::Cull::features(&adapter)
|
||||
| (adapter.features()
|
||||
& (wgpu::Features::INDIRECT_FIRST_INSTANCE
|
||||
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS));
|
||||
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS
|
||||
| wgpu::Features::TEXTURE_FORMAT_16BIT_NORM
|
||||
| wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
|
||||
| wgpu::Features::RG11B10UFLOAT_RENDERABLE));
|
||||
let driver = format!("{} {}", info.driver, info.driver_info);
|
||||
startup_step(format_args!(
|
||||
"requesting the device (driver {}) with features [{features}] and the adapter's \
|
||||
@@ -1484,7 +1523,10 @@ impl Renderer {
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
// COPY_SRC: a shader pack's weather copies the rain and snow sprites out.
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_DST
|
||||
| wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
@@ -2149,13 +2191,16 @@ impl Renderer {
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let flat_wanted = flat::wanted(&adapter, &device);
|
||||
// Readable as storage where flat draws run: a shader pack's terrain program reads them.
|
||||
let arena = arena::Arena::new(
|
||||
&device,
|
||||
std::mem::size_of::<TerrainVertex>() as u64,
|
||||
1 << 20,
|
||||
flat_wanted,
|
||||
);
|
||||
// Sections as one index list per frame where multi-draw is emulated.
|
||||
let flat = flat::wanted(&adapter, &device).then(|| {
|
||||
let flat = flat_wanted.then(|| {
|
||||
let buffers = [Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<TerrainVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
@@ -2349,6 +2394,7 @@ impl Renderer {
|
||||
multi_draw,
|
||||
visible: Vec::new(),
|
||||
visible_lods: Vec::new(),
|
||||
shadow_visible: Vec::new(),
|
||||
translucent_draws: Vec::new(),
|
||||
origins: Vec::new(),
|
||||
draws: Vec::new(),
|
||||
@@ -2357,12 +2403,17 @@ impl Renderer {
|
||||
phase2_pages: Vec::new(),
|
||||
solid_runs: page_runs::PageRuns::default(),
|
||||
phase2_runs: page_runs::PageRuns::default(),
|
||||
shadow_runs: page_runs::PageRuns::default(),
|
||||
block_entities: HashMap::new(),
|
||||
block_entity_revision: next_block_entity_revision(),
|
||||
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
|
||||
world_post,
|
||||
pack_post: None,
|
||||
pack_entity_rest: Vec::new(),
|
||||
cloud_bindings,
|
||||
pack_weather: None,
|
||||
pack_atlas: None,
|
||||
pack_terrain_flat: false,
|
||||
hud,
|
||||
menu_blur: None,
|
||||
info,
|
||||
@@ -2793,24 +2844,84 @@ impl Renderer {
|
||||
self.world_post.scale = scale.clamp(0.25, 2.0);
|
||||
self.world_post.antialias = antialias;
|
||||
}
|
||||
/// Runs `post` over the world from now on (`None`: no pack), for the dimension `dimension`.
|
||||
/// Runs `post` over the world from now on (`None`: no pack), for the dimension `dimension`;
|
||||
/// `block_ids` gives each block sprite layer's `mc_Entity` (id, fluid) pair.
|
||||
/// Returns the programs that run and the notes of loading them.
|
||||
pub fn set_shader_pack(
|
||||
&mut self,
|
||||
dimension: i32,
|
||||
pack: Option<horizon_shaders::Post>,
|
||||
block_ids: &[i32],
|
||||
) -> Option<(Vec<String>, Vec<String>)> {
|
||||
if pack.is_none() {
|
||||
self.pack_atlas = None;
|
||||
}
|
||||
let instance = wgpu::vertex_attr_array![5=>Float32x4];
|
||||
let vertex = wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<TerrainVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &TERRAIN_ATTRIBUTES,
|
||||
};
|
||||
let instances = wgpu::VertexBufferLayout {
|
||||
array_stride: 16,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &instance,
|
||||
};
|
||||
let buffers = [Some(vertex), Some(instances)];
|
||||
let flat = self.pack_terrain_flat;
|
||||
let post = pack.map(|post| {
|
||||
let world = pack_post::World {
|
||||
atlas: self.pack_atlas.as_ref().map(|a| (a.view.clone(), a.size())),
|
||||
lightmap: self.lightmap_view.clone(),
|
||||
terrain: self.pack_atlas.as_ref().map(|_| pack_post::Geometry {
|
||||
buffers: if flat { &buffers[..1] } else { &buffers },
|
||||
table: self.flat.as_ref().filter(|_| flat).map(|f| &f.draw_layout),
|
||||
depth_write: true,
|
||||
atlas: None,
|
||||
ids: None,
|
||||
cull: true,
|
||||
}),
|
||||
block_ids,
|
||||
celestial: self
|
||||
.hud
|
||||
.atlas_texture
|
||||
.as_ref()
|
||||
.map(|t| t.create_view(&Default::default())),
|
||||
clouds: Some(&self.cloud_bindings),
|
||||
weather: true,
|
||||
hand: true,
|
||||
};
|
||||
pack_post::PackPost::new(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
post,
|
||||
self.config.format.remove_srgb_suffix(),
|
||||
world,
|
||||
)
|
||||
});
|
||||
if post.is_none() {
|
||||
self.pack_atlas = None;
|
||||
} else if self.pack_atlas.is_none() {
|
||||
let report = post.as_ref().map(|p| {
|
||||
let programs = p.programs().into_iter().map(str::to_owned).collect();
|
||||
(programs, p.notes.clone())
|
||||
});
|
||||
self.pack_post = Some((dimension, post));
|
||||
report
|
||||
}
|
||||
/// What a shader pack's gbuffers programs read from Horizon's geometry: the sky's, and
|
||||
/// terrain's in the pack's block atlas (made here when missing; none when it does not fit).
|
||||
pub fn pack_inputs(&mut self) -> horizon_shaders::GameInputs {
|
||||
horizon_shaders::GameInputs {
|
||||
terrain: self.pack_terrain_inputs(),
|
||||
sky: Some(pack_sky::inputs()),
|
||||
celestial: Some(pack_sky::celestial_inputs()),
|
||||
entities: Some(pack_entities::inputs()),
|
||||
clouds: Some(pack_entities::cloud_inputs()),
|
||||
weather: Some(pack_weather::inputs()),
|
||||
hand: Some(pack_hand::inputs()),
|
||||
}
|
||||
}
|
||||
|
||||
fn pack_terrain_inputs(&mut self) -> Option<horizon_shaders::GbuffersInputs> {
|
||||
if self.pack_atlas.is_none() {
|
||||
let mut encoder = self.device.create_command_encoder(&Default::default());
|
||||
let layers = self
|
||||
.sprite_textures
|
||||
@@ -2827,12 +2938,13 @@ impl Renderer {
|
||||
);
|
||||
self.queue.submit([encoder.finish()]);
|
||||
}
|
||||
let report = post.as_ref().map(|p| {
|
||||
let programs = p.programs().into_iter().map(str::to_owned).collect();
|
||||
(programs, p.notes.clone())
|
||||
});
|
||||
self.pack_post = Some((dimension, post));
|
||||
report
|
||||
// Flat draws whenever the device has them (`render` keeps them on with a pack).
|
||||
self.pack_terrain_flat = self.flat.is_some() && self.flat_on;
|
||||
Some(
|
||||
self.pack_atlas
|
||||
.as_ref()?
|
||||
.terrain_inputs(self.pack_terrain_flat),
|
||||
)
|
||||
}
|
||||
/// The dimension the shader pack was last set for.
|
||||
pub fn shader_pack_dimension(&self) -> Option<i32> {
|
||||
@@ -3208,8 +3320,43 @@ impl Renderer {
|
||||
);
|
||||
visible_lods.sort_unstable_by_key(|v| (v.distance, v.key));
|
||||
}
|
||||
// A shader pack's shadow pass draws the sections in its camera's box, all of them (the
|
||||
// occlusion graph follows the eye, not the light), within shadowDistanceRenderMul.
|
||||
let shadow_view = self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.filter(|_| !frame.title)
|
||||
.and_then(|p| p.shadow_view(frame));
|
||||
let mut shadow_visible = std::mem::take(&mut self.shadow_visible);
|
||||
shadow_visible.clear();
|
||||
if let Some(v) = &shadow_view {
|
||||
let radius = (frame.detail_distance / 16.0) as i32;
|
||||
let radius = v
|
||||
.distance
|
||||
.map_or(radius, |d| radius.min((d / 16.0).ceil() as i32));
|
||||
let light = Frustum {
|
||||
planes: frustum(v.cull),
|
||||
};
|
||||
crate::spans::time("shadow visibility", || {
|
||||
self.sections.visible(
|
||||
camera,
|
||||
radius,
|
||||
&light,
|
||||
|_| true,
|
||||
|_, _| false,
|
||||
&mut shadow_visible,
|
||||
)
|
||||
});
|
||||
// Nearest the light first, so the depth test rejects what lies under it.
|
||||
let light = v.light;
|
||||
shadow_visible.sort_unstable_by(|a, b| {
|
||||
let height = |s: &resident::Visible| glam::Vec3::from(s.origin).dot(light);
|
||||
height(b).total_cmp(&height(a))
|
||||
});
|
||||
}
|
||||
self.drawn_sections = visible.len() + visible_lods.len();
|
||||
let instances = self.drawn_sections;
|
||||
let instances = self.drawn_sections + shadow_visible.len();
|
||||
if instances as u64 > self.instance_capacity {
|
||||
self.instance_capacity = (instances as u64).next_power_of_two();
|
||||
self.instances = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
@@ -3226,7 +3373,8 @@ impl Renderer {
|
||||
visible
|
||||
.iter()
|
||||
.map(|v| section_instance(v.origin))
|
||||
.chain(visible_lods.iter().map(|v| lod::instance(v.origin))),
|
||||
.chain(visible_lods.iter().map(|v| lod::instance(v.origin)))
|
||||
.chain(shadow_visible.iter().map(|v| section_instance(v.origin))),
|
||||
);
|
||||
if !self.origins.is_empty() {
|
||||
self.uploads.buffer(
|
||||
@@ -3243,11 +3391,23 @@ impl Renderer {
|
||||
// Occlusion culling leaves the sections its last result did not see
|
||||
// to phase 2, after the others, with instance counts of 0. Whether
|
||||
// the frame has draws enough goes by the last one's.
|
||||
// A shader pack drawing terrain draws all of it: occlusion culling reads the depth of
|
||||
// Horizon's own terrain draw.
|
||||
let pack_terrain = !frame.title
|
||||
&& self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.is_some_and(|p| p.has_terrain());
|
||||
let mut cull = self
|
||||
.cull
|
||||
.as_mut()
|
||||
.filter(|c| {
|
||||
self.cull_on && !frame.title && self.multi_draw && visible.len() >= c.min_sections
|
||||
self.cull_on
|
||||
&& !frame.title
|
||||
&& !pack_terrain
|
||||
&& self.multi_draw
|
||||
&& visible.len() >= c.min_sections
|
||||
})
|
||||
.and_then(|cull| cull.begin(&self.device).then_some(cull));
|
||||
self.phase2_draws.clear();
|
||||
@@ -3418,9 +3578,87 @@ impl Renderer {
|
||||
self.translucency_cursor += budget;
|
||||
let translucent_draws = self.draws.len() as u32 - solid_draws;
|
||||
self.section_draws = self.draws.len();
|
||||
// The shadow camera's sections after the camera's: quads that can face the light, then
|
||||
// translucent ones (in their last sorted order; depth decides there).
|
||||
let shadow_first = self.draws.len() as u32;
|
||||
let mut shadow_translucent = Vec::new();
|
||||
self.shadow_runs.clear();
|
||||
if let Some(view) = &shadow_view {
|
||||
let base = self.drawn_sections;
|
||||
let toward = view.light * 1.0e5;
|
||||
// How far below the nearest section to the light (squared, as bits, as `PageRuns`
|
||||
// takes distances): each band's draws go by page, a call per page and band.
|
||||
let height = |v: &resident::Visible| glam::Vec3::from(v.origin).dot(view.light);
|
||||
let top = shadow_visible.first().map_or(0.0, height);
|
||||
for (k, v) in shadow_visible.iter().enumerate() {
|
||||
let s = self.sections.get_mut(v.slot);
|
||||
let instance = (base + k) as u32;
|
||||
let depth = f64::from(top - height(v)).max(0.0);
|
||||
let distance = (depth * depth).to_bits();
|
||||
// A section the camera never saw has no sorted indices yet: sorted once now.
|
||||
if let Some((index_page, index_start)) = s.sorted_indices
|
||||
&& !s.sort.is_sorted()
|
||||
{
|
||||
let origin = [
|
||||
v.key.0 * 16,
|
||||
crate::chunk::MIN_Y + v.key.1 * 16,
|
||||
v.key.2 * 16,
|
||||
];
|
||||
if let Some(indices) =
|
||||
s.sort
|
||||
.update(camera.to_array(), origin, &mut self.translucent_sorter)
|
||||
{
|
||||
self.uploads.buffer(
|
||||
&mut encoder,
|
||||
self.sorted_indices.buffer(index_page),
|
||||
index_start * 4,
|
||||
bytemuck::cast_slice(indices),
|
||||
);
|
||||
}
|
||||
}
|
||||
let before = self.draws.len();
|
||||
facing_runs(&s.sides, Some(toward), v.origin, |first, quads| {
|
||||
let start = s.start as u32 + first * 4;
|
||||
self.draws.push([quads * 6, 1, 0, start, instance]);
|
||||
self.draw_pages.push((s.page, None));
|
||||
});
|
||||
let len = self.draws.len() - before;
|
||||
self.shadow_runs.push(distance, s.page, before, len, [0; 3]);
|
||||
if let Some((index_page, index_start)) = s.sorted_indices {
|
||||
let start = s.start + u64::from(s.solid) * 4;
|
||||
shadow_translucent.push((
|
||||
distance,
|
||||
[
|
||||
s.translucent * 6,
|
||||
1,
|
||||
index_start as u32,
|
||||
start as u32,
|
||||
instance,
|
||||
],
|
||||
(s.page, Some(index_page)),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let shadow_solid = self.draws.len() as u32 - shadow_first;
|
||||
self.shadow_runs
|
||||
.regroup(&mut self.draws, &mut self.draw_pages, shadow_first as usize);
|
||||
self.shadow_runs.clear();
|
||||
for (distance, draw, pages) in shadow_translucent {
|
||||
self.shadow_runs
|
||||
.push(distance, pages.0, self.draws.len(), 1, [0; 3]);
|
||||
self.draws.push(draw);
|
||||
self.draw_pages.push(pages);
|
||||
}
|
||||
self.shadow_runs.regroup(
|
||||
&mut self.draws,
|
||||
&mut self.draw_pages,
|
||||
(shadow_first + shadow_solid) as usize,
|
||||
);
|
||||
let shadow_translucent = self.draws.len() as u32 - shadow_first - shadow_solid;
|
||||
// Metal replays a multi-draw as one draw call per entry.
|
||||
self.section_draw_calls = if self.multi_draw && self.info.backend != wgpu::Backend::Metal {
|
||||
(0..self.draws.len())
|
||||
(0..self.section_draws)
|
||||
.filter(|&i| {
|
||||
i == 0
|
||||
|| i == phase1_draws as usize
|
||||
@@ -3429,7 +3667,7 @@ impl Renderer {
|
||||
})
|
||||
.count()
|
||||
} else {
|
||||
self.draws.len()
|
||||
self.section_draws
|
||||
};
|
||||
let debug_depth = frame.debug_lines.len() as u32;
|
||||
let debug_top = frame.debug_lines_on_top.len() as u32;
|
||||
@@ -3472,6 +3710,22 @@ impl Renderer {
|
||||
self.uploads
|
||||
.buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines));
|
||||
}
|
||||
// While a shader pack draws entities, the runs of `entity_spans` its programs draw are
|
||||
// left out of Horizon's own entity draw.
|
||||
let mut entities = frame.entities;
|
||||
if !frame.title
|
||||
&& let Some((_, Some(post))) = &mut self.pack_post
|
||||
&& post.has_entities()
|
||||
{
|
||||
post.prepare_entities(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
frame.entities,
|
||||
frame.entity_spans,
|
||||
&mut self.pack_entity_rest,
|
||||
);
|
||||
entities = &self.pack_entity_rest;
|
||||
}
|
||||
let [
|
||||
entity_quads,
|
||||
crumbling_quads,
|
||||
@@ -3479,12 +3733,9 @@ impl Renderer {
|
||||
water_mask_quads,
|
||||
shadow_quads,
|
||||
translucent_particle_quads,
|
||||
] = self.entity_batch.update(
|
||||
frame.entities,
|
||||
frame.additive,
|
||||
frame.hand,
|
||||
frame.see_through,
|
||||
);
|
||||
] = self
|
||||
.entity_batch
|
||||
.update(entities, frame.additive, frame.hand, frame.see_through);
|
||||
let weather_quads = frame.weather.len() as u32 / 4;
|
||||
let world_quads = entity_quads
|
||||
+ crumbling_quads
|
||||
@@ -3653,7 +3904,9 @@ impl Renderer {
|
||||
Some(flat)
|
||||
if self.flat_on
|
||||
&& !self.draws.is_empty()
|
||||
&& self.drawn_sections >= flat.min_sections =>
|
||||
&& (self.drawn_sections >= flat.min_sections
|
||||
|| pack_terrain
|
||||
|| shadow_view.is_some()) =>
|
||||
{
|
||||
let sections = &self.sections;
|
||||
let lods = &self.lods;
|
||||
@@ -3668,9 +3921,11 @@ impl Renderer {
|
||||
&self.draw_pages,
|
||||
phase1_draws as usize,
|
||||
solid_draws as usize,
|
||||
[shadow_first, shadow_first + shadow_solid].map(|d| d as usize),
|
||||
phase2,
|
||||
visible
|
||||
.iter()
|
||||
.chain(&shadow_visible)
|
||||
.filter_map(|v| {
|
||||
let id = sections.get(v.slot).flat_id?;
|
||||
Some((id, section_instance(v.origin)))
|
||||
@@ -3686,7 +3941,7 @@ impl Renderer {
|
||||
_ => false,
|
||||
};
|
||||
if flat_frame {
|
||||
self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.calls.len());
|
||||
self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.shadow_calls[0]);
|
||||
} else if self.multi_draw && !self.draws.is_empty() {
|
||||
if self.draws.len() as u64 > self.indirect_capacity {
|
||||
self.indirect_capacity = (self.draws.len() as u64).next_power_of_two();
|
||||
@@ -3713,6 +3968,46 @@ impl Renderer {
|
||||
}
|
||||
// The world's targets: the screen, or the scaled target of `post`.
|
||||
let pack_post = !frame.title && self.pack_post.as_ref().is_some_and(|p| p.1.is_some());
|
||||
// The pack's program reads the vertices this frame's draws bind.
|
||||
let pack_draws_terrain = pack_terrain && flat_frame == self.pack_terrain_flat;
|
||||
// The shadow camera's lists, drawn by the pack's shadow programs.
|
||||
let pack_draws_shadow = shadow_view.is_some() && flat_frame == self.pack_terrain_flat;
|
||||
let pack_draws_sky = pack_post
|
||||
&& self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.is_some_and(|p| p.has_sky());
|
||||
let pack_draws_celestial = pack_post
|
||||
&& self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.is_some_and(|p| p.has_celestial());
|
||||
let pack_draws_water = pack_draws_terrain
|
||||
&& self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.is_some_and(|p| p.has_water());
|
||||
let pack_draws_clouds = pack_post
|
||||
&& self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.is_some_and(|p| p.has_clouds());
|
||||
let pack_draws_hand = pack_post
|
||||
&& self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.is_some_and(|p| p.has_hand());
|
||||
let pack_draws_weather = pack_post
|
||||
&& self
|
||||
.pack_post
|
||||
.as_ref()
|
||||
.and_then(|p| p.1.as_ref())
|
||||
.is_some_and(|p| p.has_weather());
|
||||
let scaled = self.world_post.prepare(
|
||||
&self.device,
|
||||
[self.config.width, self.config.height],
|
||||
@@ -3766,13 +4061,9 @@ impl Renderer {
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
// LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks).
|
||||
let sky_visible = match frame.fog {
|
||||
Some(f) => f.sky_end > 2.0,
|
||||
None => !frame.underwater,
|
||||
};
|
||||
let sky_visible = sky_open(frame);
|
||||
if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) {
|
||||
if !frame.title && frame.skybox {
|
||||
if !frame.title && frame.skybox && !pack_draws_sky {
|
||||
pass.set_pipeline(&self.sky);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
@@ -3786,22 +4077,29 @@ impl Renderer {
|
||||
if frame.end_sky {
|
||||
self.end_sky.draw(&mut pass);
|
||||
}
|
||||
if celestial_vertices > 0 {
|
||||
if celestial_vertices > 0 && !pack_draws_celestial {
|
||||
pass.set_vertex_buffer(0, self.celestial_buffer.slice(..));
|
||||
pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1);
|
||||
}
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if !frame.title && frame.stars.is_some() {
|
||||
if !frame.title && frame.stars.is_some() && !pack_draws_sky {
|
||||
self.stars.draw(&mut pass);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if !frame.title && frame.dark_disc {
|
||||
if !frame.title && frame.dark_disc && !pack_draws_sky {
|
||||
pass.set_pipeline(&self.dark_disc);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
match self.flat.as_ref().filter(|_| flat_frame) {
|
||||
match self
|
||||
.flat
|
||||
.as_ref()
|
||||
.filter(|_| flat_frame && !pack_draws_terrain)
|
||||
{
|
||||
_ if pack_draws_terrain => {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.solid);
|
||||
let vertices = |p| self.arena.buffer(p);
|
||||
@@ -3875,7 +4173,9 @@ impl Renderer {
|
||||
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
self.weather.draw(&mut pass, &self.entity_group);
|
||||
if !pack_draws_weather {
|
||||
self.weather.draw(&mut pass, &self.entity_group);
|
||||
}
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
if crumbling_quads > 0 {
|
||||
pass.set_pipeline(&self.crumbling_pipeline);
|
||||
@@ -3937,9 +4237,11 @@ impl Renderer {
|
||||
pass.draw(0..4, debug_depth..debug_depth + debug_top);
|
||||
}
|
||||
match self.flat.as_ref().filter(|_| flat_frame) {
|
||||
// The pack draws translucent terrain after its deferred programs.
|
||||
_ if pack_draws_water => {}
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.translucent);
|
||||
flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| {
|
||||
flat.draw(&mut pass, flat.translucent_calls(), |p| {
|
||||
self.arena.buffer(p)
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
@@ -4004,7 +4306,7 @@ impl Renderer {
|
||||
0..1,
|
||||
);
|
||||
}
|
||||
if cloud_quads > 0 {
|
||||
if cloud_quads > 0 && !pack_draws_clouds {
|
||||
pass.set_pipeline(&self.cloud_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
pass.set_bind_group(1, &self.cloud_group, &[]);
|
||||
@@ -4025,9 +4327,79 @@ impl Renderer {
|
||||
}
|
||||
if let Some((color, depth)) = &scaled
|
||||
&& pack_post
|
||||
&& let Some((_, Some(post))) = &mut self.pack_post
|
||||
&& let Some((dimension, Some(mut post))) = self.pack_post.take()
|
||||
{
|
||||
let size = self.world_post.size().unwrap_or([1, 1]);
|
||||
let weather = match &self.hud.atlas_texture {
|
||||
Some(atlas) if pack_draws_weather => self
|
||||
.pack_weather
|
||||
.get_or_insert_with(|| pack_weather::PackWeather::new(&self.device))
|
||||
.prepare(
|
||||
&self.device,
|
||||
&mut encoder,
|
||||
&mut self.uploads,
|
||||
atlas,
|
||||
frame.weather,
|
||||
frame.weather_time,
|
||||
&self.indices,
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
post.set_weather(weather);
|
||||
let flat = self.flat.as_ref().filter(|_| flat_frame);
|
||||
let pages: Vec<(u32, wgpu::Buffer)> = match flat {
|
||||
Some(_) if pack_draws_terrain || pack_draws_shadow => self
|
||||
.arena
|
||||
.page_buffers()
|
||||
.map(|(p, b)| (p, b.clone()))
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut terrain =
|
||||
|rp: &mut wgpu::RenderPass<'_>,
|
||||
list: pack_post::TerrainList,
|
||||
page: &dyn Fn(&mut wgpu::RenderPass<'_>, u32)| {
|
||||
use pack_post::TerrainList as L;
|
||||
let shadow = matches!(list, L::ShadowSolid | L::ShadowTranslucent);
|
||||
if !(if shadow {
|
||||
pack_draws_shadow
|
||||
} else {
|
||||
pack_draws_terrain
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
match flat {
|
||||
Some(flat) => {
|
||||
let [shadow, shadow_translucent] = flat.shadow_calls;
|
||||
let calls = match list {
|
||||
L::Solid => &flat.calls[..flat.solid_calls],
|
||||
L::Translucent => flat.translucent_calls(),
|
||||
L::ShadowSolid => &flat.calls[shadow..shadow_translucent],
|
||||
L::ShadowTranslucent => &flat.calls[shadow_translucent..],
|
||||
};
|
||||
flat.draw_with(rp, calls, |p| self.arena.buffer(p), page);
|
||||
}
|
||||
None => {
|
||||
rp.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
rp.set_vertex_buffer(1, self.instances.slice(..));
|
||||
let (first, count) = match list {
|
||||
L::Solid => (0, solid_draws),
|
||||
L::Translucent => (solid_draws, translucent_draws),
|
||||
L::ShadowSolid => (shadow_first, shadow_solid),
|
||||
L::ShadowTranslucent => {
|
||||
(shadow_first + shadow_solid, shadow_translucent)
|
||||
}
|
||||
};
|
||||
self.draw_sections(rp, &self.indirect, 0, first, count);
|
||||
}
|
||||
}
|
||||
};
|
||||
post.set_clouds(pack_draws_clouds.then(|| pack_post::Clouds {
|
||||
vertices: self.cloud_buffer.clone(),
|
||||
group: self.cloud_group.clone(),
|
||||
indices: self.indices.clone(),
|
||||
quads: cloud_quads,
|
||||
}));
|
||||
post.run(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
@@ -4039,11 +4411,14 @@ impl Renderer {
|
||||
&frame.pack,
|
||||
size,
|
||||
[self.config.width, self.config.height],
|
||||
&pages,
|
||||
&mut terrain,
|
||||
);
|
||||
self.pack_post = Some((dimension, Some(post)));
|
||||
} else if scaled.is_some() {
|
||||
self.world_post.finish(&mut encoder, &view_target);
|
||||
}
|
||||
if hand_quads > 0 {
|
||||
if hand_quads > 0 && !pack_draws_hand {
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view_target,
|
||||
resolve_target: None,
|
||||
@@ -4248,6 +4623,7 @@ impl Renderer {
|
||||
let _ = self.started;
|
||||
self.visible = visible;
|
||||
self.visible_lods = visible_lods;
|
||||
self.shadow_visible = shadow_visible;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,8 +65,15 @@ pub struct Arena {
|
||||
}
|
||||
|
||||
impl Arena {
|
||||
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self {
|
||||
Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX)
|
||||
/// Vertices; `storage` also lets shaders read them as a storage buffer (a shader pack's
|
||||
/// terrain program reads the other corners of a vertex's quad for its normal).
|
||||
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64, storage: bool) -> Self {
|
||||
let usage = if storage {
|
||||
wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::STORAGE
|
||||
} else {
|
||||
wgpu::BufferUsages::VERTEX
|
||||
};
|
||||
Self::with_usage(device, stride, capacity, usage)
|
||||
}
|
||||
/// Sorted translucent indices; `storage` when compute passes read them.
|
||||
pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self {
|
||||
@@ -148,6 +155,11 @@ impl Arena {
|
||||
pub fn has_page(&self, page: u32) -> bool {
|
||||
self.pages.get(page as usize).is_some_and(Option::is_some)
|
||||
}
|
||||
/// Each live page's buffer, by page.
|
||||
pub fn page_buffers(&self) -> impl Iterator<Item = (u32, &wgpu::Buffer)> {
|
||||
let pages = self.pages.iter().enumerate();
|
||||
pages.filter_map(|(i, p)| Some((i as u32, &p.as_ref()?.buffer)))
|
||||
}
|
||||
pub fn buffer(&self, page: u32) -> &wgpu::Buffer {
|
||||
&self.pages[page as usize]
|
||||
.as_ref()
|
||||
@@ -352,7 +364,7 @@ mod tests {
|
||||
eprintln!("no GPU adapter: skipped");
|
||||
return;
|
||||
};
|
||||
let mut arena = Arena::new(&device, 4, GRAIN);
|
||||
let mut arena = Arena::new(&device, 4, GRAIN, false);
|
||||
arena.page_limit = 2 * GRAIN;
|
||||
assert_eq!(arena.bytes(), 0);
|
||||
let (first, a) = alloc(&mut arena, &device, &queue, GRAIN).unwrap();
|
||||
@@ -395,7 +407,7 @@ mod tests {
|
||||
return;
|
||||
};
|
||||
for mut arena in [
|
||||
Arena::new(&device, 28, GRAIN),
|
||||
Arena::new(&device, 28, GRAIN, false),
|
||||
Arena::indices(&device, GRAIN, false),
|
||||
] {
|
||||
alloc(&mut arena, &device, &queue, GRAIN).unwrap();
|
||||
|
||||
@@ -40,6 +40,8 @@ enum Source {
|
||||
struct Plan {
|
||||
phase1_calls: usize,
|
||||
solid_calls: usize,
|
||||
/// Where the shadow camera's solid and translucent calls begin.
|
||||
shadow_calls: [usize; 2],
|
||||
total: u64,
|
||||
}
|
||||
const QUADS: u32 = u32::MAX;
|
||||
@@ -73,7 +75,8 @@ pub struct Flat {
|
||||
phase2_call_data: Vec<[u32; 5]>,
|
||||
/// The copy of phase 2's draws, and its ranges.
|
||||
phase2_group: Option<(wgpu::BindGroup, u32)>,
|
||||
draw_layout: wgpu::BindGroupLayout,
|
||||
/// The layout of a page's bind group 1 (shader packs' terrain pipelines share it).
|
||||
pub(super) draw_layout: wgpu::BindGroupLayout,
|
||||
blocks_per_page: u64,
|
||||
pages: Vec<Option<PageTable>>,
|
||||
free_ids: Vec<u32>,
|
||||
@@ -96,6 +99,10 @@ pub struct Flat {
|
||||
pub calls: Vec<Call>,
|
||||
pub phase1_calls: usize,
|
||||
pub solid_calls: usize,
|
||||
/// Where a shader pack's shadow camera's solid and translucent calls
|
||||
/// begin (`calls.len()` without them): the camera's translucent calls
|
||||
/// end at the first.
|
||||
pub shadow_calls: [usize; 2],
|
||||
/// Frames with fewer sections in view keep the per-section draws.
|
||||
pub min_sections: usize,
|
||||
range_align: u64,
|
||||
@@ -163,12 +170,16 @@ fn buffer(
|
||||
/// draw calls, one per run of draws in the same vertex page, phase 1's solid
|
||||
/// ones, phase 2's (draws `phase1_draws..solid_draws`) and translucent ones
|
||||
/// apart. A phase 2 range names its draw in phase 2 and its call in phase 2
|
||||
/// instead of a destination: the call's room holds all of its draws.
|
||||
/// instead of a destination: the call's room holds all of its draws. Draws
|
||||
/// from `shadow[0]` (solid) and `shadow[1]` (translucent) on are a shader
|
||||
/// pack's shadow camera's, with calls of their own.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn plan(
|
||||
draws: &[[u32; 5]],
|
||||
pages: &[(u32, Option<u32>)],
|
||||
phase1_draws: usize,
|
||||
solid_draws: usize,
|
||||
shadow: [usize; 2],
|
||||
align: u64,
|
||||
calls: &mut Vec<Call>,
|
||||
ranges: &mut Vec<Range>,
|
||||
@@ -178,6 +189,7 @@ fn plan(
|
||||
ranges.clear();
|
||||
segments.clear();
|
||||
let (mut phase1_calls, mut solid_calls) = (None, None);
|
||||
let mut shadow_calls = [None; 2];
|
||||
let mut total = 0u64;
|
||||
let mut by_source: Vec<(Source, Vec<Range>)> = Vec::new();
|
||||
for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() {
|
||||
@@ -187,10 +199,14 @@ fn plan(
|
||||
if i == solid_draws {
|
||||
solid_calls = Some(calls.len());
|
||||
}
|
||||
match calls.last_mut() {
|
||||
Some(last) if last.page == page && i != phase1_draws && i != solid_draws => {
|
||||
last.count += d[0]
|
||||
for (k, &from) in shadow.iter().enumerate() {
|
||||
if i == from {
|
||||
shadow_calls[k].get_or_insert(calls.len());
|
||||
}
|
||||
}
|
||||
let starts = i == phase1_draws || i == solid_draws || shadow.contains(&i);
|
||||
match calls.last_mut() {
|
||||
Some(last) if last.page == page && !starts => last.count += d[0],
|
||||
_ => calls.push(Call {
|
||||
page,
|
||||
first: total as u32,
|
||||
@@ -226,6 +242,7 @@ fn plan(
|
||||
Plan {
|
||||
phase1_calls: phase1_calls.unwrap_or(calls.len()).min(solid_calls),
|
||||
solid_calls,
|
||||
shadow_calls: shadow_calls.map(|c| c.unwrap_or(calls.len())),
|
||||
total,
|
||||
}
|
||||
}
|
||||
@@ -339,6 +356,7 @@ impl Flat {
|
||||
calls: Vec::new(),
|
||||
phase1_calls: 0,
|
||||
solid_calls: 0,
|
||||
shadow_calls: [0; 2],
|
||||
min_sections: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") {
|
||||
0
|
||||
} else {
|
||||
@@ -411,6 +429,7 @@ impl Flat {
|
||||
///
|
||||
/// When culling, the solid draws from `phase1_draws` are phase 2's, which
|
||||
/// `phase2` holds as the test leaves them: `flatten_phase2` copies them.
|
||||
/// Draws from `shadow` on are a shader pack's shadow camera's (`plan`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
@@ -421,6 +440,7 @@ impl Flat {
|
||||
pages: &[(u32, Option<u32>)],
|
||||
phase1_draws: usize,
|
||||
solid_draws: usize,
|
||||
shadow: [usize; 2],
|
||||
phase2: Option<&wgpu::Buffer>,
|
||||
origins: impl Iterator<Item = (u32, [f32; 4])>,
|
||||
sorted_page: impl Fn(u32) -> wgpu::Buffer,
|
||||
@@ -463,12 +483,14 @@ impl Flat {
|
||||
let Plan {
|
||||
phase1_calls,
|
||||
solid_calls,
|
||||
shadow_calls,
|
||||
total,
|
||||
} = plan(
|
||||
draws,
|
||||
pages,
|
||||
phase1_draws,
|
||||
solid_draws,
|
||||
shadow,
|
||||
self.range_align,
|
||||
&mut self.calls,
|
||||
&mut self.range_data,
|
||||
@@ -476,10 +498,12 @@ impl Flat {
|
||||
);
|
||||
self.phase1_calls = phase1_calls;
|
||||
self.solid_calls = solid_calls;
|
||||
self.shadow_calls = shadow_calls;
|
||||
if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {
|
||||
self.calls.clear();
|
||||
self.phase1_calls = 0;
|
||||
self.solid_calls = 0;
|
||||
self.shadow_calls = [0; 2];
|
||||
return false;
|
||||
}
|
||||
if self.range_data.len() as u64 > self.range_capacity {
|
||||
@@ -643,6 +667,11 @@ impl Flat {
|
||||
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
|
||||
}
|
||||
|
||||
/// The camera's translucent calls.
|
||||
pub fn translucent_calls(&self) -> &[Call] {
|
||||
&self.calls[self.solid_calls..self.shadow_calls[0]]
|
||||
}
|
||||
|
||||
/// Draws `calls` with a flat pipeline set and `vertices` giving each
|
||||
/// page's vertex buffer.
|
||||
pub fn draw<'a>(
|
||||
@@ -650,10 +679,22 @@ impl Flat {
|
||||
pass: &mut wgpu::RenderPass<'_>,
|
||||
calls: &[Call],
|
||||
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
|
||||
) {
|
||||
self.draw_with(pass, calls, vertices, |_, _| {});
|
||||
}
|
||||
/// `draw`, calling `page` before each run of calls from one arena page (a shader pack binds
|
||||
/// that page's vertices for reading).
|
||||
pub fn draw_with<'a>(
|
||||
&self,
|
||||
pass: &mut wgpu::RenderPass<'_>,
|
||||
calls: &[Call],
|
||||
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
|
||||
page: impl Fn(&mut wgpu::RenderPass<'_>, u32),
|
||||
) {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for call in calls {
|
||||
self.bind_page(pass, call.page, &vertices);
|
||||
page(pass, call.page);
|
||||
pass.draw_indexed(call.first..call.first + call.count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
@@ -722,11 +763,13 @@ mod tests {
|
||||
phase1_calls,
|
||||
solid_calls,
|
||||
total,
|
||||
..
|
||||
} = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
solid,
|
||||
[draws.len(); 2],
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
@@ -761,6 +804,35 @@ mod tests {
|
||||
assert_eq!(ranges.len(), 12);
|
||||
}
|
||||
|
||||
/// A shader pack's shadow draws follow the camera's, in calls of their
|
||||
/// own even from the same page: solid ones, then translucent ones.
|
||||
#[test]
|
||||
fn plan_gives_the_shadow_lists_calls_of_their_own() {
|
||||
let (mut draws, mut pages, solid) = sample();
|
||||
let camera = draws.len();
|
||||
draws.extend([[6, 1, 0, 40, 6], [6 * 2, 1, 0, 64, 7], [6, 1, 6, 80, 7]]);
|
||||
pages.extend([(0, None), (0, None), (0, Some(0))]);
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let plan = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
solid,
|
||||
[camera, camera + 2],
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
assert_eq!((plan.solid_calls, plan.shadow_calls), (3, [4, 5]));
|
||||
let call = |page, first, count| Call { page, first, count };
|
||||
assert_eq!(
|
||||
&calls[3..],
|
||||
[call(0, 60, 18), call(0, 78, 18), call(0, 96, 6)]
|
||||
);
|
||||
assert_eq!(plan.total, 6 * 17);
|
||||
}
|
||||
|
||||
/// Phase 2's draws (here the third and fourth) get calls of their own,
|
||||
/// each with room for all of its draws, and ranges naming their draw
|
||||
/// and call in phase 2.
|
||||
@@ -773,6 +845,7 @@ mod tests {
|
||||
&pages,
|
||||
2,
|
||||
solid,
|
||||
[draws.len(); 2],
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
@@ -783,6 +856,7 @@ mod tests {
|
||||
Plan {
|
||||
phase1_calls: 1,
|
||||
solid_calls: 3,
|
||||
shadow_calls: [4, 4],
|
||||
total: 6 * 13
|
||||
}
|
||||
);
|
||||
@@ -886,6 +960,7 @@ mod tests {
|
||||
&pages,
|
||||
phase1,
|
||||
solid,
|
||||
[draws.len(); 2],
|
||||
align,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
//! layer is copied into a grid, row by row from the top left, and an animated layer again
|
||||
//! whenever its frame changes.
|
||||
|
||||
#[expect(dead_code, reason = "the gbuffers pass binds it (next slice)")]
|
||||
pub(super) struct PackAtlas {
|
||||
texture: wgpu::Texture,
|
||||
pub view: wgpu::TextureView,
|
||||
@@ -64,10 +63,6 @@ impl PackAtlas {
|
||||
}
|
||||
|
||||
/// The atlas's size in pixels (`atlasSize`).
|
||||
#[cfg_attr(
|
||||
not(test),
|
||||
expect(dead_code, reason = "the gbuffers pass reads it (next slice)")
|
||||
)]
|
||||
pub fn size(&self) -> [u32; 2] {
|
||||
[self.texture.width(), self.texture.height()]
|
||||
}
|
||||
@@ -118,6 +113,112 @@ impl PackAtlas {
|
||||
}
|
||||
}
|
||||
|
||||
/// GLSL: the face normal and tangent of a flat-drawn vertex, from its quad's first three corners
|
||||
/// (quads are four consecutive vertices of the page; position words 0-2, UV word 3).
|
||||
const FACE: &str = " uint hz_q = (uint(gl_VertexIndex) & ~3u) * 6u;\n \
|
||||
vec3 hz_p0 = uintBitsToFloat(uvec3(hz_vertices[hz_q], hz_vertices[hz_q + 1u], hz_vertices[hz_q + 2u]));\n \
|
||||
vec3 hz_p1 = uintBitsToFloat(uvec3(hz_vertices[hz_q + 6u], hz_vertices[hz_q + 7u], hz_vertices[hz_q + 8u]));\n \
|
||||
vec3 hz_p2 = uintBitsToFloat(uvec3(hz_vertices[hz_q + 12u], hz_vertices[hz_q + 13u], hz_vertices[hz_q + 14u]));\n \
|
||||
uvec3 hz_w = uvec3(hz_vertices[hz_q + 3u], hz_vertices[hz_q + 9u], hz_vertices[hz_q + 15u]);\n \
|
||||
vec2 hz_t0 = vec2(hz_w.x & 65535u, hz_w.x >> 16u);\n \
|
||||
vec2 hz_d1 = vec2(hz_w.y & 65535u, hz_w.y >> 16u) - hz_t0;\n \
|
||||
vec2 hz_d2 = vec2(hz_w.z & 65535u, hz_w.z >> 16u) - hz_t0;\n \
|
||||
vec3 hz_e1 = hz_p1 - hz_p0;\n \
|
||||
vec3 hz_e2 = hz_p2 - hz_p0;\n \
|
||||
vec3 hz_n = cross(hz_e1, hz_e2);\n \
|
||||
if (dot(hz_n, hz_n) > 1e-12) {\n \
|
||||
hz_Normal = normalize(hz_n);\n \
|
||||
float hz_r = hz_d1.x * hz_d2.y - hz_d2.x * hz_d1.y;\n \
|
||||
vec3 hz_t = (hz_e1 * hz_d2.y - hz_e2 * hz_d1.y) * sign(hz_r);\n \
|
||||
vec3 hz_b = (hz_e2 * hz_d1.x - hz_e1 * hz_d2.x) * sign(hz_r);\n \
|
||||
if (dot(hz_t, hz_t) > 1e-12) {\n \
|
||||
hz_t = normalize(hz_t - hz_Normal * dot(hz_Normal, hz_t));\n \
|
||||
hz_tangent = vec4(hz_t, dot(cross(hz_t, hz_Normal), hz_b) < 0.0 ? -1.0 : 1.0);\n \
|
||||
}\n \
|
||||
}\n";
|
||||
|
||||
impl PackAtlas {
|
||||
/// The vertex inputs of a gbuffers program drawing terrain (`TerrainVertex`, terrain.wgsl's
|
||||
/// `vs_terrain` or, for `flat` draws, `vs_terrain_flat`), in atlas coordinates.
|
||||
pub fn terrain_inputs(&self, flat: bool) -> horizon_shaders::GbuffersInputs {
|
||||
let mut declarations = String::from(
|
||||
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in uvec2 hz_v_uv;\n\
|
||||
layout(location = 2) in uint hz_v_layer;\nlayout(location = 3) in vec4 hz_v_color;\n\
|
||||
layout(location = 4) in uvec2 hz_v_light;\n",
|
||||
);
|
||||
let origin = if flat {
|
||||
declarations.push_str(
|
||||
"layout(set = 1, binding = 0) readonly buffer HzBlockSlots { uint hz_block_slots[]; };\n\
|
||||
layout(set = 1, binding = 1) readonly buffer HzSlotOrigins { vec4 hz_slot_origins[]; };\n",
|
||||
);
|
||||
// `mc_Entity` of each sprite layer: id, then 1 for fluids or -1 (the game's table),
|
||||
// and the arena page's vertices (`TerrainVertex`, six words each).
|
||||
declarations.push_str(
|
||||
"layout(set = 3, binding = 0) readonly buffer HzBlockIds { int hz_block_ids[]; };\n\
|
||||
layout(set = 3, binding = 1) readonly buffer HzVertices { uint hz_vertices[]; };\n",
|
||||
);
|
||||
"hz_slot_origins[hz_block_slots[uint(gl_VertexIndex) >> 8u]]"
|
||||
} else {
|
||||
declarations.push_str("layout(location = 5) in vec4 hz_v_origin;\n");
|
||||
"hz_v_origin"
|
||||
};
|
||||
let [width, height] = self.size();
|
||||
let scale = [
|
||||
self.sprite as f32 / width as f32,
|
||||
self.sprite as f32 / height as f32,
|
||||
];
|
||||
let columns = self.columns;
|
||||
// UVs past a sprite (models up to 2, distant tiles) cannot repeat in an atlas: clamped.
|
||||
let body = format!(
|
||||
" vec4 hz_origin = {origin};\n \
|
||||
uint hz_layer = hz_v_layer & 32767u;\n \
|
||||
hz_cell = vec2(float(hz_layer % {columns}u), float(hz_layer / {columns}u));\n \
|
||||
hz_scale = vec2({:?}, {:?});\n \
|
||||
hz_Vertex = vec4(hz_v_pos + hz_origin.xyz, 1.0);\n \
|
||||
hz_MultiTexCoord0 = vec4((hz_cell + clamp(vec2(hz_v_uv) * hz_origin.w, 0.0, 1.0)) * hz_scale, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord1 = vec4(float(hz_v_light.y), float(hz_v_light.x), 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
|
||||
hz_Color = hz_v_color;\n \
|
||||
hz_Normal = vec3(0.0, 1.0, 0.0);\n \
|
||||
hz_tangent = vec4(1.0, 0.0, 0.0, 1.0);\n",
|
||||
scale[0], scale[1],
|
||||
);
|
||||
let mut body = body;
|
||||
if flat {
|
||||
body.push_str(FACE);
|
||||
}
|
||||
declarations.push_str("vec2 hz_cell; vec2 hz_scale; vec4 hz_tangent;\n");
|
||||
let entity = if flat {
|
||||
"vec4(float(hz_block_ids[2u * hz_layer]), float(hz_block_ids[2u * hz_layer + 1u]), 0.0, 0.0)"
|
||||
} else {
|
||||
"vec4(-1.0, -1.0, 0.0, 0.0)"
|
||||
};
|
||||
let attributes = [
|
||||
("mc_Entity", entity),
|
||||
(
|
||||
"mc_midTexCoord",
|
||||
"vec4((hz_cell + 0.5) * hz_scale, 0.0, 1.0)",
|
||||
),
|
||||
("at_tangent", "hz_tangent"),
|
||||
("vaPosition", "hz_Vertex.xyz"),
|
||||
("vaUV0", "hz_MultiTexCoord0.xy"),
|
||||
("vaUV2", "hz_MultiTexCoord1.xy"),
|
||||
("vaColor", "hz_Color"),
|
||||
("vaNormal", "hz_Normal"),
|
||||
];
|
||||
horizon_shaders::GbuffersInputs {
|
||||
declarations,
|
||||
body,
|
||||
attributes: attributes
|
||||
.iter()
|
||||
.map(|&(n, v)| (n.to_owned(), v.to_owned()))
|
||||
.collect(),
|
||||
after: String::new(),
|
||||
alpha_test: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! The uniforms a shader pack's gbuffers programs read per draw (`HzDraw` at set 2, the
|
||||
//! translator's `DRAW_UNIFORMS`): one slot per render stage of a uniform buffer, picked with a
|
||||
//! dynamic offset at each draw.
|
||||
|
||||
use horizon_shaders::{RENDER_STAGES, render_stage};
|
||||
|
||||
/// Where a run of `Frame::entities` begins, and what it is (slice 7): the run lasts until the
|
||||
/// next span. Recorded only while a shader pack draws entities, so Horizon's own frames carry
|
||||
/// none; Horizon itself still draws the whole list at once.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct EntitySpan {
|
||||
/// The first vertex.
|
||||
pub start: u32,
|
||||
/// The render stage (5.4: `ENTITIES`, `BLOCK_ENTITIES`, `PARTICLES`, `DESTROY`), which picks
|
||||
/// the program.
|
||||
pub stage: u32,
|
||||
/// `entityId` for entities, `blockEntityId` for block entities (5.3), else 0.
|
||||
pub id: i32,
|
||||
/// An entity part that blends (a name tag, a shadow): `gbuffers_entities_translucent`.
|
||||
pub translucent: bool,
|
||||
}
|
||||
|
||||
/// `HzDraw`'s size: `renderStage`, `entityId`, `blockEntityId`, a pad, `entityColor`.
|
||||
const SIZE: u32 = 32;
|
||||
|
||||
pub(super) struct DrawUniforms {
|
||||
pub layout: wgpu::BindGroupLayout,
|
||||
group: wgpu::BindGroup,
|
||||
stride: u32,
|
||||
}
|
||||
|
||||
impl DrawUniforms {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
let stride = SIZE.max(device.limits().min_uniform_buffer_offset_alignment);
|
||||
let mut contents = vec![0u8; stride as usize * RENDER_STAGES.len()];
|
||||
for (i, slot) in contents.chunks_mut(stride as usize).enumerate() {
|
||||
slot[..4].copy_from_slice(&(i as i32).to_le_bytes());
|
||||
}
|
||||
let buffer = wgpu::util::DeviceExt::create_buffer_init(
|
||||
device,
|
||||
&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Shader pack draws"),
|
||||
contents: &contents,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
},
|
||||
);
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Shader pack draws"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: true,
|
||||
min_binding_size: wgpu::BufferSize::new(u64::from(SIZE)),
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Shader pack draws"),
|
||||
layout: &layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &buffer,
|
||||
offset: 0,
|
||||
size: wgpu::BufferSize::new(u64::from(SIZE)),
|
||||
}),
|
||||
}],
|
||||
});
|
||||
Self {
|
||||
layout,
|
||||
group,
|
||||
stride,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws that follow read `renderStage` = `MC_RENDER_STAGE_<stage>`, other values zero.
|
||||
pub fn bind(&self, pass: &mut wgpu::RenderPass<'_>, stage: &str) {
|
||||
pass.set_bind_group(2, &self.group, &[self.stride * render_stage(stage)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
//! Entities, block entities, translucent entity parts and particles drawn by a shader pack's
|
||||
//! `gbuffers_entities`, `gbuffers_block`, `gbuffers_entities_translucent` and
|
||||
//! `gbuffers_particles` (spec 2.3, 5.3, 5.4): the runs of `Frame::entities` the game marked (`EntitySpan`), each its
|
||||
//! own draw with its `entityId` or `blockEntityId` and `entityColor` in a per-draw slot of
|
||||
//! `HzDraw` (set 2). Horizon draws whatever the pack does not.
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use horizon_shaders::render_stage;
|
||||
|
||||
use super::Vertex;
|
||||
use super::pack_draw::EntitySpan;
|
||||
|
||||
/// `HzDraw`'s size (pack_draw.rs).
|
||||
const SLOT: u64 = 32;
|
||||
|
||||
const ATTRIBUTES: [wgpu::VertexAttribute; 6] = wgpu::vertex_attr_array![
|
||||
0 => Float32x3, 1 => Float32x2, 2 => Uint32, 3 => Unorm8x4, 4 => Uint8x4, 5 => Snorm8x4
|
||||
];
|
||||
|
||||
/// The entity vertex: Horizon's own (`Vertex`).
|
||||
pub fn buffers() -> [Option<wgpu::VertexBufferLayout<'static>>; 1] {
|
||||
[Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Vertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &ATTRIBUTES,
|
||||
})]
|
||||
}
|
||||
|
||||
/// What `gbuffers_entities` and `gbuffers_block` read from an entity vertex: camera-relative
|
||||
/// position, the shared atlas's UV, colour, light (block, sky in 16ths) and the world-oriented
|
||||
/// normal. The quad's corners, read from the same vertices at set 1, give the face normal where
|
||||
/// the vertex has none (block entities) and `at_tangent` along the texture's u, as for terrain.
|
||||
pub fn inputs() -> horizon_shaders::GbuffersInputs {
|
||||
let declarations = "layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\
|
||||
layout(location = 2) in uint hz_v_overlay;\nlayout(location = 3) in vec4 hz_v_color;\n\
|
||||
layout(location = 4) in uvec4 hz_v_light;\nlayout(location = 5) in vec4 hz_v_normal;\n\
|
||||
layout(set = 1, binding = 0) readonly buffer HzEntityVertices { uint hz_entity_vertices[]; };\n\
|
||||
vec4 hz_tangent; vec2 hz_mid;\n"
|
||||
.to_owned();
|
||||
let words = std::mem::size_of::<Vertex>() / 4;
|
||||
let corner = |k: usize, field: &str| {
|
||||
let at = |o: usize| format!("hz_entity_vertices[hz_q + {}u]", k * words + o);
|
||||
match field {
|
||||
"pos" => format!("uintBitsToFloat(uvec3({}, {}, {}))", at(0), at(1), at(2)),
|
||||
_ => format!("uintBitsToFloat(uvec2({}, {}))", at(3), at(4)),
|
||||
}
|
||||
};
|
||||
let body = format!(
|
||||
" uint hz_q = (uint(gl_VertexIndex) & ~3u) * {words}u;\n \
|
||||
vec3 hz_e1 = {p1} - {p0};\n \
|
||||
vec3 hz_e2 = {p2} - {p0};\n \
|
||||
vec2 hz_t0 = {t0};\n \
|
||||
vec2 hz_d1 = {t1} - hz_t0;\n \
|
||||
vec2 hz_d2 = {t2} - hz_t0;\n \
|
||||
hz_mid = (hz_t0 + {t2}) * 0.5;\n \
|
||||
vec3 hz_n = cross(hz_e1, hz_e2);\n \
|
||||
hz_Normal = dot(hz_v_normal.xyz, hz_v_normal.xyz) > 0.01 ? normalize(hz_v_normal.xyz)\n \
|
||||
: dot(hz_n, hz_n) > 1e-12 ? normalize(hz_n) : vec3(0.0, 1.0, 0.0);\n \
|
||||
hz_tangent = vec4(1.0, 0.0, 0.0, 1.0);\n \
|
||||
float hz_r = hz_d1.x * hz_d2.y - hz_d2.x * hz_d1.y;\n \
|
||||
vec3 hz_t = (hz_e1 * hz_d2.y - hz_e2 * hz_d1.y) * sign(hz_r);\n \
|
||||
vec3 hz_b = (hz_e2 * hz_d1.x - hz_e1 * hz_d2.x) * sign(hz_r);\n \
|
||||
hz_t -= hz_Normal * dot(hz_Normal, hz_t);\n \
|
||||
if (dot(hz_t, hz_t) > 1e-12) {{\n \
|
||||
hz_t = normalize(hz_t);\n \
|
||||
hz_tangent = vec4(hz_t, dot(cross(hz_t, hz_Normal), hz_b) < 0.0 ? -1.0 : 1.0);\n \
|
||||
}}\n \
|
||||
hz_Vertex = vec4(hz_v_pos, 1.0);\n \
|
||||
hz_MultiTexCoord0 = vec4(hz_v_uv, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord1 = vec4(float(hz_v_light.y), float(hz_v_light.x), 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
|
||||
hz_Color = hz_v_color;\n",
|
||||
p0 = corner(0, "pos"),
|
||||
p1 = corner(1, "pos"),
|
||||
p2 = corner(2, "pos"),
|
||||
t0 = corner(0, "uv"),
|
||||
t1 = corner(1, "uv"),
|
||||
t2 = corner(2, "uv"),
|
||||
);
|
||||
let attributes = [
|
||||
("at_tangent", "hz_tangent"),
|
||||
("mc_midTexCoord", "vec4(hz_mid, 0.0, 1.0)"),
|
||||
("vaPosition", "hz_Vertex.xyz"),
|
||||
("vaUV0", "hz_v_uv"),
|
||||
("vaUV1", "ivec2(0, 10)"),
|
||||
("vaUV2", "ivec2(hz_MultiTexCoord1.xy)"),
|
||||
("vaColor", "hz_Color"),
|
||||
("vaNormal", "hz_Normal"),
|
||||
];
|
||||
horizon_shaders::GbuffersInputs {
|
||||
declarations,
|
||||
body,
|
||||
attributes: attributes
|
||||
.iter()
|
||||
.map(|&(n, v)| (n.to_owned(), v.to_owned()))
|
||||
.collect(),
|
||||
after: String::new(),
|
||||
// Cutout, as vanilla's entity types mostly are (OQ-23): the loader's test at 0.1.
|
||||
alpha_test: Some(horizon_shaders::AlphaTest {
|
||||
op: ">",
|
||||
reference: 0.1,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// What `gbuffers_clouds` reads from the clouds' mesh (entity vertices, `vs_cloud`): the
|
||||
/// position moved by the clouds' offset, the colour of the face's shade from their palette,
|
||||
/// full sky light. Set 1 holds the clouds' uniform (`clouds::Uniform`).
|
||||
pub fn cloud_inputs() -> horizon_shaders::GbuffersInputs {
|
||||
let declarations = "layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\
|
||||
layout(location = 2) in uint hz_v_overlay;\nlayout(location = 3) in vec4 hz_v_color;\n\
|
||||
layout(location = 4) in uvec4 hz_v_light;\nlayout(location = 5) in vec4 hz_v_normal;\n\
|
||||
layout(set = 1, binding = 0) uniform HzCloud { vec4 hz_cloud_offset; vec4 hz_cloud_colors[4]; };\n"
|
||||
.to_owned();
|
||||
let body = " hz_Vertex = vec4(hz_v_pos + hz_cloud_offset.xyz, 1.0);\n \
|
||||
hz_MultiTexCoord0 = vec4(hz_v_uv, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord1 = vec4(0.0, 240.0, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
|
||||
hz_Color = hz_cloud_colors[min(hz_v_light.x, 3u)];\n \
|
||||
hz_Normal = dot(hz_v_normal.xyz, hz_v_normal.xyz) > 0.01 ? normalize(hz_v_normal.xyz) : vec3(0.0, 1.0, 0.0);\n"
|
||||
.to_owned();
|
||||
let attributes = [
|
||||
("vaPosition", "hz_Vertex.xyz"),
|
||||
("vaUV0", "hz_v_uv"),
|
||||
("vaUV2", "ivec2(0, 240)"),
|
||||
("vaColor", "hz_Color"),
|
||||
("vaNormal", "hz_Normal"),
|
||||
];
|
||||
horizon_shaders::GbuffersInputs {
|
||||
declarations,
|
||||
body,
|
||||
attributes: attributes
|
||||
.iter()
|
||||
.map(|&(n, v)| (n.to_owned(), v.to_owned()))
|
||||
.collect(),
|
||||
after: String::new(),
|
||||
alpha_test: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `entityColor` for a run whose first quad carries overlay code `overlay`: the hurt red or a
|
||||
/// white flash, its alpha how much of that colour shows over the entity (vanilla mixes the
|
||||
/// overlay texel's colour in by one minus the texel's alpha).
|
||||
pub fn entity_color(overlay: u32) -> [f32; 4] {
|
||||
let [r, g, b, a] = crate::overlay::HURT_TEXEL.map(|v| f32::from(v) / 255.0);
|
||||
let white = |u: u32| {
|
||||
let a = f32::from(crate::overlay::white_alpha(u)) / 255.0;
|
||||
[1.0, 1.0, 1.0, 1.0 - a]
|
||||
};
|
||||
match overlay {
|
||||
1 | 8 => [r, g, b, 1.0 - a],
|
||||
5 => white(15),
|
||||
16..32 => white(overlay - crate::overlay::WHITE),
|
||||
_ => [0.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// One draw: its quads in `PackEntities`' buffer, its program and its slot of `HzDraw`.
|
||||
pub(super) struct Draw {
|
||||
/// The first vertex.
|
||||
pub base: u32,
|
||||
pub quads: u32,
|
||||
/// The kind of program that draws it (`ENTITY`, `BLOCK`, `TRANSLUCENT`, `PARTICLE`).
|
||||
pub program: usize,
|
||||
/// The pack's gbuffers program draws it (else Horizon does).
|
||||
pub pack: bool,
|
||||
/// The pack's shadow program draws it into the shadow map too.
|
||||
pub shadow: bool,
|
||||
pub slot: u32,
|
||||
}
|
||||
|
||||
/// The vertices and per-draw uniforms of the runs a pack draws, rebuilt each frame.
|
||||
pub(super) struct PackEntities {
|
||||
vertices: wgpu::Buffer,
|
||||
/// Set 1: the vertices again, for the quads' corners.
|
||||
pub table: wgpu::BindGroupLayout,
|
||||
pub table_group: wgpu::BindGroup,
|
||||
slots: wgpu::Buffer,
|
||||
pub group: wgpu::BindGroup,
|
||||
stride: u64,
|
||||
/// Two triangles per quad, for `quads` quads.
|
||||
pub indices: wgpu::Buffer,
|
||||
quads: u32,
|
||||
scratch: Vec<Vertex>,
|
||||
uniforms: Vec<u8>,
|
||||
pub draws: Vec<Draw>,
|
||||
}
|
||||
|
||||
impl PackEntities {
|
||||
pub fn new(device: &wgpu::Device, layout: &wgpu::BindGroupLayout) -> Self {
|
||||
let stride = SLOT.max(u64::from(
|
||||
device.limits().min_uniform_buffer_offset_alignment,
|
||||
));
|
||||
let table = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Shader pack entity vertices"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let (vertices, table_group) = Self::vertex_buffer(device, &table, 4096);
|
||||
let (slots, group) = Self::slot_buffer(device, layout, 64, stride);
|
||||
Self {
|
||||
vertices,
|
||||
table,
|
||||
table_group,
|
||||
slots,
|
||||
group,
|
||||
stride,
|
||||
indices: quad_indices(device, 1024),
|
||||
quads: 1024,
|
||||
scratch: Vec::new(),
|
||||
uniforms: Vec::new(),
|
||||
draws: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn vertex_buffer(
|
||||
device: &wgpu::Device,
|
||||
table: &wgpu::BindGroupLayout,
|
||||
vertices: u64,
|
||||
) -> (wgpu::Buffer, wgpu::BindGroup) {
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack entity vertices"),
|
||||
size: vertices * std::mem::size_of::<Vertex>() as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX
|
||||
| wgpu::BufferUsages::STORAGE
|
||||
| wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Shader pack entity vertices"),
|
||||
layout: table,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
(buffer, group)
|
||||
}
|
||||
|
||||
fn slot_buffer(
|
||||
device: &wgpu::Device,
|
||||
layout: &wgpu::BindGroupLayout,
|
||||
slots: u64,
|
||||
stride: u64,
|
||||
) -> (wgpu::Buffer, wgpu::BindGroup) {
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack entity draws"),
|
||||
size: slots * stride,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Shader pack entity draws"),
|
||||
layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &buffer,
|
||||
offset: 0,
|
||||
size: wgpu::BufferSize::new(SLOT),
|
||||
}),
|
||||
}],
|
||||
});
|
||||
(buffer, group)
|
||||
}
|
||||
|
||||
pub fn vertices(&self) -> wgpu::BufferSlice<'_> {
|
||||
self.vertices.slice(..)
|
||||
}
|
||||
|
||||
/// The dynamic offset of draw slot `slot`.
|
||||
pub fn offset(&self, slot: u32) -> u32 {
|
||||
(u64::from(slot) * self.stride) as u32
|
||||
}
|
||||
|
||||
/// Splits `entities` between the pack, which draws the runs of `spans` its programs cover
|
||||
/// (`drawn`: whether it has `gbuffers_entities`, `gbuffers_block` or their fallbacks), and
|
||||
/// Horizon, which draws the rest (`rest`). Uploads the pack's part, and the runs its shadow
|
||||
/// programs draw (`shadow`: entities, block entities).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
layout: &wgpu::BindGroupLayout,
|
||||
entities: &[Vertex],
|
||||
spans: &[EntitySpan],
|
||||
drawn: [bool; PROGRAMS],
|
||||
shadow: [bool; 2],
|
||||
rest: &mut Vec<Vertex>,
|
||||
) {
|
||||
self.draws.clear();
|
||||
self.scratch.clear();
|
||||
self.uniforms.clear();
|
||||
rest.clear();
|
||||
let first = spans.first().map_or(entities.len(), |s| s.start as usize);
|
||||
rest.extend_from_slice(&entities[..first.min(entities.len())]);
|
||||
for (span, range) in runs(entities.len(), spans) {
|
||||
let run = &entities[range];
|
||||
let program = program_of(&span).filter(|_| plain(run));
|
||||
let pack = program.is_some_and(|p| drawn[p]);
|
||||
let casts = program.is_some_and(|p| shadow.get(p).copied().unwrap_or(false));
|
||||
if !pack {
|
||||
rest.extend_from_slice(run);
|
||||
}
|
||||
let Some(program) = program.filter(|_| (pack || casts) && !run.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
let start = self.scratch.len() as u32;
|
||||
self.scratch.extend_from_slice(run);
|
||||
let (entity_id, block_id) = match program {
|
||||
BLOCK => (0, span.id),
|
||||
_ => (span.id, 0),
|
||||
};
|
||||
let mut bytes = [0u8; SLOT as usize];
|
||||
bytes[0..4].copy_from_slice(&(span.stage as i32).to_le_bytes());
|
||||
bytes[4..8].copy_from_slice(&entity_id.to_le_bytes());
|
||||
bytes[8..12].copy_from_slice(&block_id.to_le_bytes());
|
||||
for (i, c) in entity_color(run[0].layer).iter().enumerate() {
|
||||
bytes[16 + 4 * i..20 + 4 * i].copy_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
self.uniforms.extend_from_slice(&bytes);
|
||||
self.uniforms
|
||||
.resize(self.uniforms.len() + (self.stride - SLOT) as usize, 0);
|
||||
self.draws.push(Draw {
|
||||
base: start,
|
||||
quads: run.len() as u32 / 4,
|
||||
program,
|
||||
pack,
|
||||
shadow: casts,
|
||||
slot: self.draws.len() as u32,
|
||||
});
|
||||
}
|
||||
if self.draws.is_empty() {
|
||||
return;
|
||||
}
|
||||
let vertex_size = std::mem::size_of::<Vertex>() as u64;
|
||||
let (need_vertices, need_slots) = (self.scratch.len() as u64, self.draws.len() as u64);
|
||||
let have_vertices = self.vertices.size() / vertex_size;
|
||||
let have_slots = self.slots.size() / self.stride;
|
||||
if need_vertices > have_vertices {
|
||||
(self.vertices, self.table_group) =
|
||||
Self::vertex_buffer(device, &self.table, need_vertices.next_power_of_two());
|
||||
}
|
||||
if need_slots > have_slots {
|
||||
(self.slots, self.group) =
|
||||
Self::slot_buffer(device, layout, need_slots.next_power_of_two(), self.stride);
|
||||
}
|
||||
let quads = self.draws.iter().map(|d| d.quads).max().unwrap_or(0);
|
||||
if quads > self.quads {
|
||||
self.quads = quads.next_power_of_two();
|
||||
self.indices = quad_indices(device, self.quads);
|
||||
}
|
||||
queue.write_buffer(&self.vertices, 0, bytemuck::cast_slice(&self.scratch));
|
||||
queue.write_buffer(&self.slots, 0, &self.uniforms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two triangles for each of `quads` quads, from vertex 0.
|
||||
pub(super) fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer {
|
||||
let indices: Vec<u32> = (0..quads)
|
||||
.flat_map(|q| [0, 1, 2, 0, 2, 3].map(|i| q * 4 + i))
|
||||
.collect();
|
||||
wgpu::util::DeviceExt::create_buffer_init(
|
||||
device,
|
||||
&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Shader pack entity indices"),
|
||||
contents: bytemuck::cast_slice(&indices),
|
||||
usage: wgpu::BufferUsages::INDEX,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether a run holds only geometry a gbuffers program can draw from the shared atlas: no
|
||||
/// celestial body, cloud, beam, End portal or crack (overlay codes Horizon's entity shader
|
||||
/// draws in its own way; entity.wgsl).
|
||||
fn plain(run: &[Vertex]) -> bool {
|
||||
run.iter()
|
||||
.step_by(4)
|
||||
.all(|v| !matches!(v.layer, 2 | 4 | 6 | 9 | 10 | 11 | 12))
|
||||
}
|
||||
|
||||
/// The programs of entity runs, in the order they draw.
|
||||
pub const ENTITY: usize = 0;
|
||||
pub const BLOCK: usize = 1;
|
||||
pub const TRANSLUCENT: usize = 2;
|
||||
pub const PARTICLE: usize = 3;
|
||||
pub const PROGRAMS: usize = 4;
|
||||
|
||||
/// Which program draws `span`'s run, given which of them (or their fallbacks) the pack has;
|
||||
/// `None`: Horizon draws it.
|
||||
#[cfg(test)]
|
||||
fn drawn_by_pack(span: &EntitySpan, drawn: [bool; PROGRAMS]) -> Option<usize> {
|
||||
program_of(span).filter(|&p| drawn[p])
|
||||
}
|
||||
|
||||
/// The kind of program that draws `span`'s run, when a pack may.
|
||||
pub fn program_of(span: &EntitySpan) -> Option<usize> {
|
||||
Some(if span.stage == render_stage("ENTITIES") {
|
||||
if span.translucent {
|
||||
TRANSLUCENT
|
||||
} else {
|
||||
ENTITY
|
||||
}
|
||||
} else if span.stage == render_stage("BLOCK_ENTITIES") {
|
||||
BLOCK
|
||||
} else if span.stage == render_stage("PARTICLES") {
|
||||
PARTICLE
|
||||
} else {
|
||||
return None;
|
||||
})
|
||||
}
|
||||
|
||||
/// Each span with its vertex range: from its start to the next span's (or the end).
|
||||
pub fn runs(
|
||||
len: usize,
|
||||
spans: &[EntitySpan],
|
||||
) -> impl Iterator<Item = (EntitySpan, Range<usize>)> + '_ {
|
||||
spans.iter().enumerate().map(move |(i, s)| {
|
||||
let end = spans.get(i + 1).map_or(len, |n| n.start as usize);
|
||||
let start = (s.start as usize).min(len);
|
||||
(*s, start..end.clamp(start, len))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn runs_split_the_list_between_pack_and_horizon() {
|
||||
let v = |layer| Vertex {
|
||||
layer,
|
||||
..bytemuck::Zeroable::zeroed()
|
||||
};
|
||||
let span = |start, stage: &str, id| EntitySpan {
|
||||
start,
|
||||
stage: render_stage(stage),
|
||||
id,
|
||||
translucent: false,
|
||||
};
|
||||
let spans = [
|
||||
span(2, "ENTITIES", 7),
|
||||
span(5, "PARTICLES", 0),
|
||||
span(6, "BLOCK_ENTITIES", 9),
|
||||
];
|
||||
let ranges: Vec<_> = runs(10, &spans).map(|(_, r)| r).collect();
|
||||
assert_eq!(ranges, [2..5, 5..6, 6..10]);
|
||||
let all = [true; PROGRAMS];
|
||||
assert_eq!(drawn_by_pack(&spans[0], all), Some(ENTITY));
|
||||
assert_eq!(drawn_by_pack(&spans[1], all), Some(PARTICLE));
|
||||
assert_eq!(drawn_by_pack(&spans[1], [true, true, true, false]), None);
|
||||
assert_eq!(drawn_by_pack(&spans[2], [true, false, true, true]), None);
|
||||
assert_eq!(drawn_by_pack(&spans[2], all), Some(BLOCK));
|
||||
let shadow = EntitySpan {
|
||||
translucent: true,
|
||||
..spans[0]
|
||||
};
|
||||
assert_eq!(drawn_by_pack(&shadow, all), Some(TRANSLUCENT));
|
||||
assert_eq!(drawn_by_pack(&span(0, "DESTROY", 0), all), None);
|
||||
// A beacon beam's quads stay Horizon's.
|
||||
assert!(plain(&[v(0), v(0), v(0), v(0), v(1)]));
|
||||
assert!(!plain(&[v(0), v(0), v(0), v(0), v(6)]));
|
||||
assert_eq!(entity_color(1)[0], 1.0);
|
||||
assert!((entity_color(1)[3] - (1.0 - 178.0 / 255.0)).abs() < 1e-6);
|
||||
assert_eq!(entity_color(0), [0.0; 4]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! The first-person hand and held items drawn by a shader pack's `gbuffers_hand` (spec 2.3):
|
||||
//! `Frame::hand`'s entity vertices, read as entities are (`pack_entities::inputs`), with the
|
||||
//! hand's own projection as `gl_ProjectionMatrix` (5.2: `gbufferProjection` stays the world's).
|
||||
|
||||
use glam::Mat4;
|
||||
|
||||
use super::Vertex;
|
||||
|
||||
/// `MC_HAND_DEPTH`'s value (1.5): the hand's depth is scaled by it through its projection, so
|
||||
/// that it sits in front of the world in the shared depth buffer.
|
||||
const HAND_DEPTH: f32 = 0.125;
|
||||
|
||||
/// `HzHand`: the hand's projection and its inverse.
|
||||
const UNIFORM: u64 = 2 * 64;
|
||||
|
||||
/// What `gbuffers_hand` reads: the entity inputs, and the hand's projection from set 1.
|
||||
pub fn inputs() -> horizon_shaders::GbuffersInputs {
|
||||
let mut inputs = super::pack_entities::inputs();
|
||||
inputs.declarations.push_str(
|
||||
"layout(set = 1, binding = 1) uniform HzHand { mat4 hz_hand_projection; mat4 hz_hand_projection_inverse; };\n",
|
||||
);
|
||||
inputs.body.push_str(
|
||||
" hz_ProjectionMatrix = hz_hand_projection;\n \
|
||||
hz_ProjectionMatrixInverse = hz_hand_projection_inverse;\n \
|
||||
hz_ModelViewProjectionMatrix = hz_hand_projection * hz_ModelViewMatrix;\n",
|
||||
);
|
||||
inputs
|
||||
}
|
||||
|
||||
/// The hand's projection in GL's conventions: `hud_fov` degrees, the view bob, depth scaled by
|
||||
/// `MC_HAND_DEPTH`.
|
||||
pub fn projection(hud_fov: f32, aspect: f32, far: f32, bob: Mat4) -> Mat4 {
|
||||
Mat4::from_scale(glam::Vec3::new(1.0, 1.0, HAND_DEPTH))
|
||||
* Mat4::perspective_rh_gl(hud_fov.to_radians(), aspect, 0.05, far)
|
||||
* bob
|
||||
}
|
||||
|
||||
/// The hand's vertices (also read at set 1 for normals and tangents), its uniform and quad
|
||||
/// indices.
|
||||
pub struct PackHand {
|
||||
pub layout: wgpu::BindGroupLayout,
|
||||
vertices: wgpu::Buffer,
|
||||
uniform: wgpu::Buffer,
|
||||
pub group: wgpu::BindGroup,
|
||||
pub indices: wgpu::Buffer,
|
||||
capacity: u32,
|
||||
/// Quads uploaded this frame.
|
||||
pub quads: u32,
|
||||
}
|
||||
|
||||
impl PackHand {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
let entry = |binding, ty| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Shader pack hand"),
|
||||
entries: &[
|
||||
entry(0, wgpu::BufferBindingType::Storage { read_only: true }),
|
||||
entry(1, wgpu::BufferBindingType::Uniform),
|
||||
],
|
||||
});
|
||||
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack hand"),
|
||||
size: UNIFORM,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let capacity = 256;
|
||||
let (vertices, group) = Self::vertex_buffer(device, &layout, &uniform, capacity);
|
||||
Self {
|
||||
indices: super::pack_entities::quad_indices(device, capacity),
|
||||
layout,
|
||||
vertices,
|
||||
uniform,
|
||||
group,
|
||||
capacity,
|
||||
quads: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn vertex_buffer(
|
||||
device: &wgpu::Device,
|
||||
layout: &wgpu::BindGroupLayout,
|
||||
uniform: &wgpu::Buffer,
|
||||
quads: u32,
|
||||
) -> (wgpu::Buffer, wgpu::BindGroup) {
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack hand vertices"),
|
||||
size: u64::from(quads) * 4 * std::mem::size_of::<Vertex>() as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX
|
||||
| wgpu::BufferUsages::STORAGE
|
||||
| wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Shader pack hand"),
|
||||
layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: uniform.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
(buffer, group)
|
||||
}
|
||||
|
||||
/// Uploads this frame's hand and its projection.
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
hand: &[Vertex],
|
||||
projection: Mat4,
|
||||
) {
|
||||
self.quads = (hand.len() / 4) as u32;
|
||||
if self.quads == 0 {
|
||||
return;
|
||||
}
|
||||
if self.quads > self.capacity {
|
||||
self.capacity = self.quads.next_power_of_two();
|
||||
(self.vertices, self.group) =
|
||||
Self::vertex_buffer(device, &self.layout, &self.uniform, self.capacity);
|
||||
self.indices = super::pack_entities::quad_indices(device, self.capacity);
|
||||
}
|
||||
queue.write_buffer(&self.vertices, 0, bytemuck::cast_slice(hand));
|
||||
let matrices = [projection, projection.inverse()].map(|m| m.to_cols_array());
|
||||
queue.write_buffer(&self.uniform, 0, bytemuck::cast_slice(&matrices));
|
||||
}
|
||||
|
||||
pub fn vertices(&self) -> wgpu::BufferSlice<'_> {
|
||||
self.vertices.slice(..)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The hand's window depth lies within `MC_HAND_DEPTH` of the middle (packs tell the hand
|
||||
/// apart by it), and x, y match the plain projection.
|
||||
#[test]
|
||||
fn hand_depth_is_scaled_around_the_middle() {
|
||||
let p = projection(70.0, 16.0 / 9.0, 512.0, Mat4::IDENTITY);
|
||||
let plain = Mat4::perspective_rh_gl(70f32.to_radians(), 16.0 / 9.0, 0.05, 512.0);
|
||||
for z in [-0.06f32, -0.5, -3.0, -400.0] {
|
||||
let v = glam::Vec4::new(0.1, -0.2, z, 1.0);
|
||||
let (a, b) = (p * v, plain * v);
|
||||
let window = (a.z / a.w) * 0.5 + 0.5;
|
||||
assert!(
|
||||
(window - 0.5).abs() <= HAND_DEPTH * 0.5 + 1e-6,
|
||||
"{z}: {window}"
|
||||
);
|
||||
assert!((a.x / a.w - b.x / b.w).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
// Helpers of a shader pack's post-processing (pack_post.rs): the world into colortex0 and
|
||||
// depthtex0, and colortex0 onto the screen for packs without `final`.
|
||||
// depthtex0 (a depth attachment, for terrain's depth test), and colortex0 onto the screen for
|
||||
// packs without `final`.
|
||||
|
||||
@vertex
|
||||
fn vs_full(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
|
||||
@@ -12,7 +13,7 @@ fn vs_full(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
|
||||
|
||||
struct World {
|
||||
@location(0) color: vec4<f32>,
|
||||
@location(1) depth: vec4<f32>,
|
||||
@builtin(frag_depth) depth: f32,
|
||||
}
|
||||
|
||||
// Pack buffers keep GL's rows (row 0 at the bottom), and GL's window depth: Horizon's
|
||||
@@ -23,7 +24,7 @@ fn fs_blit(@builtin(position) p: vec4<f32>) -> World {
|
||||
let at = vec2<i32>(i32(p.x), size.y - 1 - i32(p.y));
|
||||
var out: World;
|
||||
out.color = textureLoad(source, at, 0);
|
||||
out.depth = vec4<f32>(1.0 - textureLoad(world_depth, at, 0), 0.0, 0.0, 1.0);
|
||||
out.depth = 1.0 - textureLoad(world_depth, at, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -52,3 +53,11 @@ fn vs_uv(@builtin(vertex_index) i: u32) -> Full {
|
||||
fn fs_copy(v: Full) -> @location(0) vec4<f32> {
|
||||
return textureSample(source, linear, v.uv);
|
||||
}
|
||||
|
||||
// One level of a buffer's mip chain from the level above (6.1.7): the average of the 2×2
|
||||
// texels under each destination texel, by one bilinear sample at their shared corner.
|
||||
@fragment
|
||||
fn fs_down(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let size = max(textureDimensions(source) / 2u, vec2<u32>(1u));
|
||||
return textureSampleLevel(source, linear, p.xy / vec2<f32>(size), 0.0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//! A shader pack's shadow buffers (spec 6.3): the shadow map's depth (`shadowtex0`, and
|
||||
//! `shadowtex1` without translucent geometry), and the colour buffers `shadowcolor0/1`, each
|
||||
//! with two sides that `shadowcomp` programs flip as composite programs flip colortex (6.1.6).
|
||||
//! Square, `shadowMapResolution` pixels.
|
||||
|
||||
type Ops<T> = wgpu::Operations<T>;
|
||||
type Color = wgpu::Color;
|
||||
|
||||
/// Loaded and stored.
|
||||
pub(super) fn load<T>() -> Ops<T> {
|
||||
wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(c: [f32; 4]) -> Ops<Color> {
|
||||
wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: c[0].into(),
|
||||
g: c[1].into(),
|
||||
b: c[2].into(),
|
||||
a: c[3].into(),
|
||||
}),
|
||||
store: wgpu::StoreOp::Store,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the shadow pass writes and the programs read.
|
||||
pub(super) struct ShadowTargets {
|
||||
pub size: u32,
|
||||
/// `shadowtex0`, written by the shadow pass.
|
||||
pub depth: (wgpu::Texture, wgpu::TextureView),
|
||||
/// `shadowtex1`: a copy of `shadowtex0` taken before translucent terrain, when read.
|
||||
pub depth1: Option<(wgpu::Texture, wgpu::TextureView)>,
|
||||
/// Both sides of each shadowcolor buffer used.
|
||||
pub color: [Option<[wgpu::TextureView; 2]>; 2],
|
||||
/// The clear colour of each buffer cleared every frame.
|
||||
pub clears: [Option<[f32; 4]>; 2],
|
||||
/// Bit n set: B is shadowcolor n's "main".
|
||||
pub main: u16,
|
||||
/// Nothing cleared yet this frame: the first pass into the shadow buffers clears them as it
|
||||
/// begins (`clear_ops`), which saves a pass that loads and stores them all on tiled GPUs.
|
||||
fresh: bool,
|
||||
/// Bit n set: shadowcolor n was cleared that way.
|
||||
cleared: u8,
|
||||
/// Depth comparison for `sampler2DShadow` (hardware filtering): linear, as GL filters it.
|
||||
pub comparison: wgpu::Sampler,
|
||||
}
|
||||
|
||||
fn target(
|
||||
device: &wgpu::Device,
|
||||
label: &str,
|
||||
size: u32,
|
||||
format: wgpu::TextureFormat,
|
||||
copy: wgpu::TextureUsages,
|
||||
) -> (wgpu::Texture, wgpu::TextureView) {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width: size,
|
||||
height: size,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | copy,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&Default::default());
|
||||
(texture, view)
|
||||
}
|
||||
|
||||
impl ShadowTargets {
|
||||
/// The buffers of `shadow` the pack uses: `colors` (bit n: shadowcolor n), `depth1` when
|
||||
/// some program reads `shadowtex1`. The resolution is kept within the device's limit.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
shadow: &horizon_shaders::Shadow,
|
||||
formats: [wgpu::TextureFormat; 2],
|
||||
colors: u16,
|
||||
depth1: bool,
|
||||
) -> Self {
|
||||
let size = shadow
|
||||
.resolution
|
||||
.clamp(1, device.limits().max_texture_dimension_2d);
|
||||
let copy = wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST;
|
||||
let depth = wgpu::TextureFormat::Depth32Float;
|
||||
let color = std::array::from_fn(|n| {
|
||||
(colors & 1 << n != 0).then(|| {
|
||||
[0, 1].map(|side| {
|
||||
let label = format!("Shader pack shadowcolor{n} {}", ["A", "B"][side]);
|
||||
target(
|
||||
device,
|
||||
&label,
|
||||
size,
|
||||
formats[n],
|
||||
wgpu::TextureUsages::empty(),
|
||||
)
|
||||
.1
|
||||
})
|
||||
})
|
||||
});
|
||||
Self {
|
||||
size,
|
||||
depth: target(device, "Shader pack shadowtex0", size, depth, copy),
|
||||
depth1: depth1.then(|| target(device, "Shader pack shadowtex1", size, depth, copy)),
|
||||
color,
|
||||
clears: std::array::from_fn(|n| {
|
||||
let b = &shadow.colors[n];
|
||||
b.clear.then(|| b.clear_color.unwrap_or([1.0; 4]))
|
||||
}),
|
||||
main: 0,
|
||||
fresh: false,
|
||||
cleared: 0,
|
||||
comparison: device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Shader pack shadow comparison"),
|
||||
compare: Some(wgpu::CompareFunction::LessEqual),
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Side `alt` (of "main" and "alt") of shadowcolor `n`.
|
||||
pub fn color(&self, n: usize, alt: bool) -> Option<&wgpu::TextureView> {
|
||||
let side = usize::from(self.main & 1 << n != 0) ^ usize::from(alt);
|
||||
self.color.get(n)?.as_ref().map(|c| &c[side])
|
||||
}
|
||||
|
||||
/// A new frame: the shadow map and the shadowcolor buffers cleared every frame (6.3) are
|
||||
/// cleared by the first pass that begins (`clear_ops`), or else by `clear_rest`.
|
||||
pub fn begin_frame(&mut self) {
|
||||
self.fresh = true;
|
||||
self.cleared = 0;
|
||||
}
|
||||
|
||||
/// The load operations of a pass into the shadow map and shadowcolor buffers `writes`:
|
||||
/// clears in the frame's first one, loads after.
|
||||
pub fn clear_ops(
|
||||
&mut self,
|
||||
writes: impl Iterator<Item = usize>,
|
||||
) -> (Ops<f32>, [Ops<Color>; 2]) {
|
||||
if !std::mem::take(&mut self.fresh) {
|
||||
return (load(), [load(); 2]);
|
||||
}
|
||||
let mut colors = [load(); 2];
|
||||
for n in writes.filter(|&n| n < 2) {
|
||||
if let Some(c) = self.clears[n] {
|
||||
colors[n] = clear(c);
|
||||
self.cleared |= 1 << n;
|
||||
}
|
||||
}
|
||||
let depth = wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store: wgpu::StoreOp::Store,
|
||||
};
|
||||
(depth, colors)
|
||||
}
|
||||
|
||||
/// Clears what no pass has cleared this frame: all of it when no shadow program drew, the
|
||||
/// cleared shadowcolor buffers the first one did not write.
|
||||
pub fn clear_rest(&mut self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let depth = std::mem::take(&mut self.fresh);
|
||||
let cleared = std::mem::replace(&mut self.cleared, 0b11);
|
||||
let attachments: Vec<_> = (0..2)
|
||||
.filter(|n| cleared & 1 << n == 0)
|
||||
.filter_map(|n| {
|
||||
Some(Some(wgpu::RenderPassColorAttachment {
|
||||
view: self.color(n, false)?,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: clear(self.clears[n]?),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
if !depth && attachments.is_empty() {
|
||||
return;
|
||||
}
|
||||
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Shader pack shadow clear"),
|
||||
color_attachments: &attachments,
|
||||
depth_stencil_attachment: depth.then_some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth.1,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store: wgpu::StoreOp::Store,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
/// `shadowtex1`: the shadow map as it is now (before translucent geometry).
|
||||
pub fn copy_depth1(&self, encoder: &mut wgpu::CommandEncoder) {
|
||||
if let Some((copy, _)) = &self.depth1 {
|
||||
encoder.copy_texture_to_texture(
|
||||
self.depth.0.as_image_copy(),
|
||||
copy.as_image_copy(),
|
||||
self.depth.0.size(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! The vanilla sky's geometry for a shader pack's `gbuffers_skybasic` (spec 2.3): the sky disc,
|
||||
//! the sunset fan, the stars and the void disc, as Horizon's own sky draws them (terrain.wgsl,
|
||||
//! stars.rs), built once into a vertex buffer. The frame's colours and rotations sit in a small
|
||||
//! uniform (set 1) that the vertex inputs read. `gbuffers_skytextured` draws the frame's sun and
|
||||
//! moon quads, textured from the shared atlas.
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// A sky vertex: a position and what it belongs to (`SKY`...).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Vertex {
|
||||
pos: [f32; 3],
|
||||
kind: u32,
|
||||
}
|
||||
|
||||
const SKY: u32 = 0;
|
||||
const SUNSET_APEX: u32 = 1;
|
||||
/// Rim of the sunset fan: `pos.xy` is (sin, cos) of its angle.
|
||||
const SUNSET_RIM: u32 = 2;
|
||||
const STAR: u32 = 3;
|
||||
const VOID: u32 = 4;
|
||||
|
||||
/// The frame's sky (std140).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Uniform {
|
||||
/// Camera-relative world from star space.
|
||||
stars: [[f32; 4]; 4],
|
||||
/// Sky colour, alpha 1.
|
||||
color: [f32; 4],
|
||||
/// Sunset colour and alpha.
|
||||
sunrise: [f32; 4],
|
||||
/// cos and sin of the sunset fan's turn, star brightness.
|
||||
sun: [f32; 4],
|
||||
}
|
||||
|
||||
/// A sun or moon vertex: position, atlas UV, RGBA8 colour.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Celestial {
|
||||
pos: [f32; 3],
|
||||
uv: [f32; 2],
|
||||
color: u32,
|
||||
}
|
||||
|
||||
/// Quads of the sun and moon (and room to spare).
|
||||
const CELESTIAL_QUADS: usize = 4;
|
||||
|
||||
const CELESTIAL_ATTRIBUTES: [wgpu::VertexAttribute; 3] =
|
||||
wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Unorm8x4];
|
||||
|
||||
pub(super) const ATTRIBUTES: [wgpu::VertexAttribute; 2] =
|
||||
wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint32];
|
||||
|
||||
/// What `gbuffers_skybasic` reads from these vertices.
|
||||
pub fn inputs() -> horizon_shaders::GbuffersInputs {
|
||||
let declarations =
|
||||
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in uint hz_v_kind;\n\
|
||||
layout(set = 1, binding = 0) uniform HzSky { mat4 hz_sky_stars; vec4 hz_sky_color; \
|
||||
vec4 hz_sky_sunrise; vec4 hz_sky_sun; };\n"
|
||||
.to_owned();
|
||||
let body = format!(
|
||||
" vec3 hz_p = hz_v_pos;\n \
|
||||
hz_Color = hz_sky_color;\n \
|
||||
if (hz_v_kind == {SUNSET_APEX}u || hz_v_kind == {SUNSET_RIM}u) {{\n \
|
||||
vec3 hz_l = vec3(0.0, 100.0, 0.0);\n \
|
||||
hz_Color = hz_sky_sunrise;\n \
|
||||
if (hz_v_kind == {SUNSET_RIM}u) {{\n \
|
||||
hz_l = vec3(hz_v_pos.xy * 120.0, -hz_v_pos.y * 40.0 * hz_sky_sunrise.a);\n \
|
||||
hz_Color.a = 0.0;\n \
|
||||
}}\n \
|
||||
vec3 hz_r = vec3(hz_l.x * hz_sky_sun.x - hz_l.y * hz_sky_sun.y, hz_l.x * hz_sky_sun.y + hz_l.y * hz_sky_sun.x, hz_l.z);\n \
|
||||
hz_p = vec3(hz_r.x, -hz_r.z, hz_r.y);\n \
|
||||
}} else if (hz_v_kind == {STAR}u) {{\n \
|
||||
hz_p = (hz_sky_stars * vec4(hz_v_pos, 1.0)).xyz;\n \
|
||||
hz_Color = vec4(hz_sky_sun.z);\n \
|
||||
}} else if (hz_v_kind == {VOID}u) {{\n \
|
||||
hz_Color = vec4(0.0, 0.0, 0.0, 1.0);\n \
|
||||
}}\n \
|
||||
hz_Vertex = vec4(hz_p, 1.0);\n \
|
||||
hz_MultiTexCoord0 = vec4(0.0, 0.0, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord1 = vec4(0.0, 240.0, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
|
||||
hz_Normal = vec3(0.0, 1.0, 0.0);\n"
|
||||
);
|
||||
horizon_shaders::GbuffersInputs {
|
||||
declarations,
|
||||
body,
|
||||
attributes: vec![
|
||||
("vaPosition".into(), "hz_Vertex.xyz".into()),
|
||||
("vaColor".into(), "hz_Color".into()),
|
||||
("vaNormal".into(), "hz_Normal".into()),
|
||||
],
|
||||
// At the far plane: the sky shows only where nothing else drew, and it writes no depth.
|
||||
after: " gl_Position.z = gl_Position.w;\n".into(),
|
||||
alpha_test: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What `gbuffers_skytextured` reads from the sun and moon's vertices.
|
||||
pub fn celestial_inputs() -> horizon_shaders::GbuffersInputs {
|
||||
horizon_shaders::GbuffersInputs {
|
||||
declarations:
|
||||
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\
|
||||
layout(location = 2) in vec4 hz_v_color;\n"
|
||||
.into(),
|
||||
body: " hz_Vertex = vec4(hz_v_pos, 1.0);\n \
|
||||
hz_MultiTexCoord0 = vec4(hz_v_uv, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord1 = vec4(0.0, 240.0, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
|
||||
hz_Color = hz_v_color;\n \
|
||||
hz_Normal = vec3(0.0, 0.0, 1.0);\n"
|
||||
.into(),
|
||||
attributes: vec![
|
||||
("vaPosition".into(), "hz_Vertex.xyz".into()),
|
||||
("vaUV0".into(), "hz_v_uv".into()),
|
||||
("vaColor".into(), "hz_Color".into()),
|
||||
("vaNormal".into(), "hz_Normal".into()),
|
||||
],
|
||||
after: " gl_Position.z = gl_Position.w;\n".into(),
|
||||
alpha_test: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One draw of the sky: its render stage, whether `gbuffers_skytextured` draws it, its vertices.
|
||||
pub(super) struct Part {
|
||||
pub stage: &'static str,
|
||||
pub textured: bool,
|
||||
pub range: Range<u32>,
|
||||
}
|
||||
|
||||
/// A disc fan at height `y`, radius 512, as triangles (SkyRenderer's sky and void discs).
|
||||
fn disc(y: f32, kind: u32, out: &mut Vec<Vertex>) {
|
||||
let sign = y.signum();
|
||||
let rim = |i: i32| {
|
||||
let a = (i as f32).to_radians();
|
||||
Vertex {
|
||||
pos: [sign * 512.0 * a.cos(), y, 512.0 * a.sin()],
|
||||
kind,
|
||||
}
|
||||
};
|
||||
let centre = Vertex {
|
||||
pos: [0.0, y, 0.0],
|
||||
kind,
|
||||
};
|
||||
for i in (-180..180).step_by(45) {
|
||||
out.extend([centre, rim(i), rim(i + 45)]);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct PackSky {
|
||||
vertices: wgpu::Buffer,
|
||||
celestial: wgpu::Buffer,
|
||||
uniform: wgpu::Buffer,
|
||||
pub layout: wgpu::BindGroupLayout,
|
||||
group: wgpu::BindGroup,
|
||||
/// Vertex ranges of the sky disc, the sunset fan, the stars and the void.
|
||||
ranges: [Range<u32>; 4],
|
||||
}
|
||||
|
||||
impl PackSky {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
let mut v = Vec::new();
|
||||
disc(16.0, SKY, &mut v);
|
||||
let sky = 0..v.len() as u32;
|
||||
let apex = Vertex {
|
||||
pos: [0.0; 3],
|
||||
kind: SUNSET_APEX,
|
||||
};
|
||||
let rim = |i: u32| {
|
||||
let a = i as f32 * std::f32::consts::TAU / 16.0;
|
||||
Vertex {
|
||||
pos: [a.sin(), a.cos(), 0.0],
|
||||
kind: SUNSET_RIM,
|
||||
}
|
||||
};
|
||||
for i in 0..16 {
|
||||
v.extend([apex, rim(i), rim(i + 1)]);
|
||||
}
|
||||
let sunset = sky.end..v.len() as u32;
|
||||
v.extend(
|
||||
super::stars::star_triangles()
|
||||
.into_iter()
|
||||
.map(|pos| Vertex { pos, kind: STAR }),
|
||||
);
|
||||
let stars = sunset.end..v.len() as u32;
|
||||
disc(-4.0, VOID, &mut v);
|
||||
let void = stars.end..v.len() as u32;
|
||||
let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Shader pack sky"),
|
||||
contents: bytemuck::cast_slice(&v),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
let celestial = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack sun and moon"),
|
||||
size: (std::mem::size_of::<Celestial>() * 6 * CELESTIAL_QUADS) as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack sky"),
|
||||
size: std::mem::size_of::<Uniform>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Shader pack sky"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Shader pack sky"),
|
||||
layout: &layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: uniform.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
Self {
|
||||
vertices,
|
||||
celestial,
|
||||
uniform,
|
||||
layout,
|
||||
group,
|
||||
ranges: [sky, sunset, stars, void],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn buffers() -> [Option<wgpu::VertexBufferLayout<'static>>; 1] {
|
||||
[Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Vertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &ATTRIBUTES,
|
||||
})]
|
||||
}
|
||||
|
||||
pub fn celestial_buffers() -> [Option<wgpu::VertexBufferLayout<'static>>; 1] {
|
||||
[Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Celestial>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &CELESTIAL_ATTRIBUTES,
|
||||
})]
|
||||
}
|
||||
|
||||
/// Writes the frame's sky and returns its draws in vanilla's order: the disc, the sunset
|
||||
/// fan while the sun is near the horizon, the sun and the moon, the stars and, with the
|
||||
/// camera low, the void. `tilt` is the pack's `sunPathRotation` (degrees): the sun, moon
|
||||
/// and stars turn with it (7.1).
|
||||
pub fn prepare(&self, queue: &wgpu::Queue, frame: &super::Frame, tilt: f32) -> Vec<Part> {
|
||||
let turn = super::pack_uniforms::tilt_matrix(tilt);
|
||||
let sun_angle = frame.sky.sun_angle.to_radians();
|
||||
// The fan turns to the other horizon in the afternoon (terrain.wgsl's sunrise_weight).
|
||||
let flip = if sun_angle.sin() < 0.0 { 180f32 } else { 0.0 };
|
||||
let theta = (flip + 90.0).to_radians();
|
||||
let (rotation, brightness) = frame.stars.unwrap_or_default();
|
||||
let [r, g, b] = frame.sky.sky_color;
|
||||
let uniform = Uniform {
|
||||
stars: (turn * rotation).to_cols_array_2d(),
|
||||
color: [r, g, b, 1.0],
|
||||
sunrise: frame.sky.sunrise_color,
|
||||
sun: [theta.cos(), theta.sin(), brightness.clamp(0.0, 1.0), 0.0],
|
||||
};
|
||||
queue.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniform));
|
||||
// The sun's quad, then the moon's (Game::celestial_geometry), as triangles.
|
||||
let quads = frame
|
||||
.celestial
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.take(CELESTIAL_QUADS);
|
||||
let triangles: Vec<Celestial> = quads
|
||||
.clone()
|
||||
.flat_map(|q| [0, 1, 2, 0, 2, 3].map(|i| q[i]))
|
||||
.map(|v| Celestial {
|
||||
pos: turn.transform_vector3(v.pos.into()).into(),
|
||||
uv: v.uv,
|
||||
color: v.color,
|
||||
})
|
||||
.collect();
|
||||
queue.write_buffer(&self.celestial, 0, bytemuck::cast_slice(&triangles));
|
||||
let [sky, sunset, stars, void] = self.ranges.clone();
|
||||
let part = |stage, textured, range| Part {
|
||||
stage,
|
||||
textured,
|
||||
range,
|
||||
};
|
||||
let mut parts = vec![part("SKY", false, sky)];
|
||||
if frame.sky.sunrise_color[3] > 0.001 {
|
||||
parts.push(part("SUNSET", false, sunset));
|
||||
}
|
||||
for (i, stage) in ["SUN", "MOON"].into_iter().enumerate().take(quads.len()) {
|
||||
parts.push(part(stage, true, i as u32 * 6..i as u32 * 6 + 6));
|
||||
}
|
||||
if frame.stars.is_some() {
|
||||
parts.push(part("STARS", false, stars));
|
||||
}
|
||||
if frame.dark_disc {
|
||||
parts.push(part("VOID", false, void));
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Binds the vertices of the `textured` (sun and moon) or other parts.
|
||||
pub fn bind(&self, pass: &mut wgpu::RenderPass<'_>, textured: bool) {
|
||||
if textured {
|
||||
pass.set_vertex_buffer(0, self.celestial.slice(..));
|
||||
} else {
|
||||
pass.set_bind_group(1, &self.group, &[]);
|
||||
pass.set_vertex_buffer(0, self.vertices.slice(..));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Developers' aid: `HORIZON_SHADER_PACK_TIMING=1` times every pass of a shader pack on the
|
||||
//! GPU, one frame in `EVERY`, and logs each pass's median every `REPORT` timed frames. The
|
||||
//! frame after a timed one waits for the GPU before reading the timestamps (Metal resolves
|
||||
//! them without waiting for the passes that write them), so timing slows the game.
|
||||
|
||||
const EVERY: u32 = 30;
|
||||
const REPORT: usize = 30;
|
||||
/// Passes timed per frame at most (two timestamps each).
|
||||
const CAPACITY: u32 = 64;
|
||||
|
||||
pub(super) struct PassTiming {
|
||||
queries: wgpu::QuerySet,
|
||||
resolve: wgpu::Buffer,
|
||||
read: wgpu::Buffer,
|
||||
period_ns: f32,
|
||||
frame: u32,
|
||||
/// The passes timed in the frame being recorded or waiting to be read, in order.
|
||||
names: Vec<String>,
|
||||
timed: bool,
|
||||
samples: Vec<(String, Vec<f32>)>,
|
||||
reports: usize,
|
||||
}
|
||||
|
||||
impl PassTiming {
|
||||
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Self> {
|
||||
if std::env::var_os("HORIZON_SHADER_PACK_TIMING").is_none()
|
||||
|| !device.features().contains(wgpu::Features::TIMESTAMP_QUERY)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let size = u64::from(CAPACITY) * 2 * 8;
|
||||
let buffer = |label, usage| {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(label),
|
||||
size,
|
||||
usage,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
};
|
||||
Some(Self {
|
||||
queries: device.create_query_set(&wgpu::QuerySetDescriptor {
|
||||
label: Some("Shader pack pass timing"),
|
||||
ty: wgpu::QueryType::Timestamp,
|
||||
count: CAPACITY * 2,
|
||||
}),
|
||||
resolve: buffer(
|
||||
"Shader pack timing resolve",
|
||||
wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
|
||||
),
|
||||
read: buffer(
|
||||
"Shader pack timing read",
|
||||
wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
),
|
||||
period_ns: queue.get_timestamp_period(),
|
||||
frame: 0,
|
||||
names: Vec::new(),
|
||||
timed: false,
|
||||
samples: Vec::new(),
|
||||
reports: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// At the start of a frame: reads the last timed frame's passes, and decides whether this
|
||||
/// one is timed.
|
||||
pub fn begin(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
|
||||
if self.timed && !self.names.is_empty() {
|
||||
self.collect(device, queue);
|
||||
}
|
||||
self.names.clear();
|
||||
self.frame += 1;
|
||||
self.timed = self.frame.is_multiple_of(EVERY);
|
||||
}
|
||||
|
||||
/// Timestamp writes for the pass `name`, in a timed frame.
|
||||
pub fn writes(&mut self, name: &str) -> Option<wgpu::RenderPassTimestampWrites<'_>> {
|
||||
let i = self.names.len() as u32;
|
||||
if !self.timed || i >= CAPACITY {
|
||||
return None;
|
||||
}
|
||||
self.names.push(name.to_owned());
|
||||
Some(wgpu::RenderPassTimestampWrites {
|
||||
query_set: &self.queries,
|
||||
beginning_of_pass_write_index: Some(2 * i),
|
||||
end_of_pass_write_index: Some(2 * i + 1),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
|
||||
// The timed frame first, then the resolve, so every timestamp is written.
|
||||
_ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let count = self.names.len() as u32 * 2;
|
||||
let bytes = u64::from(count) * 8;
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
encoder.resolve_query_set(&self.queries, 0..count, &self.resolve, 0);
|
||||
encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, bytes);
|
||||
queue.submit([encoder.finish()]);
|
||||
let slice = self.read.slice(..bytes);
|
||||
slice.map_async(wgpu::MapMode::Read, |_| {});
|
||||
_ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let Ok(data) = slice.get_mapped_range() else {
|
||||
return;
|
||||
};
|
||||
let stamps: Vec<u64> = data
|
||||
.as_chunks::<8>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|b| u64::from_le_bytes(*b))
|
||||
.collect();
|
||||
drop(data);
|
||||
self.read.unmap();
|
||||
// Passes overlap on tiled GPUs (a pass begins before the one before it ends): a pass
|
||||
// costs the time from the later of its beginning and the previous pass's end.
|
||||
let mut previous_end = 0;
|
||||
for (name, pair) in self.names.iter().zip(stamps.as_chunks::<2>().0) {
|
||||
if pair[0] == 0 || pair[1] < pair[0] {
|
||||
continue;
|
||||
}
|
||||
let from = pair[0].max(previous_end).min(pair[1]);
|
||||
previous_end = pair[1];
|
||||
let ms = (pair[1] - from) as f32 * self.period_ns / 1e6;
|
||||
match self.samples.iter_mut().find(|s| s.0 == *name) {
|
||||
Some(s) => s.1.push(ms),
|
||||
None => self.samples.push((name.clone(), vec![ms])),
|
||||
}
|
||||
}
|
||||
self.reports += 1;
|
||||
if self.reports.is_multiple_of(REPORT) {
|
||||
self.report();
|
||||
}
|
||||
}
|
||||
|
||||
fn report(&mut self) {
|
||||
let mut total = 0.0;
|
||||
let mut parts = Vec::new();
|
||||
// A pass that did not run in this window (no entities, the sky out of sight) is left out.
|
||||
for (name, v) in self.samples.iter_mut().filter(|s| !s.1.is_empty()) {
|
||||
v.sort_by(f32::total_cmp);
|
||||
let median = v[v.len() / 2];
|
||||
total += median;
|
||||
parts.push(format!("{name} {median:.3}"));
|
||||
v.clear();
|
||||
}
|
||||
log::info!(
|
||||
"shader pack GPU time per pass (median ms of {REPORT} frames): {} = {total:.3}",
|
||||
parts.join(", ")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//! Matrices follow GL's conventions (5.5): `gbufferProjection` maps view depth to clip z in
|
||||
//! [-w, w], and the depth buffers packs read hold GL window depth.
|
||||
|
||||
use glam::{Mat4, Vec3, Vec4};
|
||||
use glam::{DMat4, DVec3, Mat4, Vec3, Vec4};
|
||||
use horizon_shaders::Shadow;
|
||||
|
||||
use super::Frame;
|
||||
|
||||
@@ -23,6 +24,15 @@ pub struct PackInputs {
|
||||
pub hide_gui: bool,
|
||||
/// The brightness option, 0..1.
|
||||
pub brightness: f32,
|
||||
/// The biome at the camera (3.4): registry id, `CAT_*`, `PPT_*`, temperature, downfall.
|
||||
pub biome: i32,
|
||||
pub biome_category: i32,
|
||||
pub biome_precipitation: i32,
|
||||
pub temperature: f32,
|
||||
pub rainfall: f32,
|
||||
/// `heldItemId`, `heldItemId2` (item.properties, 5.3) and `heldBlockLightValue(2)`.
|
||||
pub held_items: [i32; 2],
|
||||
pub held_light: [i32; 2],
|
||||
}
|
||||
|
||||
/// One uniform's value: up to 16 floats or 3 integers.
|
||||
@@ -134,43 +144,129 @@ pub const NAMES: &[&str] = &[
|
||||
"heldBlockLightValue",
|
||||
"heldBlockLightValue2",
|
||||
"renderStage",
|
||||
"biome",
|
||||
"biome_category",
|
||||
"biome_precipitation",
|
||||
"temperature",
|
||||
"rainfall",
|
||||
"gbufferModelView",
|
||||
"gbufferModelViewInverse",
|
||||
"gbufferProjection",
|
||||
"gbufferProjectionInverse",
|
||||
"gbufferPreviousModelView",
|
||||
"gbufferPreviousProjection",
|
||||
"atlasSize",
|
||||
"shadowModelView",
|
||||
"shadowModelViewInverse",
|
||||
"shadowProjection",
|
||||
"shadowProjectionInverse",
|
||||
];
|
||||
|
||||
/// Values carried from frame to frame.
|
||||
pub struct FrameUniforms {
|
||||
pub values: Vec<Value>,
|
||||
/// The block atlas's size (`atlasSize`), 0 without one.
|
||||
pub atlas: [u32; 2],
|
||||
start: std::time::Instant,
|
||||
last: Option<std::time::Instant>,
|
||||
frame: u32,
|
||||
previous: Option<(Vec3, Mat4, Mat4)>,
|
||||
wetness: f32,
|
||||
eye_smooth: [f32; 2],
|
||||
/// The pack's shadow settings (7.1).
|
||||
pub shadow: Shadow,
|
||||
}
|
||||
|
||||
impl Default for FrameUniforms {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
values: Vec::new(),
|
||||
atlas: [0; 2],
|
||||
start: std::time::Instant::now(),
|
||||
last: None,
|
||||
frame: 0,
|
||||
previous: None,
|
||||
wetness: 0.0,
|
||||
eye_smooth: [0.0; 2],
|
||||
shadow: Shadow::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `(0, 100, 0)` on the frame the sky draws a body on: Y -90°, then X by its angle in degrees.
|
||||
fn body(angle: f32) -> Vec3 {
|
||||
(Mat4::from_rotation_y((-90.0f32).to_radians()) * Mat4::from_rotation_x(angle.to_radians()))
|
||||
.transform_vector3(Vec3::new(0.0, 100.0, 0.0))
|
||||
/// `(0, 100, 0)` on the frame the sky draws a body on: Y -90°, then X by its angle in degrees;
|
||||
/// `sunPathRotation` (`tilt`, degrees) then turns the path about the world's X axis (7.1, OQ-6).
|
||||
fn body(angle: f32, tilt: f32) -> Vec3 {
|
||||
(tilt_matrix(tilt)
|
||||
* Mat4::from_rotation_y((-90.0f32).to_radians())
|
||||
* Mat4::from_rotation_x(angle.to_radians()))
|
||||
.transform_vector3(Vec3::new(0.0, 100.0, 0.0))
|
||||
}
|
||||
|
||||
/// `sunPathRotation`'s turn of the sky's bodies: `tilt` degrees about the world's X axis, so a
|
||||
/// positive angle moves the noon sun toward +Z (south).
|
||||
pub fn tilt_matrix(tilt: f32) -> Mat4 {
|
||||
Mat4::from_rotation_x(tilt.to_radians())
|
||||
}
|
||||
|
||||
/// The world direction of the shadow light (7.1): the sun by day, the moon by night.
|
||||
pub fn shadow_light(frame: &Frame, shadow: &Shadow) -> Vec3 {
|
||||
let sun_angle = (frame.sky.sun_angle / 360.0 + 0.25).rem_euclid(1.0);
|
||||
let angle = if sun_angle < 0.5 {
|
||||
frame.sky.sun_angle
|
||||
} else {
|
||||
frame.sky.moon_angle
|
||||
};
|
||||
body(angle, shadow.sun_path_rotation).normalize()
|
||||
}
|
||||
|
||||
/// `shadow_camera`'s view and projection in wgpu's clip space (depth 0..1), for culling.
|
||||
pub fn shadow_culling(frame: &Frame, shadow: &Shadow) -> Mat4 {
|
||||
let (view, gl) = shadow_camera(shadow_light(frame, shadow), frame.camera, shadow);
|
||||
// GL's depth -w..w to wgpu's 0..w.
|
||||
let depth = Mat4::from_cols(
|
||||
Vec4::X,
|
||||
Vec4::Y,
|
||||
Vec4::new(0.0, 0.0, 0.5, 0.0),
|
||||
Vec4::new(0.0, 0.0, 0.5, 1.0),
|
||||
);
|
||||
depth * gl * view
|
||||
}
|
||||
|
||||
/// Distance from the snapped point to the shadow camera, toward the light: the middle of the
|
||||
/// default near and far planes (OQ-6).
|
||||
const SHADOW_EYE: f64 = 128.0;
|
||||
|
||||
/// The shadow camera (7.1; OQ-6, impl-plan.md): its view (player space to shadow view space)
|
||||
/// and GL projection. The camera looks from the light, world +Z up (+Y when the light is near
|
||||
/// Z); the point it centres moves in steps of `shadowIntervalSize` along the shadow view's
|
||||
/// own axes, and it sits `SHADOW_EYE` blocks toward the light from it. Orthographic over
|
||||
/// `shadowDistance` each side, or perspective with `shadowMapFov`.
|
||||
pub fn shadow_camera(light: Vec3, camera: DVec3, shadow: &Shadow) -> (Mat4, Mat4) {
|
||||
let light = light.as_dvec3();
|
||||
let up = if light.z.abs() > 0.99 {
|
||||
DVec3::Y
|
||||
} else {
|
||||
DVec3::Z
|
||||
};
|
||||
let rotation = DMat4::look_to_rh(DVec3::ZERO, -light, up);
|
||||
let at = rotation.transform_vector3(camera);
|
||||
let step = f64::from(shadow.interval);
|
||||
let snapped = if step > 0.0 {
|
||||
(at / step).floor() * step
|
||||
} else {
|
||||
at
|
||||
};
|
||||
let offset = at - snapped - DVec3::new(0.0, 0.0, SHADOW_EYE);
|
||||
let view = (DMat4::from_translation(offset) * rotation).as_mat4();
|
||||
let (near, far) = (shadow.near, shadow.far);
|
||||
let projection = match shadow.fov {
|
||||
Some(fov) => Mat4::perspective_rh_gl(fov.to_radians(), 1.0, near, far),
|
||||
None => {
|
||||
let d = shadow.distance;
|
||||
Mat4::orthographic_rh_gl(-d, d, -d, d, near, far)
|
||||
}
|
||||
};
|
||||
(view, projection)
|
||||
}
|
||||
|
||||
/// `value` moved toward `target` with a half-life of `half_life` seconds over `dt` (5.6).
|
||||
@@ -201,8 +297,9 @@ impl FrameUniforms {
|
||||
let to_view = |v: Vec3| view.transform_vector3(v);
|
||||
let sun_angle = (frame.sky.sun_angle / 360.0 + 0.25).rem_euclid(1.0);
|
||||
let day = sun_angle < 0.5;
|
||||
let sun = to_view(body(frame.sky.sun_angle));
|
||||
let moon = to_view(body(frame.sky.moon_angle));
|
||||
let tilt = self.shadow.sun_path_rotation;
|
||||
let sun = to_view(body(frame.sky.sun_angle, tilt));
|
||||
let moon = to_view(body(frame.sky.moon_angle, tilt));
|
||||
// Half-lives are given in ticks (7.2); smoothing runs per frame in seconds (OQ-26).
|
||||
let half_life = if inputs.rain > self.wetness {
|
||||
600.0
|
||||
@@ -214,14 +311,22 @@ impl FrameUniforms {
|
||||
for (smoothed, target) in self.eye_smooth.iter_mut().zip(eye) {
|
||||
*smoothed = smooth(*smoothed, target, 10.0 / 20.0, dt);
|
||||
}
|
||||
// Vanilla fades by the stronger of two linear fogs; a pack gets one: the pair (start
|
||||
// and end together) of the one that is complete nearer (OQ-36). Mixing the nearer start
|
||||
// of one with the nearer end of the other made fog begin at the camera on clear days.
|
||||
let (fog_color, fog_start, fog_end) = match &frame.fog {
|
||||
Some(f) => (
|
||||
[f.color[0], f.color[1], f.color[2]],
|
||||
f.environmental_start.min(f.render_distance_start),
|
||||
f.environmental_end.min(f.render_distance_end),
|
||||
),
|
||||
Some(f) => {
|
||||
let (start, end) = if f.environmental_end < f.render_distance_end {
|
||||
(f.environmental_start, f.environmental_end)
|
||||
} else {
|
||||
(f.render_distance_start, f.render_distance_end)
|
||||
};
|
||||
([f.color[0], f.color[1], f.color[2]], start, end)
|
||||
}
|
||||
None => (frame.sky.fog_color, frame.distance * 0.9, frame.distance),
|
||||
};
|
||||
let light = shadow_light(frame, &self.shadow);
|
||||
let (shadow_view, shadow_projection) = shadow_camera(light, frame.camera, &self.shadow);
|
||||
let day_time = inputs.day_time.rem_euclid(24000) as i32;
|
||||
let world_day = inputs.day_time.div_euclid(24000);
|
||||
let seconds = (now - self.start).as_secs_f32() % 3600.0;
|
||||
@@ -243,6 +348,11 @@ impl FrameUniforms {
|
||||
"worldDay" => Value::i(&[world_day as i32]),
|
||||
"moonPhase" => Value::i(&[world_day.rem_euclid(8) as i32]),
|
||||
"frameCounter" => Value::i(&[self.frame as i32]),
|
||||
"shadowModelView" => m4(shadow_view),
|
||||
"shadowModelViewInverse" => m4(shadow_view.inverse()),
|
||||
"shadowProjection" => m4(shadow_projection),
|
||||
"shadowProjectionInverse" => m4(shadow_projection.inverse()),
|
||||
"atlasSize" => Value::i(&[self.atlas[0] as i32, self.atlas[1] as i32]),
|
||||
"frameTime" => Value::f(&[dt]),
|
||||
"frameTimeCounter" => Value::f(&[seconds]),
|
||||
"viewWidth" => Value::f(&[size[0] as f32]),
|
||||
@@ -269,6 +379,11 @@ impl FrameUniforms {
|
||||
"screenBrightness" => Value::f(&[inputs.brightness]),
|
||||
"hideGUI" => Value::i(&[inputs.hide_gui as i32]),
|
||||
"eyeBrightness" => Value::i(&eye.map(|v| v as i32)),
|
||||
"biome" => Value::i(&[inputs.biome]),
|
||||
"biome_category" => Value::i(&[inputs.biome_category]),
|
||||
"biome_precipitation" => Value::i(&[inputs.biome_precipitation]),
|
||||
"temperature" => Value::f(&[inputs.temperature]),
|
||||
"rainfall" => Value::f(&[inputs.rainfall]),
|
||||
"eyeBrightnessSmooth" => Value::i(&self.eye_smooth.map(|v| v.round() as i32)),
|
||||
"gbufferModelView" => m4(view),
|
||||
"gbufferModelViewInverse" => m4(view.inverse()),
|
||||
@@ -276,8 +391,11 @@ impl FrameUniforms {
|
||||
"gbufferProjectionInverse" => m4(projection.inverse()),
|
||||
"gbufferPreviousModelView" => m4(previous_view),
|
||||
"gbufferPreviousProjection" => m4(previous_projection),
|
||||
// Held items wait for `item.properties` (5.3: 0 without the file); renderStage
|
||||
// is NONE outside gbuffers draws.
|
||||
"heldItemId" => Value::i(&[inputs.held_items[0]]),
|
||||
"heldItemId2" => Value::i(&[inputs.held_items[1]]),
|
||||
"heldBlockLightValue" => Value::i(&[inputs.held_light[0]]),
|
||||
"heldBlockLightValue2" => Value::i(&[inputs.held_light[1]]),
|
||||
// renderStage is NONE outside gbuffers draws.
|
||||
_ => Value::i(&[0]),
|
||||
}
|
||||
};
|
||||
@@ -299,6 +417,47 @@ impl FrameUniforms {
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameUniforms {
|
||||
/// Evaluates the pack's custom uniforms with this frame's values and puts them after
|
||||
/// `NAMES`' values, in `custom.uniforms()` order.
|
||||
pub fn eval_custom(&mut self, custom: &mut horizon_shaders::Custom) {
|
||||
self.values.truncate(NAMES.len());
|
||||
let values = &self.values;
|
||||
let builtin = |name: &str| {
|
||||
let v = values.get(index(name)?)?;
|
||||
let n = components(name);
|
||||
Some(match *v {
|
||||
Value::F(f) => horizon_shaders::Val::vector(&f.map(f64::from)[..n]),
|
||||
Value::I(i) => horizon_shaders::Val::vector(&i.map(f64::from)[..n.min(3)]),
|
||||
})
|
||||
};
|
||||
let dt = match index("frameTime").and_then(|i| values.get(i)) {
|
||||
Some(Value::F(f)) => f64::from(f[0]),
|
||||
_ => 0.0,
|
||||
};
|
||||
let out = custom.eval(dt, &builtin);
|
||||
self.values
|
||||
.extend(out.iter().map(|v| Value::f(&v.v.map(|x| x as f32)[..v.n])));
|
||||
}
|
||||
}
|
||||
|
||||
/// How many components the uniform `name` has (16 for a matrix).
|
||||
fn components(name: &str) -> usize {
|
||||
match name {
|
||||
"cameraPosition"
|
||||
| "previousCameraPosition"
|
||||
| "upPosition"
|
||||
| "sunPosition"
|
||||
| "moonPosition"
|
||||
| "shadowLightPosition"
|
||||
| "fogColor"
|
||||
| "skyColor" => 3,
|
||||
"eyeBrightness" | "eyeBrightnessSmooth" | "atlasSize" => 2,
|
||||
n if n.starts_with("gbuffer") || n.starts_with("shadow") && n != "shadowAngle" => 16,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The position of `name` in [`NAMES`].
|
||||
pub fn index(name: &str) -> Option<usize> {
|
||||
NAMES.iter().position(|n| *n == name)
|
||||
@@ -323,7 +482,38 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn noon_is_straight_up_and_the_sun_sets_in_the_west() {
|
||||
assert!(body(0.0).abs_diff_eq(Vec3::new(0.0, 100.0, 0.0), 1e-3));
|
||||
assert!(body(90.0).abs_diff_eq(Vec3::new(-100.0, 0.0, 0.0), 1e-3));
|
||||
assert!(body(0.0, 0.0).abs_diff_eq(Vec3::new(0.0, 100.0, 0.0), 1e-3));
|
||||
assert!(body(90.0, 0.0).abs_diff_eq(Vec3::new(-100.0, 0.0, 0.0), 1e-3));
|
||||
// sunPathRotation tilts noon toward +Z and leaves sunset on the horizon.
|
||||
assert!(body(0.0, 30.0).abs_diff_eq(Vec3::new(0.0, 86.60254, 50.0), 1e-3));
|
||||
assert!(body(90.0, 30.0).abs_diff_eq(Vec3::new(-100.0, 0.0, 0.0), 1e-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shadow_camera_looks_down_from_the_light_in_steps() {
|
||||
let shadow = Shadow::default();
|
||||
let mut camera = DVec3::new(1000.3, 70.0, -20.7);
|
||||
// Noon: the light is straight up.
|
||||
let (view, projection) = shadow_camera(Vec3::Y, camera, &shadow);
|
||||
let at = |p: Vec3| view.transform_point3(p);
|
||||
// Straight down: a block below the player is farther from the light.
|
||||
assert!(at(Vec3::new(0.0, -1.0, 0.0)).z < at(Vec3::ZERO).z);
|
||||
// The player is less than a step from the centre, 128 blocks from the light.
|
||||
let centre = at(Vec3::ZERO);
|
||||
assert!(centre.x.abs() <= 2.0 && centre.y.abs() <= 2.0, "{centre}");
|
||||
assert!((centre.z + 128.0).abs() < 1e-3, "{centre}");
|
||||
// Moving within a step keeps the world where it was in the map.
|
||||
camera.x = 1000.6;
|
||||
let (moved, _) = shadow_camera(Vec3::Y, camera, &shadow);
|
||||
let world = Vec3::new(5.0, -3.0, 9.0);
|
||||
let shift = Vec3::new(0.3, 0.0, 0.0);
|
||||
assert!(
|
||||
moved
|
||||
.transform_point3(world - shift)
|
||||
.abs_diff_eq(at(world), 1e-3)
|
||||
);
|
||||
// shadowDistance blocks reach the map's edge.
|
||||
let edge = projection.project_point3(Vec3::new(160.0, 0.0, -128.0));
|
||||
assert!((edge.x.abs() - 1.0).abs() < 1e-4, "{edge}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Rain and snow drawn by a shader pack's `gbuffers_weather` (spec 2.3): the game's weather
|
||||
//! quads as entity vertices, their UV animation applied here rather than in Horizon's weather
|
||||
//! shader, each kind textured from its own copy of its sprite so that the pack's `texture`
|
||||
//! repeats it across the column as a standalone rain or snow texture would.
|
||||
|
||||
use crate::weather::{Time, Vertex as WeatherVertex};
|
||||
|
||||
use super::Vertex;
|
||||
use super::pack_post::Weather;
|
||||
|
||||
/// What `gbuffers_weather` reads from a weather vertex: camera-relative position, the UV in
|
||||
/// repeats of the sprite, colour (with vanilla's fade) and light. Weather has no normal; the
|
||||
/// pack sees straight up.
|
||||
pub fn inputs() -> horizon_shaders::GbuffersInputs {
|
||||
let declarations =
|
||||
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\
|
||||
layout(location = 2) in uint hz_v_overlay;\nlayout(location = 3) in vec4 hz_v_color;\n\
|
||||
layout(location = 4) in uvec4 hz_v_light;\nlayout(location = 5) in vec4 hz_v_normal;\n"
|
||||
.to_owned();
|
||||
let body = " hz_Vertex = vec4(hz_v_pos, 1.0);\n \
|
||||
hz_MultiTexCoord0 = vec4(hz_v_uv, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord1 = vec4(float(hz_v_light.y), float(hz_v_light.x), 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
|
||||
hz_Color = hz_v_color;\n \
|
||||
hz_Normal = vec3(0.0, 1.0, 0.0);\n"
|
||||
.to_owned();
|
||||
let attributes = [
|
||||
("vaPosition", "hz_Vertex.xyz"),
|
||||
("vaUV0", "hz_v_uv"),
|
||||
("vaUV2", "ivec2(hz_MultiTexCoord1.xy)"),
|
||||
("vaColor", "hz_Color"),
|
||||
("vaNormal", "hz_Normal"),
|
||||
];
|
||||
horizon_shaders::GbuffersInputs {
|
||||
declarations,
|
||||
body,
|
||||
attributes: attributes
|
||||
.iter()
|
||||
.map(|&(n, v)| (n.to_owned(), v.to_owned()))
|
||||
.collect(),
|
||||
after: String::new(),
|
||||
// Vanilla's weather drops texels below 0.1, as Horizon's own weather shader does.
|
||||
alpha_test: Some(horizon_shaders::AlphaTest {
|
||||
op: ">",
|
||||
reference: 0.1,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The UV phase of `v` at `time`: `weather_phase` of entity.wgsl, on the CPU.
|
||||
pub fn phase(v: &WeatherVertex, time: Time) -> [f32; 2] {
|
||||
let [ticks, fall_ticks, partial, _] = time.values;
|
||||
let a = v.animation;
|
||||
if v.snow == 0 {
|
||||
let t = ticks + a[1] + partial;
|
||||
return [0.0, (-t / 32.0 * a[0]) % 32.0];
|
||||
}
|
||||
let t = ticks + partial;
|
||||
let du = t * 0.01 * a[2];
|
||||
let dv = t * a[3] * 0.001;
|
||||
let base = |lo: u32, hi: u32| f64::from_bits(u64::from(lo) | u64::from(hi) << 32);
|
||||
let u = (base(v.bases[0], v.bases[1]) + f64::from(du)) as f32;
|
||||
let v_base = (base(v.bases[2], v.bases[3]) + f64::from(dv)) as f32;
|
||||
[u, -(fall_ticks + partial) / 512.0 + v_base]
|
||||
}
|
||||
|
||||
/// One kind's sprite copied out of the shared atlas: the sprite's rectangle (bits) and its view.
|
||||
type Sprite = Option<([u32; 4], wgpu::TextureView)>;
|
||||
|
||||
/// The pack's weather vertices and the rain and snow sprites, kept across frames.
|
||||
pub struct PackWeather {
|
||||
vertices: wgpu::Buffer,
|
||||
capacity: usize,
|
||||
scratch: Vec<Vertex>,
|
||||
sprites: [Sprite; 2],
|
||||
/// Bumped when a sprite is copied again.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl PackWeather {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
Self {
|
||||
vertices: Self::buffer(device, 64),
|
||||
capacity: 64,
|
||||
scratch: Vec::new(),
|
||||
sprites: [None, None],
|
||||
generation: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack weather"),
|
||||
size: (capacity * std::mem::size_of::<Vertex>()) as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// This frame's rain then snow (the game emits them in that order) as entity vertices, and
|
||||
/// the sprites they read. `None` when there is none.
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
uploads: &mut super::upload::Uploads,
|
||||
atlas: &wgpu::Texture,
|
||||
weather: &[WeatherVertex],
|
||||
time: Time,
|
||||
indices: &wgpu::Buffer,
|
||||
) -> Option<Weather> {
|
||||
if weather.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let rain = weather.iter().take_while(|v| v.snow == 0).count() as u32 / 4;
|
||||
let snow = weather.len() as u32 / 4 - rain;
|
||||
for (kind, first) in [(0, weather.first()), (1, weather.get(rain as usize * 4))] {
|
||||
let Some(first) = first.filter(|v| v.snow as usize == kind) else {
|
||||
continue;
|
||||
};
|
||||
let key = first.rect.map(f32::to_bits);
|
||||
if self.sprites[kind].as_ref().is_none_or(|s| s.0 != key) {
|
||||
let view = copy_sprite(device, encoder, atlas, first.rect);
|
||||
self.sprites[kind] = Some((key, view));
|
||||
self.generation += 1;
|
||||
}
|
||||
}
|
||||
self.scratch.clear();
|
||||
self.scratch.extend(weather.iter().map(|v| {
|
||||
let [du, dv] = phase(v, time);
|
||||
Vertex {
|
||||
pos: v.pos,
|
||||
uv: [v.uv[0] + du, v.uv[1] + dv],
|
||||
layer: 0,
|
||||
color: v.color,
|
||||
light: v.light,
|
||||
normal: [0; 4],
|
||||
}
|
||||
}));
|
||||
if self.scratch.len() > self.capacity {
|
||||
self.capacity = self.scratch.len().next_power_of_two();
|
||||
self.vertices = Self::buffer(device, self.capacity);
|
||||
}
|
||||
uploads.buffer(
|
||||
encoder,
|
||||
&self.vertices,
|
||||
0,
|
||||
bytemuck::cast_slice(&self.scratch),
|
||||
);
|
||||
let view = |k: usize| self.sprites[k].as_ref().map(|s| s.1.clone());
|
||||
Some(Weather {
|
||||
vertices: self.vertices.clone(),
|
||||
indices: indices.clone(),
|
||||
quads: [0..rain, rain..rain + snow],
|
||||
sprites: [view(0), view(1)],
|
||||
generation: self.generation,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A texture holding the atlas's texels under `rect` (normalised x, y, width, height), as
|
||||
/// Horizon's weather shader reads them (`weather_texel`).
|
||||
fn copy_sprite(
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
atlas: &wgpu::Texture,
|
||||
rect: [f32; 4],
|
||||
) -> wgpu::TextureView {
|
||||
let size = [atlas.width() as f32, atlas.height() as f32];
|
||||
let origin = [0, 1].map(|i| (rect[i] * size[i]).round() as u32);
|
||||
let extent = [0, 1].map(|i| ((rect[i + 2] * size[i]).round() as u32).max(1));
|
||||
let extent = [0, 1].map(|i| {
|
||||
extent[i].min(
|
||||
[atlas.width(), atlas.height()][i]
|
||||
.saturating_sub(origin[i])
|
||||
.max(1),
|
||||
)
|
||||
});
|
||||
let size = wgpu::Extent3d {
|
||||
width: extent[0],
|
||||
height: extent[1],
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Shader pack weather sprite"),
|
||||
size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: atlas.format(),
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
encoder.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: atlas,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d {
|
||||
x: origin[0],
|
||||
y: origin[1],
|
||||
z: 0,
|
||||
},
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
size,
|
||||
);
|
||||
texture.create_view(&Default::default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::weather::Parameters;
|
||||
|
||||
/// The CPU phase matches the game's own weather columns (`Parameters::column`), which
|
||||
/// Horizon's weather shader is tested against.
|
||||
#[test]
|
||||
fn phase_matches_the_weather_columns() {
|
||||
for i in 0..512i32 {
|
||||
let x = i.wrapping_mul(45_238_971);
|
||||
let z = i.wrapping_mul(-418_711).wrapping_add(i32::MIN);
|
||||
let p = Parameters::new(x, z);
|
||||
let bases = p.snow_base.map(f64::to_bits);
|
||||
for ticks in [0, 511, 512, 131_071, 131_072, 1_000_003] {
|
||||
let partial = [0.0, 0.5, 0.999][i as usize % 3];
|
||||
for snow in [false, true] {
|
||||
let column = p.column(snow, ticks, x, -64, 320, z, 0, partial);
|
||||
let v = WeatherVertex {
|
||||
pos: [0.0; 3],
|
||||
uv: [0.0; 2],
|
||||
rect: [0.0; 4],
|
||||
animation: [
|
||||
p.rain_speed,
|
||||
p.rain_tick_offset,
|
||||
p.snow_drift[0],
|
||||
p.snow_drift[1],
|
||||
],
|
||||
bases: [
|
||||
bases[0] as u32,
|
||||
(bases[0] >> 32) as u32,
|
||||
bases[1] as u32,
|
||||
(bases[1] >> 32) as u32,
|
||||
],
|
||||
color: 0,
|
||||
light: 0,
|
||||
snow: u32::from(snow),
|
||||
};
|
||||
let [u, v] = phase(&v, Time::new(ticks, partial));
|
||||
assert_eq!(
|
||||
[u.to_bits(), v.to_bits()],
|
||||
[column.u_offset.to_bits(), column.v_offset.to_bits()],
|
||||
"x {x} z {z} ticks {ticks} snow {snow}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -385,14 +385,18 @@ impl Graphics {
|
||||
if self.workers > 0 {
|
||||
return self.workers as usize;
|
||||
}
|
||||
// The pool never takes every core. The render thread and the
|
||||
// integrated server thread (single player runs on its own server
|
||||
// thread by default) each need one, and a pool that fills every core
|
||||
// starves them: the frame rate collapses to single digits while the
|
||||
// workers saturate the CPU and its memory bandwidth.
|
||||
// Vanilla's count (Util.maxAllowedExecutorThreads: every core but
|
||||
// one). The pool never takes every core: a pool that fills them all
|
||||
// starves the render and server threads, and the frame rate collapses
|
||||
// while the workers saturate the CPU and its memory bandwidth. One
|
||||
// core left is enough with the workers behind those two threads
|
||||
// (horizon_threads: niced on Linux; on macOS and Windows the server
|
||||
// and render threads are raised above four cores, where vanilla
|
||||
// raises its server thread). Leaving two idled a core of a 4-thread
|
||||
// laptop while a world loaded: a teleport there took ~15% longer.
|
||||
let auto = std::thread::available_parallelism()
|
||||
.map_or(2, |n| n.get())
|
||||
.saturating_sub(2)
|
||||
.saturating_sub(1)
|
||||
.max(1);
|
||||
if self.battery { auto.div_ceil(2) } else { auto }
|
||||
}
|
||||
@@ -555,11 +559,11 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_workers_leave_cores_for_the_render_and_server_threads() {
|
||||
fn automatic_workers_leave_a_core_as_vanilla_does() {
|
||||
let g = Graphics::default();
|
||||
assert_eq!(g.workers, 0);
|
||||
let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
|
||||
assert_eq!(g.worker_threads(), cores.saturating_sub(2).max(1));
|
||||
assert_eq!(g.worker_threads(), cores.saturating_sub(1).max(1));
|
||||
// A manual count is the player's own choice, kept as asked.
|
||||
let manual = Graphics { workers: 3, ..g };
|
||||
assert_eq!(manual.worker_threads(), 3);
|
||||
|
||||
@@ -261,11 +261,17 @@ impl PlayerHealth {
|
||||
self.hurt_animation_time = 10;
|
||||
}
|
||||
/// `LocalPlayer.hurtTo` with `flashOnSetHealth`: a drop below the current
|
||||
/// health starts the hurt animation.
|
||||
/// health starts the hurt animation; `damageCooldownTime` (20 on a drop,
|
||||
/// 10 on a gain) is what lets `Hud.extractPlayerHealth` blink the hearts.
|
||||
pub fn flash_health_change(&mut self, health: f32) {
|
||||
let damage = self.health() - health;
|
||||
if damage > 0.0 {
|
||||
if damage <= 0.0 {
|
||||
if damage < 0.0 {
|
||||
self.hurt.cooldown = 10;
|
||||
}
|
||||
} else {
|
||||
self.hurt.last_hurt = damage;
|
||||
self.hurt.cooldown = 20;
|
||||
self.animate_hurt();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -851,6 +851,12 @@ impl HudBatch {
|
||||
r.v1 = cv;
|
||||
self.rect_uv(x, y, w, h, r, color);
|
||||
}
|
||||
/// Any four-cornered shape in one colour, corners in order round it.
|
||||
pub fn fill_quad(&mut self, atlas: &HudAtlas, corners: [[f32; 2]; 4], color: u32) {
|
||||
let w = atlas.white;
|
||||
let uv = [(w.u0 + w.u1) / 2.0, (w.v0 + w.v1) / 2.0];
|
||||
self.quad(corners, [uv; 4], color);
|
||||
}
|
||||
/// GuiGraphics.fillGradient: `top` to `bottom`, down the rectangle.
|
||||
pub fn fill_gradient(
|
||||
&mut self,
|
||||
|
||||
@@ -937,6 +937,20 @@ pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
|
||||
match entity {
|
||||
BlockEntity::Sign(sign) => Some(Tag::compound(sign.encode())),
|
||||
BlockEntity::Spawner(s) => Some(s.update_tag()),
|
||||
// SkullBlockEntity: the profile is the whole reason a head differs.
|
||||
BlockEntity::Skull(s) => {
|
||||
let mut entries = Vec::new();
|
||||
if let Some(profile) = &s.profile {
|
||||
entries.push(("profile", profile.clone()));
|
||||
}
|
||||
if let Some(sound) = &s.note_block_sound {
|
||||
entries.push(("note_block_sound", Tag::String(sound.as_str().into())));
|
||||
}
|
||||
if let Some(name) = &s.custom_name {
|
||||
entries.push(("custom_name", name.clone()));
|
||||
}
|
||||
Some(Tag::compound(entries))
|
||||
}
|
||||
BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None,
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -78,6 +78,17 @@ impl Hub {
|
||||
);
|
||||
}
|
||||
|
||||
/// `ServerLevel.globalLevelEvent`: the packet with its global flag, for
|
||||
/// every player on the server (`PlayerList.broadcastAll`).
|
||||
pub fn global_level_event(&self, kind: i32, pos: [i32; 3], data: i32) {
|
||||
self.broadcast(&C::LevelEvent(play::LevelEvent {
|
||||
kind,
|
||||
pos,
|
||||
data,
|
||||
global: true,
|
||||
}));
|
||||
}
|
||||
|
||||
/// ClientboundBlockEventPacket (`PlayerList.broadcast` within 64 blocks).
|
||||
pub fn block_event(&self, pos: [i32; 3], b0: i32, b1: i32, state: u32) {
|
||||
let block = self
|
||||
|
||||
@@ -54,6 +54,8 @@ pub mod datapack;
|
||||
pub mod debug_chart;
|
||||
pub mod debug_keys;
|
||||
pub mod debug_overlay;
|
||||
pub mod dialog;
|
||||
pub mod dialog_screen;
|
||||
pub mod discord_presence;
|
||||
pub mod dynamic_light;
|
||||
pub mod effects;
|
||||
@@ -146,6 +148,7 @@ pub mod player_sync;
|
||||
pub mod poi_sections;
|
||||
pub mod portal_sections;
|
||||
pub mod pose;
|
||||
pub mod pregen;
|
||||
pub mod projectiles;
|
||||
pub mod raid;
|
||||
pub mod random_sequences;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! behaviour, models, animations and sounds.
|
||||
pub mod ai;
|
||||
pub mod allay;
|
||||
pub mod ambient;
|
||||
pub mod anim;
|
||||
pub mod animal_brain;
|
||||
pub mod aquatic;
|
||||
@@ -1646,6 +1647,11 @@ impl Mob {
|
||||
pub fn species(&self) -> Species {
|
||||
self.kind.species
|
||||
}
|
||||
/// `Mob.getMainArm`: the left arm when the mob is left-handed, a player's
|
||||
/// `mainHand` option for a player mob.
|
||||
pub fn main_arm_left(&self) -> bool {
|
||||
self.extra.main_hand_left || self.extra.left_handed
|
||||
}
|
||||
/// The player hit this mob (melee): LivingEntity.hurt with knockback.
|
||||
pub fn hurt(
|
||||
&mut self,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
//! What a client's copy of a mob makes on its own, in the
|
||||
//! `level().isClientSide()` branches of `aiStep`: nothing of it reaches the
|
||||
//! server or goes over the network, so the window's game runs it, whether it
|
||||
//! simulates the world (in-frame) or follows a server.
|
||||
use super::{Mob, MobEvent, Species};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
/// `Enderman.aiStep`, `Endermite.aiStep` and `Blaze.aiStep` on a client:
|
||||
/// two portal particles a tick around endermen and endermites; two large
|
||||
/// smoke particles a tick around blazes and, one tick in 24, their burn.
|
||||
pub fn client_ai_step(m: &mut Mob, out: &mut Vec<MobEvent>) {
|
||||
let species = m.species();
|
||||
if !matches!(
|
||||
species,
|
||||
Species::Enderman | Species::Endermite | Species::Blaze
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
|
||||
let p = m.position;
|
||||
if species == Species::Blaze && m.random.next_int_bound(24).unwrap_or(1) == 0 && !m.silent {
|
||||
let volume = 1.0 + m.random.next_float();
|
||||
let pitch = m.random.next_float() * 0.7 + 0.3;
|
||||
out.push(MobEvent::LocalSound(
|
||||
"entity.blaze.burn",
|
||||
[p.x + 0.5, p.y + 0.5, p.z + 0.5],
|
||||
volume,
|
||||
pitch,
|
||||
));
|
||||
}
|
||||
for _ in 0..2 {
|
||||
// Entity.getRandomX(0.5), getRandomY(), getRandomZ(0.5).
|
||||
let r = &mut m.random;
|
||||
let x = p.x + w * (2.0 * r.next_double() - 1.0) * 0.5;
|
||||
let y = p.y + h * r.next_double();
|
||||
let z = p.z + w * (2.0 * r.next_double() - 1.0) * 0.5;
|
||||
let (kind, at, velocity) = if species == Species::Blaze {
|
||||
("large_smoke", [x, y, z], [0.0; 3])
|
||||
} else {
|
||||
// The enderman's are a quarter block lower.
|
||||
let y = if species == Species::Enderman {
|
||||
y - 0.25
|
||||
} else {
|
||||
y
|
||||
};
|
||||
let velocity = [
|
||||
(r.next_double() - 0.5) * 2.0,
|
||||
-r.next_double(),
|
||||
(r.next_double() - 0.5) * 2.0,
|
||||
];
|
||||
("portal", [x, y, z], velocity)
|
||||
};
|
||||
out.push(MobEvent::ParticleAt { kind, at, velocity });
|
||||
}
|
||||
}
|
||||
@@ -642,7 +642,7 @@ pub fn setup(
|
||||
} else {
|
||||
ArmPose::Empty
|
||||
};
|
||||
let mut h = if m.extra.main_hand_left {
|
||||
let mut h = if m.main_arm_left() {
|
||||
Hum::new(ArmPose::Empty, main)
|
||||
} else {
|
||||
Hum::new(main, ArmPose::Empty)
|
||||
@@ -693,7 +693,7 @@ pub fn setup(
|
||||
} else {
|
||||
ArmPose::Empty
|
||||
};
|
||||
let mut h = if m.extra.main_hand_left {
|
||||
let mut h = if m.main_arm_left() {
|
||||
Hum::new(off, pose)
|
||||
} else {
|
||||
Hum::new(pose, off)
|
||||
|
||||
@@ -69,18 +69,10 @@ pub fn register(m: &mut Mob) {
|
||||
}
|
||||
/// Chicken.aiStep: wing flapping, slowed falling and laying eggs.
|
||||
pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let a = &mut m.anim;
|
||||
a.flap_o = a.flap;
|
||||
a.flap_speed_o = a.flap_speed;
|
||||
a.flap_speed = (a.flap_speed + if m.on_ground { -1.0 } else { 4.0 } * 0.3).clamp(0.0, 1.0);
|
||||
if !m.on_ground && a.flapping < 1.0 {
|
||||
a.flapping = 1.0;
|
||||
}
|
||||
a.flapping *= 0.9;
|
||||
chicken_flap(m);
|
||||
if !m.on_ground && m.velocity.y < 0.0 {
|
||||
m.velocity.y *= 0.6;
|
||||
}
|
||||
a.flap += a.flapping * 2.0;
|
||||
if m.alive() && !m.is_baby() && !m.extra.jockey {
|
||||
m.extra.egg_time -= 1;
|
||||
if m.extra.egg_time <= 0 {
|
||||
@@ -95,6 +87,21 @@ pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Chicken.aiStep's wings: `flapSpeed` rises in the air and falls on the
|
||||
/// ground, `flapping` restarts at 1 in the air and decays, and `flap` turns
|
||||
/// by it. It runs on a client too, for the chickens it only displays (the
|
||||
/// falling slowdown and the eggs are the server's).
|
||||
pub fn chicken_flap(m: &mut Mob) {
|
||||
let a = &mut m.anim;
|
||||
a.flap_o = a.flap;
|
||||
a.flap_speed_o = a.flap_speed;
|
||||
a.flap_speed = (a.flap_speed + if m.on_ground { -1.0 } else { 4.0 } * 0.3).clamp(0.0, 1.0);
|
||||
if !m.on_ground && a.flapping < 1.0 {
|
||||
a.flapping = 1.0;
|
||||
}
|
||||
a.flapping *= 0.9;
|
||||
a.flap += a.flapping * 2.0;
|
||||
}
|
||||
/// Farm animal climate from the biome tags (`spawns_warm/cold_variant_farm_animals`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Climate {
|
||||
@@ -125,3 +132,39 @@ pub fn sheep_color(climate: Climate, random: &mut impl RandomSource) -> u8 {
|
||||
6
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_core::geometry::Vec3;
|
||||
|
||||
/// `chicken_flap` reads only the ground flag: any mob type will do.
|
||||
fn chicken() -> Mob {
|
||||
Mob::new(1, crate::mobs::sensor_scan_tests::kind(), Vec3::ZERO, 0.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_falling_chicken_flaps_and_a_landed_one_folds_its_wings() {
|
||||
let mut m = chicken();
|
||||
m.on_ground = true;
|
||||
chicken_flap(&mut m);
|
||||
assert_eq!(m.anim.flap_speed, 0.0);
|
||||
assert_eq!(m.anim.flap, 0.0);
|
||||
// In the air flapSpeed rises by 1.2 (clamped to 1), flapping restarts
|
||||
// at 1 and decays by 0.9, and flap turns by twice flapping.
|
||||
m.on_ground = false;
|
||||
chicken_flap(&mut m);
|
||||
assert_eq!(m.anim.flap_speed, 1.0);
|
||||
assert_eq!(m.anim.flapping, 0.9);
|
||||
assert_eq!(m.anim.flap, 1.8);
|
||||
chicken_flap(&mut m);
|
||||
assert_eq!(m.anim.flap_o, 1.8);
|
||||
assert_eq!(m.anim.flap_speed_o, 1.0);
|
||||
assert_eq!(m.anim.flap, 3.6);
|
||||
// Landed, flapSpeed falls by 0.3 a tick and flapping decays.
|
||||
m.on_ground = true;
|
||||
chicken_flap(&mut m);
|
||||
assert!((m.anim.flap_speed - 0.7).abs() < 1.0e-6);
|
||||
assert!((m.anim.flapping - 0.81).abs() < 1.0e-6);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,6 +198,15 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.extra.leash_spin = 0.0;
|
||||
return;
|
||||
};
|
||||
// Leashable.tickLeash: a dying entity cannot interact with the level.
|
||||
if !m.alive() {
|
||||
events.push(MobEvent::LeashBreak {
|
||||
mob: m.id,
|
||||
drop: true,
|
||||
sound: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let Some(state) = holder_state(w, holder) else {
|
||||
// The holder is gone: the lead drops.
|
||||
if !matches!(holder, Holder::Player) {
|
||||
|
||||
@@ -621,8 +621,10 @@ impl BowAttack {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `LivingEntity.isHolding(Items.BOW)`: the bow can sit in either hand.
|
||||
fn holding_bow(m: &Mob) -> bool {
|
||||
m.extra.main_hand.as_deref() == Some("minecraft:bow")
|
||||
|| m.extra.off_hand.as_deref() == Some("minecraft:bow")
|
||||
}
|
||||
impl Goal for BowAttack {
|
||||
goal_clone!();
|
||||
@@ -715,7 +717,10 @@ impl Goal for BowAttack {
|
||||
} else {
|
||||
self.attack_time -= 1;
|
||||
if self.attack_time <= 0 && self.see_time >= -60 {
|
||||
// mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand):
|
||||
// the off hand when the main one doesn't hold the bow.
|
||||
m.extra.using_item = 1;
|
||||
m.extra.using_off_hand = m.extra.main_hand.as_deref() != Some("minecraft:bow");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3076,8 +3076,13 @@ mod tests {
|
||||
if client_side {
|
||||
w.player.health.flash_health_change(20.0);
|
||||
assert_eq!(w.player.health.hurt_animation_time, 0);
|
||||
assert_eq!(w.player.health.hurt.cooldown, 0);
|
||||
w.player.health.flash_health_change(12.0);
|
||||
assert_eq!(w.player.health.hurt_animation_time, 10);
|
||||
// LocalPlayer.hurtTo's damageCooldownTime: the HUD's hearts blink.
|
||||
assert_eq!(w.player.health.hurt.cooldown, 20);
|
||||
w.player.health.flash_health_change(25.0);
|
||||
assert_eq!(w.player.health.hurt.cooldown, 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,10 @@ pub enum Event {
|
||||
PackPush(cfg::ResourcePackPush),
|
||||
/// ClientboundResourcePackPopPacket: one pack, or every pack.
|
||||
PackPop(Option<u128>),
|
||||
/// `show_dialog` in configuration: the dialog itself.
|
||||
ShowDialog(horizon_world::nbt::Tag),
|
||||
/// `clear_dialog` in configuration.
|
||||
ClearDialog,
|
||||
/// `ClientboundTransferPacket`: the server sent us to another address.
|
||||
/// The connection ends right after; the game reconnects there with the
|
||||
/// stored cookies.
|
||||
@@ -234,6 +238,25 @@ impl Session {
|
||||
w.shutdown();
|
||||
}
|
||||
}
|
||||
/// ServerboundCustomClickActionPacket (a dialog's answer), in whichever
|
||||
/// phase the connection is.
|
||||
pub fn send_custom_click(&self, id: &str, payload: Option<horizon_world::nbt::Tag>) {
|
||||
let click = cfg::CustomClickAction {
|
||||
id: id.to_owned(),
|
||||
payload,
|
||||
};
|
||||
let mut writer = self.writer.lock().unwrap();
|
||||
let body = if self.configuring.load(Ordering::Relaxed) {
|
||||
cfg::Serverbound::CustomClickAction(click).encode()
|
||||
} else {
|
||||
play::Serverbound::CustomClickAction(click).encode()
|
||||
};
|
||||
if let Some(w) = writer.as_mut()
|
||||
&& w.send(&body).is_err()
|
||||
{
|
||||
w.shutdown();
|
||||
}
|
||||
}
|
||||
pub fn disconnect(&mut self) {
|
||||
if let Some(w) = self.writer.lock().unwrap().take() {
|
||||
w.shutdown();
|
||||
@@ -602,6 +625,13 @@ fn configure(
|
||||
cfg::Clientbound::ResourcePackPop(p) => {
|
||||
let _ = send.send(Event::PackPop(p.id));
|
||||
}
|
||||
// The game shows it; the answer goes back from there.
|
||||
cfg::Clientbound::ShowDialog(d) => {
|
||||
let _ = send.send(Event::ShowDialog(d.dialog));
|
||||
}
|
||||
cfg::Clientbound::ClearDialog(_) => {
|
||||
let _ = send.send(Event::ClearDialog);
|
||||
}
|
||||
cfg::Clientbound::CookieRequest(q) => {
|
||||
let payload = cookies.lock().unwrap().get(&q.key).cloned();
|
||||
reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse {
|
||||
|
||||
@@ -3403,9 +3403,6 @@ mod tests {
|
||||
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;
|
||||
|
||||
@@ -8,7 +8,8 @@ use std::io::Read;
|
||||
use std::{collections::BTreeSet, fs, io, path::Path, path::PathBuf};
|
||||
|
||||
// Bump when overlay/merge semantics change. Markers are disposable cache data.
|
||||
const VERSION: u32 = 3;
|
||||
// Version 3 could omit untouched vanilla directories on Windows (#1649, #1688).
|
||||
const VERSION: u32 = 4;
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub(super) struct Dependencies {
|
||||
@@ -421,6 +422,73 @@ mod tests {
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(unix))]
|
||||
fn texture_only_packs_rebuild_incomplete_windows_v3_overlays() {
|
||||
let f = Fixture::new();
|
||||
let blockstate = "assets/minecraft/blockstates/oak_stairs.json";
|
||||
let model = "assets/minecraft/models/block/oak_stairs.json";
|
||||
let texture = "assets/minecraft/textures/block/stone.png";
|
||||
let font = "assets/minecraft/textures/font/ascii.png";
|
||||
f.write(&format!("vanilla/{blockstate}"), br#"{"variants":{}}"#);
|
||||
f.write(&format!("vanilla/{model}"), br#"{"elements":[]}"#);
|
||||
f.write(&format!("vanilla/{texture}"), b"vanilla texture");
|
||||
f.write(&format!("vanilla/{font}"), b"vanilla font");
|
||||
let folder = f.dir_pack("textures");
|
||||
f.write(&format!("textures/{texture}"), b"pack texture");
|
||||
f.write(
|
||||
"textures.zip",
|
||||
&archive(
|
||||
&[
|
||||
(
|
||||
"pack.mcmeta",
|
||||
br#"{"pack":{"description":"test","pack_format":97}}"#.to_vec(),
|
||||
),
|
||||
(texture, b"pack texture".to_vec()),
|
||||
],
|
||||
true,
|
||||
),
|
||||
);
|
||||
let zip = packs::pack(
|
||||
"zip".into(),
|
||||
Text::empty(),
|
||||
Source::Zip(f.0.join("textures.zip")),
|
||||
)
|
||||
.unwrap();
|
||||
let vanilla = f.0.join("vanilla");
|
||||
for pack in [folder, zip] {
|
||||
let out = f.0.join(format!("cached-{}", pack.id));
|
||||
let selected = std::slice::from_ref(&pack);
|
||||
packs::build_overlay(&vanilla, selected, &out).unwrap();
|
||||
let check = || {
|
||||
for name in [blockstate, model, font] {
|
||||
assert_eq!(
|
||||
fs::read(out.join(name)).unwrap(),
|
||||
fs::read(vanilla.join(name)).unwrap()
|
||||
);
|
||||
}
|
||||
assert_eq!(fs::read(out.join(texture)).unwrap(), b"pack texture");
|
||||
};
|
||||
check();
|
||||
// Before #1688, Windows silently omitted untouched directories.
|
||||
// A v3 marker still validates because it checks only source files.
|
||||
let marker_path = marker_path(&out);
|
||||
let mut marker: Marker =
|
||||
serde_json::from_slice(&fs::read(&marker_path).unwrap()).unwrap();
|
||||
marker.version = 3;
|
||||
for dir in ["blockstates", "models", "textures/font"] {
|
||||
fs::remove_dir_all(out.join("assets/minecraft").join(dir)).unwrap();
|
||||
}
|
||||
fs::write(&marker_path, serde_json::to_vec(&marker).unwrap()).unwrap();
|
||||
assert!(marker.dependencies.valid());
|
||||
packs::build_overlay(&vanilla, selected, &out).unwrap();
|
||||
check();
|
||||
// The repaired overlay also remains complete on a cache hit.
|
||||
packs::build_overlay(&vanilla, selected, &out).unwrap();
|
||||
check();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_inputs_config_and_owned_output_recovery() {
|
||||
let f = Fixture::new();
|
||||
@@ -456,7 +524,10 @@ mod tests {
|
||||
let path = f.0.join(format!("high/{resource}"));
|
||||
let original_time = fs::metadata(&path).unwrap().modified().unwrap();
|
||||
fs::write(&path, br#"{"p":"c"}"#).unwrap();
|
||||
fs::File::open(path)
|
||||
// Windows requires a writable handle to restore the timestamp.
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
.set_times(fs::FileTimes::new().set_modified(original_time))
|
||||
.unwrap();
|
||||
|
||||
@@ -1212,10 +1212,7 @@ impl ParticleEngine {
|
||||
requested: None,
|
||||
names: Vec::new(),
|
||||
rects: Vec::new(),
|
||||
atlas: atlas
|
||||
.iter()
|
||||
.map(|(name, &rect)| (name.clone(), (rect, translucent.contains(name))))
|
||||
.collect(),
|
||||
atlas: HashMap::new(),
|
||||
sets: HashMap::new(),
|
||||
set_sprites: Vec::new(),
|
||||
emitters: Vec::new(),
|
||||
@@ -1225,6 +1222,34 @@ impl ParticleEngine {
|
||||
made: Default::default(),
|
||||
item_sprites: HashMap::new(),
|
||||
};
|
||||
engine.reload(root, atlas, translucent);
|
||||
engine
|
||||
}
|
||||
/// `onResourceManagerReload`: sprite rects and sets come from the
|
||||
/// reloaded atlas and pack; a live particle keeps drawing its sprite by
|
||||
/// name or index.
|
||||
pub fn reload(
|
||||
&mut self,
|
||||
root: &Path,
|
||||
atlas: &HashMap<String, Rect>,
|
||||
translucent: &HashSet<String>,
|
||||
) {
|
||||
self.atlas = atlas
|
||||
.iter()
|
||||
.map(|(name, &rect)| (name.clone(), (rect, translucent.contains(name))))
|
||||
.collect();
|
||||
self.rects = self
|
||||
.names
|
||||
.iter()
|
||||
.map(|name| self.atlas.get(name).map(|&(rect, _)| rect))
|
||||
.collect();
|
||||
self.sets.clear();
|
||||
self.set_sprites.clear();
|
||||
self.item_sprites.clear();
|
||||
self.load_sprites(root);
|
||||
}
|
||||
/// The sprite sets of every `particles/*.json` under `root`.
|
||||
fn load_sprites(&mut self, root: &Path) {
|
||||
let dir = root.join("assets/minecraft/particles");
|
||||
for &ty in ParticleType::ALL {
|
||||
let Ok(bytes) = std::fs::read(dir.join(format!("{}.json", ty.name()))) else {
|
||||
@@ -1239,18 +1264,16 @@ impl ParticleEngine {
|
||||
a.iter()
|
||||
.filter_map(|t| t.as_str())
|
||||
.map(|t| {
|
||||
engine
|
||||
.intern(&format!("particle/{}", t.trim_start_matches("minecraft:")))
|
||||
self.intern(&format!("particle/{}", t.trim_start_matches("minecraft:")))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if !sprites.is_empty() {
|
||||
engine.sets.insert(ty, engine.set_sprites.len() as u32);
|
||||
engine.set_sprites.push(sprites);
|
||||
self.sets.insert(ty, self.set_sprites.len() as u32);
|
||||
self.set_sprites.push(sprites);
|
||||
}
|
||||
}
|
||||
engine
|
||||
}
|
||||
fn intern(&mut self, name: &str) -> u32 {
|
||||
if let Some(i) = self.names.iter().position(|n| n == name) {
|
||||
@@ -1601,7 +1624,10 @@ impl ParticleEngine {
|
||||
return;
|
||||
}
|
||||
if let Some(set) = p.set {
|
||||
let sprites = &self.set_sprites[set as usize];
|
||||
// A sprite set's index can outlive the reload that rebuilt them.
|
||||
let Some(sprites) = self.set_sprites.get(set as usize) else {
|
||||
return;
|
||||
};
|
||||
let lifetime = p.lifetime.max(1);
|
||||
let index = (p.age.max(0) as i64 * (sprites.len() as i64 - 1) / i64::from(lifetime))
|
||||
.clamp(0, sprites.len() as i64 - 1);
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
//! Pregeneration (`/pregen`): every chunk of a square or a circle generated,
|
||||
//! lit and saved ahead of the players. The area is cut into strips of columns
|
||||
//! and each strip is swept north to south by a [`Band`] a few rows deep:
|
||||
//! streaming generates the band's chunks and keeps them until they are lit,
|
||||
//! then the band moves on and the rows behind it unload and are saved, so
|
||||
//! memory stays bounded whatever the radius.
|
||||
use crate::streaming::Band;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Shape {
|
||||
Square,
|
||||
Circle,
|
||||
}
|
||||
|
||||
/// The widest strip, in chunks. Strips are swept one after another; the few
|
||||
/// columns along the edge between two are generated with both.
|
||||
const STRIP_WIDTH: i32 = 256;
|
||||
/// How many chunks a band holds at least: enough to keep every worker busy
|
||||
/// while the rows before it finish.
|
||||
const BAND_CHUNKS: i32 = 1024;
|
||||
|
||||
pub struct Pregen {
|
||||
/// The centre chunk and the radius in chunks.
|
||||
pub center: (i32, i32),
|
||||
pub radius: i32,
|
||||
pub shape: Shape,
|
||||
/// The strips' columns, west to east.
|
||||
strips: Vec<(i32, i32)>,
|
||||
strip: usize,
|
||||
/// The band's first row: every row of the strip before it is done.
|
||||
row: i32,
|
||||
/// Chunks of the area lit so far, and in all.
|
||||
pub done: u64,
|
||||
pub total: u64,
|
||||
}
|
||||
|
||||
impl Pregen {
|
||||
pub fn new(center: (i32, i32), radius: i32, shape: Shape) -> Self {
|
||||
let radius = radius.max(0);
|
||||
let (x0, width) = (center.0 - radius, 2 * radius + 1);
|
||||
let count = (width + STRIP_WIDTH - 1) / STRIP_WIDTH;
|
||||
// The columns `i * width / count` on, in i64: the product overflows
|
||||
// for a radius of a few hundred thousand chunks.
|
||||
let edge = |i: i32| x0 + (i64::from(width) * i64::from(i) / i64::from(count)) as i32;
|
||||
let strips = (0..count).map(|i| (edge(i), edge(i + 1) - 1)).collect();
|
||||
let mut pregen = Self {
|
||||
center,
|
||||
radius,
|
||||
shape,
|
||||
strips,
|
||||
strip: 0,
|
||||
row: 0,
|
||||
done: 0,
|
||||
total: 0,
|
||||
};
|
||||
pregen.total = (center.1 - radius..=center.1 + radius)
|
||||
.map(|z| pregen.row_chunks(x0, x0 + width - 1, z))
|
||||
.sum();
|
||||
pregen.row = pregen.rows().map_or(0, |r| r.0);
|
||||
pregen
|
||||
}
|
||||
|
||||
/// How far from the centre column the area reaches at `d` chunks from
|
||||
/// the centre row (or, the same, from the centre column), if it does.
|
||||
fn half_width(&self, d: i32) -> Option<i32> {
|
||||
let (r, d) = (i64::from(self.radius), i64::from(d));
|
||||
match self.shape {
|
||||
Shape::Square => (d.abs() <= r).then_some(self.radius),
|
||||
Shape::Circle => (d * d <= r * r).then(|| (r * r - d * d).isqrt() as i32),
|
||||
}
|
||||
}
|
||||
|
||||
fn contains(&self, x: i32, z: i32) -> bool {
|
||||
self.half_width(z - self.center.1)
|
||||
.is_some_and(|h| (x - self.center.0).abs() <= h)
|
||||
}
|
||||
|
||||
/// The area's chunks in columns `x0..=x1` of row `z`.
|
||||
fn row_chunks(&self, x0: i32, x1: i32, z: i32) -> u64 {
|
||||
self.half_width(z - self.center.1).map_or(0, |h| {
|
||||
let (lo, hi) = (x0.max(self.center.0 - h), x1.min(self.center.0 + h));
|
||||
(i64::from(hi) - i64::from(lo) + 1).max(0) as u64
|
||||
})
|
||||
}
|
||||
|
||||
/// The first and last rows of the current strip that hold chunks of the
|
||||
/// area.
|
||||
fn rows(&self) -> Option<(i32, i32)> {
|
||||
let &(x0, x1) = self.strips.get(self.strip)?;
|
||||
let nearest = (x0 - self.center.0).max(self.center.0 - x1).max(0);
|
||||
let h = self.half_width(nearest)?;
|
||||
Some((self.center.1 - h, self.center.1 + h))
|
||||
}
|
||||
|
||||
/// The band streaming should hold now; none once every strip is done.
|
||||
pub fn band(&self) -> Option<Band> {
|
||||
let &(x0, x1) = self.strips.get(self.strip)?;
|
||||
let (_, last) = self.rows()?;
|
||||
let rows = (BAND_CHUNKS + (x1 - x0)) / (x1 - x0 + 1);
|
||||
Some(Band {
|
||||
x0,
|
||||
x1,
|
||||
z0: self.row,
|
||||
z1: (self.row + rows - 1).min(last),
|
||||
circle: (self.shape == Shape::Circle).then_some((self.center, self.radius)),
|
||||
})
|
||||
}
|
||||
|
||||
/// Move past the band's first rows once all their chunks are `lit`.
|
||||
/// Returns whether the band moved.
|
||||
pub fn advance(&mut self, lit: impl Fn(i32, i32) -> bool) -> bool {
|
||||
let mut moved = false;
|
||||
while let (Some(&(x0, x1)), Some((_, last))) = (self.strips.get(self.strip), self.rows()) {
|
||||
let z = self.row;
|
||||
if !(x0..=x1).all(|x| !self.contains(x, z) || lit(x, z)) {
|
||||
break;
|
||||
}
|
||||
self.done += self.row_chunks(x0, x1, z);
|
||||
self.row += 1;
|
||||
if self.row > last {
|
||||
self.strip += 1;
|
||||
self.row = self.rows().map_or(self.row, |r| r.0);
|
||||
}
|
||||
moved = true;
|
||||
}
|
||||
moved
|
||||
}
|
||||
|
||||
/// The chunks of the band's first row, which it waits for.
|
||||
pub fn first_row(&self) -> Vec<(i32, i32)> {
|
||||
let Some(&(x0, x1)) = self.strips.get(self.strip) else {
|
||||
return Vec::new();
|
||||
};
|
||||
(x0..=x1)
|
||||
.filter(|&x| self.contains(x, self.row))
|
||||
.map(|x| (x, self.row))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn finished(&self) -> bool {
|
||||
self.strip >= self.strips.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sweeps_every_chunk_of_the_area_once() {
|
||||
for shape in [Shape::Square, Shape::Circle] {
|
||||
for (center, radius) in [((0, 0), 0), ((3, -7), 5), ((-40, 12), 130), ((0, 0), 300)] {
|
||||
let mut p = Pregen::new(center, radius, shape);
|
||||
let r = i64::from(radius);
|
||||
let area = (-radius..=radius)
|
||||
.flat_map(|dz| (-radius..=radius).map(move |dx| (dx, dz)))
|
||||
.filter(|&(dx, dz)| {
|
||||
shape == Shape::Square
|
||||
|| i64::from(dx).pow(2) + i64::from(dz).pow(2) <= r * r
|
||||
})
|
||||
.count() as u64;
|
||||
assert_eq!(p.total, area, "{shape:?} {radius}");
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
while !p.finished() {
|
||||
let band = p.band().unwrap();
|
||||
assert!(band.z0 <= band.z1);
|
||||
let row = p.first_row();
|
||||
for &(x, z) in &row {
|
||||
assert!(seen.insert((x, z)), "{x} {z} twice");
|
||||
}
|
||||
assert!(
|
||||
p.advance(|x, z| z == band.z0 && row.contains(&(x, z))) || row.is_empty()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
(p.done, seen.len() as u64),
|
||||
(area, area),
|
||||
"{shape:?} {radius}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_area_is_planned_at_once() {
|
||||
let started = std::time::Instant::now();
|
||||
let p = Pregen::new((0, 0), 30_000_000 >> 4, Shape::Circle);
|
||||
assert!(p.total > 11_000_000_000_000);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
@@ -553,6 +553,17 @@ pub fn encode_block_entity(
|
||||
entries.push(("creaking", uuid_tag(uuid)));
|
||||
}
|
||||
}
|
||||
BlockEntity::Skull(s) => {
|
||||
if let Some(profile) = &s.profile {
|
||||
entries.push(("profile", profile.clone()));
|
||||
}
|
||||
if let Some(sound) = &s.note_block_sound {
|
||||
entries.push(("note_block_sound", string(sound)));
|
||||
}
|
||||
if let Some(name) = &s.custom_name {
|
||||
entries.push(("custom_name", name.clone()));
|
||||
}
|
||||
}
|
||||
BlockEntity::Spawner(s) => entries.extend(s.save()),
|
||||
BlockEntity::TrialSpawner(s) => entries.extend(s.save()),
|
||||
BlockEntity::Vault(v) => entries.extend(v.save()),
|
||||
@@ -572,6 +583,17 @@ fn merge_block_entity(original: &Tag, loaded: &Tag, current: &Tag) -> Tag {
|
||||
}
|
||||
merged
|
||||
}
|
||||
/// `BannerBlockEntity.loadAdditional` (and the `components` a block entity keeps).
|
||||
pub fn decode_banner(tag: &Tag) -> crate::containers::Banner {
|
||||
crate::containers::Banner {
|
||||
layers: crate::banner::layers_from_nbt(tag.get("patterns")),
|
||||
name: text(tag.get("CustomName")),
|
||||
components: match tag.get("components") {
|
||||
Some(Tag::Compound(c)) => c.clone(),
|
||||
_ => Compound::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> {
|
||||
use crate::containers::BlockEntity;
|
||||
let int = |k: &str| number(tag.get(k)).map(|v| v as i32);
|
||||
@@ -605,17 +627,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
|
||||
return Some((pos, BlockEntity::Lectern(lectern)));
|
||||
}
|
||||
if id == "minecraft:banner" {
|
||||
return Some((
|
||||
pos,
|
||||
BlockEntity::Banner(crate::containers::Banner {
|
||||
layers: crate::banner::layers_from_nbt(tag.get("patterns")),
|
||||
name: text(tag.get("CustomName")),
|
||||
components: match tag.get("components") {
|
||||
Some(Tag::Compound(c)) => c.clone(),
|
||||
_ => Compound::new(),
|
||||
},
|
||||
}),
|
||||
));
|
||||
return Some((pos, BlockEntity::Banner(decode_banner(tag))));
|
||||
}
|
||||
if id == "minecraft:beacon" {
|
||||
let beacon = crate::containers::Beacon {
|
||||
@@ -627,6 +639,18 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
|
||||
};
|
||||
return Some((pos, BlockEntity::Beacon(Box::new(beacon))));
|
||||
}
|
||||
// A skull's block entity id is not its block's name (every head block).
|
||||
if id == "minecraft:skull" {
|
||||
return Some((
|
||||
pos,
|
||||
BlockEntity::Skull(crate::containers::Skull::new(
|
||||
tag.get("profile").cloned(),
|
||||
text(tag.get("note_block_sound")),
|
||||
tag.get("custom_name")
|
||||
.and_then(crate::block_entity_nbt::component),
|
||||
)),
|
||||
));
|
||||
}
|
||||
// A spawner's block entity id is not its block's name.
|
||||
let block = match id.as_str() {
|
||||
"minecraft:mob_spawner" => "minecraft:spawner",
|
||||
@@ -699,7 +723,8 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
|
||||
| BlockEntity::Beacon(_)
|
||||
| BlockEntity::Lectern(_)
|
||||
| BlockEntity::Banner(_)
|
||||
| BlockEntity::CreakingHeart(_) => {}
|
||||
| BlockEntity::CreakingHeart(_)
|
||||
| BlockEntity::Skull(_) => {}
|
||||
BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag),
|
||||
BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag),
|
||||
BlockEntity::Vault(v) => **v = crate::vault::Vault::load(tag),
|
||||
@@ -3892,6 +3917,54 @@ mod tests {
|
||||
}
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn skull_block_entity_keeps_its_profile() {
|
||||
// A placed `player_head` as vanilla saves it: the owning player's
|
||||
// `profile` survives load, encode and `canonical`.
|
||||
let saved = horizon_world::nbt::parse_snbt(
|
||||
r#"{id:"minecraft:skull",x:10,y:64,z:20,profile:{name:"Steve",id:[I;1,2,3,4],properties:[{name:"textures",value:"abc"}]},note_block_sound:"minecraft:entity.player.hurt",custom_name:"Trophy"}"#,
|
||||
)
|
||||
.unwrap()
|
||||
.0;
|
||||
let (pos, back) = decode_block_entity(&saved).expect("skull");
|
||||
assert_eq!(pos, (10, 64, 20));
|
||||
let crate::containers::BlockEntity::Skull(skull) = &back else {
|
||||
panic!("not a skull");
|
||||
};
|
||||
assert_eq!(skull.profile, saved.get("profile").cloned());
|
||||
assert_eq!(
|
||||
skull.note_block_sound.as_deref(),
|
||||
Some("minecraft:entity.player.hurt")
|
||||
);
|
||||
assert_eq!(back.id(), "minecraft:skull");
|
||||
let tag = encode_block_entity(pos, &back, "minecraft:player_head");
|
||||
assert_eq!(
|
||||
crate::block_entity_nbt::id(&tag).as_deref(),
|
||||
Some("minecraft:skull")
|
||||
);
|
||||
assert_eq!(tag.get("profile"), saved.get("profile"));
|
||||
let (_, again) = decode_block_entity(&tag).expect("skull again");
|
||||
let crate::containers::BlockEntity::Skull(again) = again else {
|
||||
panic!("not a skull");
|
||||
};
|
||||
assert_eq!(again.profile, skull.profile);
|
||||
// A profile-less head (skeleton, creeper) round-trips too.
|
||||
let plain = encode_block_entity(
|
||||
pos,
|
||||
&crate::containers::BlockEntity::Skull(crate::containers::Skull::default()),
|
||||
"minecraft:creeper_head",
|
||||
);
|
||||
let (_, decoded) = decode_block_entity(&plain).expect("plain skull");
|
||||
assert!(matches!(decoded, crate::containers::BlockEntity::Skull(_)));
|
||||
// The heads and skulls have one; the piston's head is no skull.
|
||||
use crate::containers::BlockEntity;
|
||||
assert!(matches!(
|
||||
BlockEntity::for_block("minecraft:player_wall_head"),
|
||||
Some(BlockEntity::Skull(_))
|
||||
));
|
||||
assert!(BlockEntity::for_block("minecraft:piston_head").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uuid_text_round_trips() {
|
||||
let u = [-158327916, 1572358581, -2125825222, -487948715];
|
||||
|
||||
@@ -413,6 +413,13 @@ impl SculkEntity {
|
||||
spreader: SculkSpreader::default(),
|
||||
}
|
||||
}
|
||||
/// Whether its block entity tick does nothing: no vibration chosen
|
||||
/// or on its way, none waiting to be chosen, and no charge to spread.
|
||||
pub fn idle(&self) -> bool {
|
||||
self.vibration.current.is_none()
|
||||
&& self.vibration.selector.current().is_none()
|
||||
&& self.spreader.cursors.is_empty()
|
||||
}
|
||||
pub fn for_block(name: &str) -> Option<Self> {
|
||||
Some(Self::new(match name {
|
||||
"minecraft:sculk_sensor" => SculkKind::Sensor,
|
||||
|
||||
@@ -104,7 +104,7 @@ pub struct Settings {
|
||||
pub master_volume: f32,
|
||||
/// Volumes of every other sound source, indexed like SOUND_SOURCES.
|
||||
pub volumes: [f32; 11],
|
||||
/// 0 = auto.
|
||||
/// Requested scale (0 = auto); rendering caps it to the current framebuffer.
|
||||
pub gui_scale: u32,
|
||||
pub view_bobbing: bool,
|
||||
/// Brightness 0..1 (gamma).
|
||||
@@ -284,12 +284,6 @@ 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()
|
||||
@@ -597,6 +591,31 @@ impl Settings {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn gui_scale_survives_temporary_small_framebuffer() {
|
||||
for requested in [0, 1, 2, 6] {
|
||||
let settings = Settings::parse(&format!("guiScale:{requested}\n"));
|
||||
// Hyprland's initial surface can be smaller than the fullscreen one.
|
||||
for (framebuffer, maximum) in [([715, 860], 2), ([3400, 1913], 7)] {
|
||||
let effective = crate::window::calculate_scale(
|
||||
framebuffer,
|
||||
settings.gui_scale as i32,
|
||||
settings.force_unicode,
|
||||
);
|
||||
assert_eq!(
|
||||
effective,
|
||||
if requested == 0 {
|
||||
maximum
|
||||
} else {
|
||||
(requested as i32).min(maximum)
|
||||
}
|
||||
);
|
||||
let saved = Settings::parse(&settings.serialize());
|
||||
assert_eq!(saved.gui_scale, requested);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_vanilla_options_txt() {
|
||||
let text = "version:4000\nfov:0.5\nrenderDistance:16\nmaxFps:260\nrenderClouds:\"fast\"\nkey_key.jump:key.keyboard.j\nsoundCategory_music:0.25\nresourcePacks:[\"vanilla\",\"file/x.zip\"]\nlang:fr_fr\nsomeFutureOption:42\n";
|
||||
|
||||
@@ -130,6 +130,47 @@ pub fn profile_skin_url(profile: &serde_json::Value) -> Option<String> {
|
||||
unpack(value, Signature::Unsigned, &TEXTURE_URIS).skin
|
||||
}
|
||||
|
||||
/// `profile_skin_url` on a block entity's `profile` NBT (`SkullBlockEntity`):
|
||||
/// the same `properties` list, held as a compound. A name-only profile (a
|
||||
/// string tag) has no properties and no skin URL.
|
||||
pub fn profile_skin_url_nbt(profile: &horizon_world::nbt::Tag) -> Option<String> {
|
||||
let properties = match profile.get("properties")? {
|
||||
horizon_world::nbt::Tag::List(list) => list,
|
||||
_ => return None,
|
||||
};
|
||||
let value = properties.iter().find_map(|p| {
|
||||
let name = nbt_text(p.get("name"))?;
|
||||
(name == "textures")
|
||||
.then(|| nbt_text(p.get("value")))
|
||||
.flatten()
|
||||
})?;
|
||||
unpack(&value, Signature::Unsigned, &TEXTURE_URIS).skin
|
||||
}
|
||||
|
||||
/// The profile's uuid as u128: `id` as an int array (block entity NBT) or a
|
||||
/// uuid string (older and component forms). Used for `DefaultPlayerSkin.get`
|
||||
/// when a head's skin is not downloaded yet.
|
||||
pub fn profile_uuid_nbt(profile: &horizon_world::nbt::Tag) -> Option<u128> {
|
||||
match profile.get("id")? {
|
||||
horizon_world::nbt::Tag::IntArray(v) if v.len() == 4 => Some(
|
||||
v.iter()
|
||||
.fold(0u128, |a, &w| (a << 32) | u128::from(w as u32)),
|
||||
),
|
||||
horizon_world::nbt::Tag::String(s) => {
|
||||
let digits: String = s.to_string_lossy().chars().filter(|c| *c != '-').collect();
|
||||
u128::from_str_radix(&digits, 16).ok()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option<String> {
|
||||
match tag {
|
||||
Some(horizon_world::nbt::Tag::String(s)) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `MinecraftProfileTexture.getHash`: the base name of the URL's path.
|
||||
pub fn texture_hash(url: &str) -> Option<String> {
|
||||
let rest = url.split_once("://")?.1;
|
||||
@@ -457,6 +498,42 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn skull_block_entity_profiles_supply_head_skins() {
|
||||
let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0=";
|
||||
let profile = horizon_world::nbt::parse_snbt(&format!(
|
||||
r#"{{name:"T",id:[I;-158327916,1572358581,-2125825222,-487948715],properties:[{{name:"textures",value:"{value}"}}]}}"#
|
||||
))
|
||||
.unwrap()
|
||||
.0;
|
||||
assert_eq!(
|
||||
super::profile_skin_url_nbt(&profile).as_deref(),
|
||||
Some("https://textures.minecraft.net/texture/abc123")
|
||||
);
|
||||
assert_eq!(
|
||||
super::profile_uuid_nbt(&profile),
|
||||
Some(
|
||||
[-158327916, 1572358581, -2125825222, -487948715]
|
||||
.iter()
|
||||
.fold(0u128, |a, &w: &i32| (a << 32) | u128::from(w as u32))
|
||||
)
|
||||
);
|
||||
// A name-only profile (a string tag) has no properties: no url, no id.
|
||||
let named = horizon_world::nbt::Tag::String("MHF_Blaze".into());
|
||||
assert_eq!(super::profile_skin_url_nbt(&named), None);
|
||||
assert_eq!(super::profile_uuid_nbt(&named), None);
|
||||
// A uuid in string form decodes too.
|
||||
let text_id = horizon_world::nbt::parse_snbt(
|
||||
r#"{name:"T",id:"e843a1f4-0000-0001-0000-000200000003"}"#,
|
||||
)
|
||||
.unwrap()
|
||||
.0;
|
||||
assert_eq!(
|
||||
super::profile_uuid_nbt(&text_id),
|
||||
Some(u128::from_str_radix("e843a1f4000000010000000200000003", 16).unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha1_and_base64() {
|
||||
let hex: String = sha1(b"abc").iter().map(|b| format!("{b:02x}")).collect();
|
||||
|
||||
@@ -278,6 +278,11 @@ pub struct Streaming {
|
||||
cover: Option<ExtraCover>,
|
||||
/// Mesh the sections for drawing (false on a server thread).
|
||||
pub mesh: bool,
|
||||
/// The pregeneration band (`set_band`).
|
||||
band: Option<Band>,
|
||||
/// The columns and the next row the band's decoration ranks were given
|
||||
/// for (`set_band`).
|
||||
band_ranked: Option<(i32, i32, i32)>,
|
||||
}
|
||||
/// Snapshot only after a scan found no missing candidates. Public range fields
|
||||
/// and `World::chunks` can change without going through Streaming, so compare
|
||||
@@ -289,6 +294,7 @@ struct GenerationScan {
|
||||
radius: i32,
|
||||
extra: Vec<((i32, i32), i32)>,
|
||||
forced: HashSet<(i32, i32)>,
|
||||
band: Option<Band>,
|
||||
chunk_revision: u64,
|
||||
}
|
||||
impl GenerationScan {
|
||||
@@ -298,6 +304,7 @@ impl GenerationScan {
|
||||
&& self.radius == ranges.radius
|
||||
&& self.extra == ranges.extra
|
||||
&& self.forced == *ranges.forced
|
||||
&& self.band.as_ref() == ranges.band
|
||||
&& self.chunk_revision == world.chunks.membership_revision()
|
||||
}
|
||||
fn remember(&mut self, ranges: Ranges<'_>, world: &World) {
|
||||
@@ -307,6 +314,7 @@ impl GenerationScan {
|
||||
self.extra.clear();
|
||||
self.extra.extend_from_slice(ranges.extra);
|
||||
self.forced.clone_from(ranges.forced);
|
||||
self.band = ranges.band.copied();
|
||||
self.chunk_revision = world.chunks.membership_revision();
|
||||
}
|
||||
}
|
||||
@@ -348,6 +356,10 @@ impl GenerationScan {
|
||||
let r = radius + margin.max(reach + 1);
|
||||
runs.extend((center.1 - r..=center.1 + r).map(|z| (z, center.0 - r, center.0 + r)));
|
||||
}
|
||||
if let Some(band) = input.ranges.band {
|
||||
let r = margin.max(reach + 1);
|
||||
runs.extend((band.z0 - r..=band.z1 + r).map(|z| (z, band.x0 - r, band.x1 + r)));
|
||||
}
|
||||
runs.sort_unstable();
|
||||
let mut runs = runs.into_iter().peekable();
|
||||
while let Some((z, x0, mut x1)) = runs.next() {
|
||||
@@ -392,6 +404,7 @@ impl GenerationScan {
|
||||
extra: input.ranges.extra,
|
||||
forced: input.ranges.forced,
|
||||
cover: input.ranges.cover,
|
||||
band: input.ranges.band,
|
||||
};
|
||||
self.remember(ranges, input.world);
|
||||
} else {
|
||||
@@ -564,6 +577,8 @@ impl Streaming {
|
||||
extra: Vec::new(),
|
||||
cover: None,
|
||||
mesh: true,
|
||||
band: None,
|
||||
band_ranked: None,
|
||||
}
|
||||
}
|
||||
/// Shares generation resources, but gives distant work its own worker state.
|
||||
@@ -916,6 +931,7 @@ impl Streaming {
|
||||
p.is_some()
|
||||
&& i64::from(x - center.0).pow(2) + i64::from(z - center.1).pow(2) > r4 * r4
|
||||
&& !ranges.in_extra(x, z, 4)
|
||||
&& !ranges.in_band(x, z, 4)
|
||||
&& !ranges
|
||||
.forced
|
||||
.iter()
|
||||
@@ -985,6 +1001,7 @@ impl Streaming {
|
||||
extra: &self.extra,
|
||||
forced: &self.forced,
|
||||
cover: ExtraCover::matching(&self.cover, &self.extra),
|
||||
band: self.band.as_ref(),
|
||||
};
|
||||
let (protos, generating) = (&self.protos, &self.generating);
|
||||
self.decoration_order.retain(|x, z| {
|
||||
@@ -1113,6 +1130,7 @@ impl Streaming {
|
||||
extra: &self.extra,
|
||||
forced: &self.forced,
|
||||
cover: ExtraCover::matching(&self.cover, &self.extra),
|
||||
band: self.band.as_ref(),
|
||||
};
|
||||
self.waiting.retain(|&(x, sy, z)| {
|
||||
let back = ranges.in_view(x, z);
|
||||
@@ -1189,6 +1207,7 @@ impl Streaming {
|
||||
extra: &self.extra,
|
||||
forced: &self.forced,
|
||||
cover: ExtraCover::matching(&self.cover, &self.extra),
|
||||
band: self.band.as_ref(),
|
||||
},
|
||||
world,
|
||||
generating: &self.generating,
|
||||
@@ -1285,6 +1304,7 @@ impl Streaming {
|
||||
extra: &self.extra,
|
||||
forced: &self.forced,
|
||||
cover: ExtraCover::matching(&self.cover, &self.extra),
|
||||
band: self.band.as_ref(),
|
||||
}
|
||||
}
|
||||
fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool {
|
||||
@@ -1354,6 +1374,66 @@ impl Streaming {
|
||||
fn in_range(&self, x: i32, z: i32, margin: i32) -> bool {
|
||||
self.ranges().in_range(x, z, margin)
|
||||
}
|
||||
pub fn band(&self) -> Option<Band> {
|
||||
self.band
|
||||
}
|
||||
/// Generate, light and keep the chunks of `band` (none: stop), and let
|
||||
/// go of what earlier bands held as it falls out of range. The chunks a
|
||||
/// band reaches are ranked for decoration row by row, as they first come
|
||||
/// within reach, so that a task decorates in the same order however its
|
||||
/// work is timed and shared among the workers.
|
||||
pub fn set_band(&mut self, band: Option<Band>) {
|
||||
if self.band == band {
|
||||
return;
|
||||
}
|
||||
self.band = band;
|
||||
self.generation_scan.exhausted = false;
|
||||
let Some(band) = band else {
|
||||
return;
|
||||
};
|
||||
// Decoration reaches two chunks past the band and generation three.
|
||||
const REACH: i32 = 4;
|
||||
let (x0, x1) = (band.x0 - REACH, band.x1 + REACH);
|
||||
let first = match self.band_ranked {
|
||||
Some((rx0, rx1, next)) if (rx0, rx1) == (x0, x1) => next,
|
||||
_ => band.z0 - REACH,
|
||||
};
|
||||
let end = band.z1 + REACH;
|
||||
for z in first..=end {
|
||||
for x in x0..=x1 {
|
||||
self.decoration_order.rank_or_append(x, z);
|
||||
}
|
||||
}
|
||||
self.band_ranked = Some((x0, x1, end.max(first - 1) + 1));
|
||||
}
|
||||
/// What holds up the columns `keys`, for a task that stopped advancing:
|
||||
/// how many are not loaded, loaded but unlit with a light job in flight,
|
||||
/// and unlit with none (those whose neighbours are all loaded are queued
|
||||
/// for light again).
|
||||
pub fn unstick_light(&mut self, world: &mut World, keys: &[(i32, i32)]) -> [usize; 3] {
|
||||
let mut counts = [0; 3];
|
||||
for &key in keys {
|
||||
if !world.chunks.contains_key(&key) {
|
||||
counts[0] += 1;
|
||||
} else if self.lit.contains(&key) {
|
||||
} else if self.lighting.contains_key(&key) {
|
||||
counts[1] += 1;
|
||||
} else {
|
||||
counts[2] += 1;
|
||||
if Self::region(world, key.0, key.1).is_some() {
|
||||
world.dirty_light.insert(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
/// Wait up to `timeout` for a worker to finish a job; the next `update`
|
||||
/// takes it. A server pumps generation with this between its ticks.
|
||||
pub fn wait(&mut self, timeout: std::time::Duration) {
|
||||
if let Ok(done) = self.results.recv_timeout(timeout) {
|
||||
self.deferred.push(done);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `ChunkTrackingView.isInViewDistance`: whether the column (x, z) is drawn
|
||||
/// at this render distance around `center`, the camera's column
|
||||
@@ -1373,6 +1453,53 @@ struct Ranges<'a> {
|
||||
/// `extra` as a grid, when one was made for it: `in_extra` without a
|
||||
/// scan of every area.
|
||||
cover: Option<&'a ExtraCover>,
|
||||
band: Option<&'a Band>,
|
||||
}
|
||||
/// The chunks a pregeneration task (`/pregen`) wants lit now: rows `z0..=z1`
|
||||
/// of the columns `x0..=x1`, those within `circle` (a centre and a radius in
|
||||
/// chunks) when there is one. Like an extra area, it finishes its chunks and
|
||||
/// the ring around them, so that its own chunks can be lit, and generation
|
||||
/// reaches past that. A task moves it down a strip of columns a row at a
|
||||
/// time, so each chunk is generated once and only the rows in flight stay
|
||||
/// loaded.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Band {
|
||||
pub x0: i32,
|
||||
pub x1: i32,
|
||||
pub z0: i32,
|
||||
pub z1: i32,
|
||||
pub circle: Option<((i32, i32), i32)>,
|
||||
}
|
||||
impl Band {
|
||||
/// Whether (x, z) lies within `margin` (Chebyshev) of one of the band's
|
||||
/// chunks: the square of side `2 * margin + 1` around it meets the
|
||||
/// rectangle at a point inside the circle.
|
||||
pub fn within(&self, x: i32, z: i32, margin: i32) -> bool {
|
||||
let (x0, x1) = (
|
||||
x.saturating_sub(margin).max(self.x0),
|
||||
x.saturating_add(margin).min(self.x1),
|
||||
);
|
||||
let (z0, z1) = (
|
||||
z.saturating_sub(margin).max(self.z0),
|
||||
z.saturating_add(margin).min(self.z1),
|
||||
);
|
||||
if x0 > x1 || z0 > z1 {
|
||||
return false;
|
||||
}
|
||||
self.circle.is_none_or(|((cx, cz), r)| {
|
||||
let dx = i64::from(cx.clamp(x0, x1)) - i64::from(cx);
|
||||
let dz = i64::from(cz.clamp(z0, z1)) - i64::from(cz);
|
||||
dx * dx + dz * dz <= i64::from(r) * i64::from(r)
|
||||
})
|
||||
}
|
||||
/// The band's chunks go after the players' (lower runs first), row by
|
||||
/// row, as the task wants them lit.
|
||||
fn priority(&self, x: i32, z: i32) -> i64 {
|
||||
const AFTER_PLAYERS: i64 = 1 << 40;
|
||||
AFTER_PLAYERS
|
||||
+ (i64::from(z - self.z0 + 8).max(0) << 20)
|
||||
+ i64::from(x - self.x0 + 8).max(0)
|
||||
}
|
||||
}
|
||||
/// For every column near the extra areas, how far it lies outside the
|
||||
/// nearest one's square (Chebyshev distance less its radius; 0 inside). A server has an area per player, and streaming asks of every
|
||||
@@ -1468,10 +1595,14 @@ impl ExtraCover {
|
||||
impl Ranges<'_> {
|
||||
/// `distance`, or `rings` while the level loading screen is up.
|
||||
fn priority(&self, x: i32, z: i32, loading: bool) -> i64 {
|
||||
if loading {
|
||||
let own = if loading {
|
||||
self.rings(x, z)
|
||||
} else {
|
||||
self.distance(x, z)
|
||||
};
|
||||
match self.band {
|
||||
Some(band) if band.within(x, z, 4) => own.min(band.priority(x, z)),
|
||||
_ => own,
|
||||
}
|
||||
}
|
||||
/// Ring by ring: the Chebyshev distance to the nearest centre first, then
|
||||
@@ -1532,10 +1663,18 @@ impl Ranges<'_> {
|
||||
let (dx, dz) = (gap(x - self.center.0), gap(z - self.center.1));
|
||||
let r = i64::from(self.radius + 1);
|
||||
// The extra areas are squares: their finished square grown by `reach`.
|
||||
dx * dx + dz * dz <= r * r || self.in_extra(x, z, 1 + reach)
|
||||
dx * dx + dz * dz <= r * r
|
||||
|| self.in_extra(x, z, 1 + reach)
|
||||
|| self.in_band(x, z, 1 + reach)
|
||||
}
|
||||
fn in_range(&self, x: i32, z: i32, margin: i32) -> bool {
|
||||
self.in_main_range(x, z, margin) || self.in_extra(x, z, margin)
|
||||
self.in_main_range(x, z, margin)
|
||||
|| self.in_extra(x, z, margin)
|
||||
|| self.in_band(x, z, margin)
|
||||
}
|
||||
/// Within `margin` of the pregeneration band.
|
||||
fn in_band(&self, x: i32, z: i32, margin: i32) -> bool {
|
||||
self.band.is_some_and(|b| b.within(x, z, margin))
|
||||
}
|
||||
/// Within `margin` of an extra area's square (Chebyshev distance, as
|
||||
/// vanilla's ticket levels spread).
|
||||
@@ -1659,6 +1798,7 @@ mod tests {
|
||||
extra: &self.extra,
|
||||
forced: &self.forced,
|
||||
cover: None,
|
||||
band: None,
|
||||
},
|
||||
world: &self.world,
|
||||
generating: &self.generating,
|
||||
@@ -1972,6 +2112,7 @@ mod tests {
|
||||
extra: &[],
|
||||
forced: &forced,
|
||||
cover: None,
|
||||
band: None,
|
||||
};
|
||||
let square = |x: i32, z: i32, n: i32| {
|
||||
(-n..=n).flat_map(move |dz| (-n..=n).map(move |dx| (x + dx, z + dz)))
|
||||
@@ -2027,6 +2168,7 @@ mod tests {
|
||||
extra: &[],
|
||||
forced: &forced,
|
||||
cover: None,
|
||||
band: None,
|
||||
};
|
||||
let at = |dx: i32, dz: i32| (2 + dx, -1 + dz);
|
||||
let key = |(x, z): (i32, i32), loading| r.priority(x, z, loading);
|
||||
@@ -2053,6 +2195,7 @@ mod tests {
|
||||
extra: &[((radius * 2 + 9, 3), 4)],
|
||||
forced: &forced,
|
||||
cover: None,
|
||||
band: None,
|
||||
};
|
||||
let span = radius * 3 + 20;
|
||||
for x in -span..=span {
|
||||
@@ -2093,6 +2236,7 @@ mod tests {
|
||||
extra: &extra,
|
||||
forced: &forced,
|
||||
cover: None,
|
||||
band: None,
|
||||
};
|
||||
let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0);
|
||||
for x in 40 - view - 8..=40 + view + 8 {
|
||||
@@ -2148,8 +2292,13 @@ mod cover_tests {
|
||||
}
|
||||
|
||||
/// Every question streaming asks gets the same answer with the grid.
|
||||
///
|
||||
/// A debug build checks every fourth cell of each row, shifted by row and case so the cases still cover every
|
||||
/// cell's position relative to the areas: the full check took 20 of the ~30 s of the crate's tests.
|
||||
/// `cargo test --release -p horizon-client --lib the_grid_answers_as_the_scan` checks every cell.
|
||||
#[test]
|
||||
fn the_grid_answers_as_the_scan() {
|
||||
let stride = if cfg!(debug_assertions) { 4 } else { 1 };
|
||||
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
|
||||
let forced: HashSet<(i32, i32)> = [(40, -40)].into();
|
||||
for case in 0..60 {
|
||||
@@ -2161,11 +2310,13 @@ mod cover_tests {
|
||||
extra: &extra,
|
||||
forced: &forced,
|
||||
cover,
|
||||
band: None,
|
||||
};
|
||||
let (scan, grid) = (ranges(None), ranges(Some(&cover)));
|
||||
let span = [4, 30, 120][case % 3] + 40;
|
||||
for z in -span..=span {
|
||||
for x in -span..=span {
|
||||
let first = -span + (z + case as i32).rem_euclid(stride);
|
||||
for x in (first..=span).step_by(stride as usize) {
|
||||
for m in 0..=ExtraCover::REACH + 2 {
|
||||
assert_eq!(
|
||||
scan.in_extra(x, z, m),
|
||||
@@ -2218,6 +2369,7 @@ mod cover_tests {
|
||||
extra: &extra,
|
||||
forced: &forced,
|
||||
cover,
|
||||
band: None,
|
||||
};
|
||||
// The columns streaming asks about: everything kept, and the
|
||||
// generation scan's ring past it.
|
||||
|
||||
@@ -128,6 +128,27 @@ fn text(nbt: &Compound, key: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The client block entity for one of a chunk's generated block entities,
|
||||
/// before a container's loot is unpacked: `StructureTemplate.placeInWorld`
|
||||
/// hands the template's block entity NBT to the level's block entity.
|
||||
fn generated_block_entity(block: &str, nbt: &Compound) -> Option<BlockEntity> {
|
||||
let mut entity = BlockEntity::for_block(block)?;
|
||||
match &mut entity {
|
||||
// MonsterRoomFeature and the structures' setEntityId.
|
||||
BlockEntity::Spawner(s) => {
|
||||
**s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone()));
|
||||
}
|
||||
BlockEntity::TrialSpawner(s) => {
|
||||
**s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone()));
|
||||
}
|
||||
BlockEntity::Vault(v) => **v = crate::vault::Vault::load(&Tag::Compound(nbt.clone())),
|
||||
// BannerBlockEntity.loadAdditional: the End cities' black triangles.
|
||||
BlockEntity::Banner(b) => *b = crate::save::decode_banner(&Tag::Compound(nbt.clone())),
|
||||
_ => {}
|
||||
}
|
||||
Some(entity)
|
||||
}
|
||||
|
||||
/// Client block entities for the generated block entities of a chunk.
|
||||
pub fn block_entities(
|
||||
chunk: &ProtoChunk,
|
||||
@@ -137,19 +158,9 @@ pub fn block_entities(
|
||||
for (pos, nbt) in &chunk.block_entities {
|
||||
let [x, y, z] = *pos;
|
||||
let block = chunk.block_name(x, y, z);
|
||||
let Some(mut entity) = BlockEntity::for_block(block) else {
|
||||
let Some(mut entity) = generated_block_entity(block, nbt) else {
|
||||
continue;
|
||||
};
|
||||
// MonsterRoomFeature and the structures' setEntityId.
|
||||
if let BlockEntity::Spawner(s) = &mut entity {
|
||||
**s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone()));
|
||||
}
|
||||
if let BlockEntity::TrialSpawner(s) = &mut entity {
|
||||
**s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone()));
|
||||
}
|
||||
if let BlockEntity::Vault(v) = &mut entity {
|
||||
**v = crate::vault::Vault::load(&Tag::Compound(nbt.clone()));
|
||||
}
|
||||
if let (BlockEntity::Chest(slots), Some(table), Some(loot)) =
|
||||
(&mut entity, text(nbt, "LootTable"), loot)
|
||||
{
|
||||
@@ -165,14 +176,10 @@ pub fn block_entities(
|
||||
.iter_mut()
|
||||
.zip(loot.fill(&table, seed, 27, Some(biome)))
|
||||
{
|
||||
*slot = stack.map(|s| {
|
||||
let mut item = loot_item(&s);
|
||||
// An ominous bottle's level (the default, 0, is no component).
|
||||
if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) {
|
||||
item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8);
|
||||
}
|
||||
item
|
||||
});
|
||||
// With what the rolls put on them: enchantments
|
||||
// (enchant_with_levels in End city chests), potions and an
|
||||
// ominous bottle's level.
|
||||
*slot = stack.map(|s| loot_item_with_components(&s));
|
||||
}
|
||||
}
|
||||
out.push(((x, y, z), entity));
|
||||
@@ -211,7 +218,7 @@ pub fn unpack_entity_loot(
|
||||
let slots: Vec<Option<ItemStack>> = loot
|
||||
.fill(&table, seed, 27, Some(biome))
|
||||
.into_iter()
|
||||
.map(|s| s.map(|s| loot_item(&s)))
|
||||
.map(|s| s.map(|s| loot_item_with_components(&s)))
|
||||
.collect();
|
||||
nbt.remove(&JavaString::from("LootTable"));
|
||||
nbt.remove(&JavaString::from("LootTableSeed"));
|
||||
@@ -224,6 +231,45 @@ mod tests {
|
||||
use super::*;
|
||||
use horizon_world::loot::{ExplorationMap, LootStack};
|
||||
|
||||
#[test]
|
||||
fn placed_chest_loot_keeps_its_enchantments_and_potions() {
|
||||
let stack =
|
||||
|item: &str, enchantments: Vec<(String, i32)>, potion: Option<&str>| LootStack {
|
||||
item: item.into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
enchantments,
|
||||
potion: potion.map(str::to_owned),
|
||||
map: false,
|
||||
exploration: None,
|
||||
ominous_amplifier: None,
|
||||
};
|
||||
// An End city chest's enchant_with_levels roll.
|
||||
let boots = loot_item_with_components(&stack(
|
||||
"minecraft:diamond_boots",
|
||||
vec![
|
||||
("minecraft:protection".into(), 3),
|
||||
("minecraft:unbreaking".into(), 2),
|
||||
],
|
||||
None,
|
||||
));
|
||||
assert_eq!(boots.enchantments().len(), 2);
|
||||
// A book's go into stored_enchantments.
|
||||
let book = loot_item_with_components(&stack(
|
||||
"minecraft:enchanted_book",
|
||||
vec![("minecraft:mending".into(), 1)],
|
||||
None,
|
||||
));
|
||||
assert!(book.enchantments().is_empty());
|
||||
assert_eq!(book.stored_enchantments().len(), 1);
|
||||
let arrow = loot_item_with_components(&stack(
|
||||
"minecraft:tipped_arrow",
|
||||
Vec::new(),
|
||||
Some("minecraft:slowness"),
|
||||
));
|
||||
assert_eq!(arrow.potion(), Some("minecraft:slowness"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exploration_maps_wait_in_custom_data_until_searched() {
|
||||
let mut stack = LootStack {
|
||||
@@ -278,4 +324,43 @@ mod tests {
|
||||
stack.exploration = None;
|
||||
assert!(!has_pending_map(&loot_item(&stack)));
|
||||
}
|
||||
|
||||
/// The End cities' tower tops save their banners' patterns in the
|
||||
/// template; the placed banner must keep them (`EndCityPieces`).
|
||||
#[test]
|
||||
fn a_generated_banner_keeps_its_template_patterns() {
|
||||
let patterns = Tag::List(vec![
|
||||
Tag::compound([
|
||||
("color", Tag::String("black".into())),
|
||||
("pattern", Tag::String("minecraft:triangle_top".into())),
|
||||
]),
|
||||
Tag::compound([
|
||||
("color", Tag::String("black".into())),
|
||||
("pattern", Tag::String("minecraft:triangle_bottom".into())),
|
||||
]),
|
||||
]);
|
||||
let nbt = Tag::compound([
|
||||
("id", Tag::String("minecraft:banner".into())),
|
||||
("patterns", patterns),
|
||||
]);
|
||||
let Tag::Compound(nbt) = nbt else {
|
||||
unreachable!()
|
||||
};
|
||||
let Some(BlockEntity::Banner(banner)) =
|
||||
generated_block_entity("minecraft:magenta_banner", &nbt)
|
||||
else {
|
||||
panic!("a banner block makes a banner block entity");
|
||||
};
|
||||
assert_eq!(banner.layers.len(), 2);
|
||||
assert_eq!(&*banner.layers[0].pattern, "minecraft:triangle_top");
|
||||
assert_eq!(&*banner.layers[1].pattern, "minecraft:triangle_bottom");
|
||||
assert_eq!(&*banner.layers[0].color, "black");
|
||||
// A banner the template saved without patterns stays bare.
|
||||
let Some(BlockEntity::Banner(bare)) =
|
||||
generated_block_entity("minecraft:white_banner", &Compound::new())
|
||||
else {
|
||||
panic!("a banner block makes a banner block entity");
|
||||
};
|
||||
assert!(bare.layers.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,10 @@ pub struct VanillaTerrain {
|
||||
tick_states: Vec<u32>,
|
||||
seed: i64,
|
||||
dimension: String,
|
||||
/// When the last proto chunk was generated, in milliseconds since
|
||||
/// `created`: the ring search waits for a pause in generation.
|
||||
last_proto: std::sync::atomic::AtomicU64,
|
||||
created: std::time::Instant,
|
||||
}
|
||||
/// A proto chunk, or the position of one whose generation failed.
|
||||
enum VanillaProto {
|
||||
@@ -139,6 +143,8 @@ impl VanillaTerrain {
|
||||
tick_states,
|
||||
seed,
|
||||
dimension: dimension.to_owned(),
|
||||
last_proto: std::sync::atomic::AtomicU64::new(0),
|
||||
created: std::time::Instant::now(),
|
||||
})
|
||||
}
|
||||
/// A proto chunk's blocks, biomes, scheduled ticks and post-processing
|
||||
@@ -272,9 +278,53 @@ impl VanillaTerrain {
|
||||
pub fn origin(&self) -> crate::Result<ChunkPos> {
|
||||
Ok(self.generator.origin()?)
|
||||
}
|
||||
/// Concentric ring positions of a structure set (strongholds), once known.
|
||||
/// Concentric ring positions of a structure set (strongholds), searched
|
||||
/// for now if no chunk needed them yet.
|
||||
pub fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
|
||||
self.generator.ring_positions(set)
|
||||
let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let worker = worker.get_or_insert_with(|| self.generator.worker());
|
||||
worker.ring_positions(set)
|
||||
}
|
||||
/// Searches the concentric rings on a thread of their own, as vanilla's
|
||||
/// background executor does, once generation pauses for two seconds
|
||||
/// (at the latest a minute after the world opens) and in the idle
|
||||
/// class: on a laptop's few cores, sharing them with the first chunks,
|
||||
/// which don't need the rings, made those 3 s slower. An eye of ender
|
||||
/// thrown later finds the rings ready, and a chunk or a query that
|
||||
/// needs them first shares the remaining searches with this thread.
|
||||
pub fn search_rings_behind(self: &Arc<Self>) {
|
||||
const QUIET: u64 = 2_000;
|
||||
const LATEST: u64 = 60_000;
|
||||
let terrain = Arc::downgrade(self);
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("Ring search".into())
|
||||
.spawn(move || {
|
||||
horizon_threads::idle_current();
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||
// The world closed: nothing to search for.
|
||||
let Some(terrain) = terrain.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let now = terrain.elapsed_ms();
|
||||
let last = terrain
|
||||
.last_proto
|
||||
.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if now >= LATEST || (last > 0 && now - last >= QUIET) {
|
||||
let _ = terrain
|
||||
.generator
|
||||
.worker()
|
||||
.ring_positions("minecraft:strongholds");
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("ring search thread: {e}");
|
||||
}
|
||||
}
|
||||
fn elapsed_ms(&self) -> u64 {
|
||||
u64::try_from(self.created.elapsed().as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
}
|
||||
/// The worldgen bundle at `dir`, loaded once and shared by every generator
|
||||
@@ -323,6 +373,10 @@ impl ChunkGenerator for VanillaTerrain {
|
||||
}
|
||||
}
|
||||
fn proto(&self, worker: &mut GeneratorWorker, x: i32, z: i32) -> Proto {
|
||||
self.last_proto.store(
|
||||
self.elapsed_ms().max(1),
|
||||
std::sync::atomic::Ordering::Relaxed,
|
||||
);
|
||||
match worker.generate_proto(ChunkPos::new(x, z)) {
|
||||
Ok(chunk) => Box::new(VanillaProto::Ready(Box::new(chunk))),
|
||||
Err(e) => {
|
||||
|
||||
@@ -106,14 +106,16 @@ enum Palette {
|
||||
List(Vec<u32>),
|
||||
Global,
|
||||
}
|
||||
/// `n / per_word` for `n < 4096` by multiplication: `MAGIC[bits] = ceil(2^20 /
|
||||
/// (64 / bits))` is exact while `n * (64 / bits) < 2^20`.
|
||||
const MAGIC: [u32; 33] = {
|
||||
let mut table = [0; 33];
|
||||
/// `n / per_word` for `n < 4096` by multiplication: `MAGIC[bits].0 = ceil(2^20 /
|
||||
/// (64 / bits))` is exact while `n * (64 / bits) < 2^20`. `.1` is the bits a
|
||||
/// word's entries fill (`64 / bits * bits`): looked up, not divided for, as a
|
||||
/// division by a run-time value costs tens of cycles on x86.
|
||||
const MAGIC: [(u32, u32); 33] = {
|
||||
let mut table = [(0, 0); 33];
|
||||
let mut bits = 1;
|
||||
while bits <= 32 {
|
||||
let per = 64 / bits as u32;
|
||||
table[bits] = (1u32 << 20).div_ceil(per);
|
||||
table[bits] = ((1u32 << 20).div_ceil(per), per * bits as u32);
|
||||
bits += 1;
|
||||
}
|
||||
table
|
||||
@@ -134,9 +136,9 @@ fn locate(bits: u8, i: usize) -> (usize, u32) {
|
||||
let word = i >> (6 - log);
|
||||
(word, ((i & ((64 >> log) - 1)) as u32) << log)
|
||||
} else {
|
||||
let per = 64 / u32::from(bits);
|
||||
let word = (i as u32 * MAGIC[usize::from(bits)]) >> 20;
|
||||
(word as usize, (i as u32 - word * per) * u32::from(bits))
|
||||
let (magic, filled) = MAGIC[usize::from(bits)];
|
||||
let word = (i as u32 * magic) >> 20;
|
||||
(word as usize, i as u32 * u32::from(bits) - word * filled)
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
@@ -720,6 +722,17 @@ mod tests {
|
||||
use super::*;
|
||||
const BLOCKS: Strategy = Strategy::blocks(16);
|
||||
const BIOMES: Strategy = Strategy::biomes(7);
|
||||
|
||||
#[test]
|
||||
fn locate_matches_division_for_every_width() {
|
||||
for bits in 1..=32u8 {
|
||||
let per = 64 / usize::from(bits);
|
||||
for i in 0..4096 {
|
||||
let expected = (i / per, ((i % per) * usize::from(bits)) as u32);
|
||||
assert_eq!(locate(bits, i), expected, "{bits} bits, entry {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn rng(state: &mut u64) -> u64 {
|
||||
*state ^= *state << 13;
|
||||
*state ^= *state >> 7;
|
||||
|
||||
@@ -7,7 +7,7 @@ rust-version = "1.85"
|
||||
description = "Write Horizon mods in Rust: WebAssembly components for the horizon:mod world (docs/mods.md)"
|
||||
|
||||
[dependencies]
|
||||
wit-bindgen = { version = "0.57.1", default-features = false, features = ["macros", "realloc"] }
|
||||
wit-bindgen = { version = "0.60.0", default-features = false, features = ["macros", "realloc"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "predator-missile"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "Example Horizon mod: a missile you launch with /missile and steer with the mouse"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
horizon-mod-sdk = { path = "../.." }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user