Merge feat/java-packs-photon-chocapic into feat/java-gbuffers-terrain

Brings main's shader api 2 (#1414) up the stack. One path for blending:
the terrain programs' blend.* now go through Pass.blend/buffer_blends like
composite and final (java_pack::pass_blends). depthtex1/depthtex2 are one
source, DepthSolid: Horizon's depth before translucent geometry, then the
pack's solid terrain's. Horizon's world goes to the pack's first terrain
target (colortex1 for MakeUp).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-23 17:46:12 +02:00
425 changed files with 43178 additions and 10949 deletions
-1
View File
@@ -6,7 +6,6 @@
/.github/ @ludovic111
/tools/ci/ @ludovic111
/tools/release_train.py @ludovic111
/tools/release_channels.py @ludovic111
/crates/horizon-release-sign/ @ludovic111
/crates/horizon-server/src/update.rs @ludovic111
/crates/horizon-server/Cargo.toml @ludovic111
+1
View File
@@ -0,0 +1 @@
0.2
+4
View File
@@ -18,6 +18,10 @@ concurrency:
# A new push to a pull request replaces its running checks; main's runs all finish (releases follow them).
group: checks-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
HORIZON_TELEMETRY_URL: "off"
jobs:
verify:
runs-on: ubuntu-latest
+4 -3
View File
@@ -49,6 +49,10 @@ concurrency:
group: launcher-${{ github.ref == 'refs/heads/main' && 'release' || github.ref }}
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:
decide:
runs-on: ubuntu-latest
@@ -188,9 +192,6 @@ jobs:
retry "$launcher" install latest
"$launcher" versions --installed
"$launcher" links --json
"$launcher" menu-style classic
grep -qx 'menuStyle:classic' "$HORIZON_HOME/horizon.txt"
"$launcher" menu-style horizon
clients=("$HORIZON_LAUNCHER_HOME"/versions/v*/horizon-client*)
client="${clients[0]}"
echo "installed client: $client"
+4
View File
@@ -23,6 +23,10 @@ permissions:
concurrency:
group: nightly-audit
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:
audit:
runs-on: [self-hosted, horizon-game]
+4
View File
@@ -15,6 +15,10 @@ on:
required: true
permissions:
contents: read
env:
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
HORIZON_TELEMETRY_URL: "off"
jobs:
parity:
runs-on: [self-hosted, horizon-game]
-55
View File
@@ -1,55 +0,0 @@
name: promote
# Beta game releases become stable once a day (docs/release-flow.md, "Channels"): at 20:00 UTC (21:00 in Paris in
# winter time, 22:00 in summer) tools/release_channels.py promotes the newest beta that had been out 6 hours by then,
# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Alpha
# channel install every beta when it is published; Stable gets the day's promotion. The later runs of the evening are
# retries for a run GitHub starts late or skips: they promote the same beta, so stable still moves once.
# By hand, from GitHub's app too (Actions > promote > Run workflow):
# gh workflow run promote -f tag=v0.2.3 # that beta now, without waiting for 20:00
# gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without its smoke test
# gh workflow run promote -f dry_run=true # say what would be promoted
# Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it
# still holds the betas published before it closed. The issue's text is never read (its author could edit it).
# When the oldest waiting beta is 30 hours old (it missed a promotion it was due for), an issue "Promotion to stable
# has stalled" says so; it closes itself after the next promotion.
on:
schedule:
- cron: '7,37 20-21 * * *'
workflow_dispatch:
inputs:
tag:
description: The beta to promote now (empty = the newest beta that is due)
type: string
default: ''
force:
description: Promote that tag even if a release-blocker covers it or its smoke test didn't run
type: boolean
default: false
dry_run:
description: Say what would be promoted, change nothing
type: boolean
default: false
permissions:
contents: write
issues: write
concurrency:
group: promote
cancel-in-progress: false
jobs:
promote:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
# The notes of a promoted release cover every pull request since the last stable one.
fetch-depth: 0
# gh uses GH_TOKEN below; nothing needs git credentials on disk.
persist-credentials: false
- name: Promote
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
FORCE: ${{ inputs.force && 'yes' || '' }}
DRY_RUN: ${{ (inputs.dry_run || github.ref != 'refs/heads/main') && 'yes' || '' }}
run: python3 tools/release_channels.py promote ${TAG:+--tag "$TAG"} ${FORCE:+--force} ${DRY_RUN:+--dry-run}
+25 -10
View File
@@ -3,12 +3,15 @@ name: release
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides:
# a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes
# ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now.
# RELEASES_PAUSED=1 (repository variable) stops them.
# RELEASES_PAUSED=1 (repository variable) stops them; so does an open issue labelled release-blocker, forced runs too.
# Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and
# Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then
# publishes vX.Y.Z on the release line in .github/release-line.txt (docs/versioning.md; without it, the dated
# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes
# stable in its daily promotion. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with
# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as the release and GitHub's latest: one
# channel, which launchers, `horizon-server update` and install.sh follow at once. So it is published only after the
# checks that used to gate a promotion pass in this run: the Mac mini's smoke test drew a world, and no release-blocker
# is open (tools/release_train.py gate); otherwise nothing is published. macOS: with the repository variable
# MACOS_SIGN_IDENTITY set, the programs are signed with
# Developer ID and the hardened runtime and the zip is notarized, from the runner's signing keychain
# (packaging/macos/README.md); unset (forks), ad hoc.
# gh workflow run release --ref <branch> # dry run: builds and notes, publishes nothing
@@ -32,6 +35,8 @@ on:
default: false
permissions:
contents: read
# The open release-blocker issues (decide).
issues: read
concurrency:
group: game-release
cancel-in-progress: false
@@ -203,7 +208,7 @@ jobs:
or not report.get("meshed_sections") or not report.get("player"):
sys.exit("the smoke run did not draw a world")
EOF
# Published with the release: a beta becomes stable only with it (tools/release_channels.py).
# Published with the release; the publish job checks it again before it publishes anything.
cp "$home/smoke.json" "$RUNNER_TEMP/smoke-test.json"
- uses: actions/upload-artifact@v4
if: runner.environment == 'self-hosted'
@@ -319,6 +324,7 @@ jobs:
timeout-minutes: 15
permissions:
contents: write
issues: read
steps:
- uses: actions/checkout@v4
with:
@@ -341,6 +347,17 @@ jobs:
run: |
key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)")
cargo run --locked --quiet -p horizon-release-sign -- verify --tag "$TAG" --publishing "${key[@]}" dist
- name: Ready to publish (the smoke test passed, no release-blocker is open)
# Right before publishing: an issue labelled while the builds ran still holds this release. A dry run only
# reports what a real run would do.
env:
GH_TOKEN: ${{ github.token }}
DRY_RUN: ${{ needs.decide.outputs.dry_run }}
run: |
if ! python3 tools/release_train.py gate --kind game --smoke dist/smoke-test.json --blockers; then
[[ "$DRY_RUN" == true ]] || { echo "::error::Nothing published"; exit 1; }
echo "::warning::A real run would publish nothing"
fi
- name: Publish ${{ needs.decide.outputs.tag }}
if: needs.decide.outputs.dry_run != 'true'
env:
@@ -348,17 +365,15 @@ jobs:
TAG: ${{ needs.decide.outputs.tag }}
run: |
signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig)
smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json)
# A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion
# (docs/release-flow.md).
# The release and the latest at once: there is one channel (docs/release-flow.md).
gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \
--notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \
--notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz \
dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \
dist/SHA256SUMS "${signature[@]}" "${smoke[@]}"
dist/SHA256SUMS "${signature[@]}" dist/smoke-test.json
- name: Dry run, the release that would be published
if: needs.decide.outputs.dry_run == 'true'
run: |
echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)"
echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }} as the release and latest: $(cat notes/title.txt)"
ls -l dist
- uses: actions/upload-artifact@v4
with:
+4
View File
@@ -11,6 +11,10 @@ permissions:
concurrency:
group: run-parity-${{ github.event.pull_request.number }}
cancel-in-progress: true
env:
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
HORIZON_TELEMETRY_URL: "off"
jobs:
parity:
if: github.event.label.name == 'run-parity'
+175
View File
@@ -0,0 +1,175 @@
# Horizon: a map for agents
Minecraft: Java Edition 26.3 rewritten in Rust (wgpu). Vanilla is the specification wherever it has the
feature. Read [CONTRIBUTING.md](CONTRIBUTING.md) once; this page tells you where things are.
Feature → files → harness for the most-changed areas: [docs/architecture.md](docs/architecture.md).
## Rules that bite
- **Never commit Mojang's files**: game jars, assets, decompiled source, prepared resources (`.local/`).
`tools/check_public_tree.py` rejects them; `git config core.hooksPath .githooks` runs it on commit.
- **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d`
folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and
`XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to
`~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`.
- **Mark what an agent posts.** A PR body starts with
`> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.` (issues: "Filed by", reviews:
"Review by"); every comment starts with `🤖 Agent:`. Never write as Ludovic.
- **Attribution.** Commits end with `Co-Authored-By: Claude <model> <noreply@anthropic.com>`; PR bodies end
with `🤖 Generated with [Claude Code](https://claude.com/claude-code)`.
- Everything players run is Rust. Python/Java only for dev tools and harness drivers in `tools/`.
- Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where
they would change the vanilla look.
- Small PRs (< ~500 lines). Labels: `feature` (players get something new), `skip-release` (they see no
change), none for a fix. Agents never add `release-now`: the maintainer decides it. Every merge to main ships
([docs/release-flow.md](docs/release-flow.md)).
- Contributors first: `gh pr list --state open --search <area>` before you start; never duplicate theirs.
## Crates
Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-server` are separate workspaces.
| Crate | Owns |
|---|---|
| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) |
| `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage |
| `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) |
| `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` |
| `horizon-assets` | Resource decoding: block-state and item models, baking, atlases |
| `horizon-prepare` | Builds `.local/horizon-client/26.3` from the player's own Minecraft install (runs the Java exporters) |
| `horizon-server` | `horizon-server`: `server.toml`, CLI, supervisor of the headless game ([docs/hosting.md](docs/hosting.md)) |
| `horizon-server-files` | `server.properties`, eula, ops/whitelist/bans, usercache |
| `horizon-friends`, `horizon-relay` | Play with Friends: invite codes, encrypted tunnel, the relay ([docs/play-with-friends.md](docs/play-with-friends.md)) |
| `horizon-shaderpack` | OptiFine/Iris packs: preprocessor, GLSL → WGSL ([docs/shader-packs.md](docs/shader-packs.md)) |
| `horizon-mods`, `horizon-mod-sdk`, `cargo-horizon-mod` | Sandboxed WebAssembly mods: runtime, SDK + WIT, `cargo horizon-mod` ([docs/mods.md](docs/mods.md)) |
| `horizon-port-pack` | Porting Java modpacks ([docs/modpacks.md](docs/modpacks.md)) |
| `horizon-theme` | Design tokens and fonts for the launcher, the game's own menus and the website |
| `horizon-telemetry`, `horizon-telemetry-server`, `horizon-bench` | Opt-in data collection, its ingest server, the benchmark report format |
| `horizon-dualsense`, `horizon-threads`, `horizon-release-sign`, `horizon-bots`, `voxel-kernels`, `xtask` | DualSense output, thread priorities, signed release checksums, load-test bots, occupancy kernels, repo tasks |
| `launcher/` | GPUI launcher: `main.rs` (UI), `backend.rs` (installs, updates), `cli.rs`, `mcp.rs`, `*_page.rs` |
Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m
unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles),
`website/` (playhorizon.dev; its paths are relative to `website/`), `docs/`, `.github/workflows/`.
## Build and test fast
```sh
python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests, harnesses; paste its block in the PR
python3 tools/pr_ready.py --quick # same without harnesses
cargo test -p horizon-client --lib --bins --tests # skips the 104 examples (pr_ready does this); `--doc` separately
cargo build --profile fast -p horizon-client # optimized, quick to link: use it to play or run lan_e2e
python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job)
python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them
python3 tools/parity.py mob_ai sculk # named harnesses
python3 tools/lan_e2e.py --check chest # two real games over LAN (host in-frame); --server-thread for the host on its server thread
python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
```
- Harnesses and the game need the vanilla data in `.local/` (`minecraft/`, `horizon-client/26.3`, `datagen/`,
`tools/`): see [docs/parity-workflow.md](docs/parity-workflow.md). Without it, pr_ready lists the
harnesses for CI.
- A harness = `tools/test_<name>_parity.py` (324 of them) + a Java oracle (`mods/horizon/src/test/java/dev/horizonlab/parity/Vanilla*Oracle.java`)
+ a Rust probe: `crates/<crate>/examples/<name>_{probe,fixture}.rs` (horizon-world 175, horizon-client 104),
or the game binary with a fixture env var (`game/dispense_fixture.rs`, `game/sculk_fixture.rs`,
`game/command_harness.rs`, `game/net_harness.rs`). Copy a nearby harness for a new one.
- Probes build into `.local/parity-target/`; harnesses find binaries via `lab.cargo_target()`, never `target/`.
- What a change reruns (of 329 harnesses, measured 2026-10-23): a file of the game binary (`game.rs`, `game/`)
~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`.
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):
`target/fast/horizon-ctl --socket $PWD/ctl.sock launch --world W --creative --offscreen --wait --resources $PWD/.local/horizon-client/26.3`,
then `horizon-ctl --socket … state|keys|turn|command|screenshot|quit`
([docs/horizon-ctl-commands.md](docs/horizon-ctl-commands.md)).
## Vanilla reference
- Decompiled sources: `.local/minecraft/26.3/sources/{client,server}/` (`python3 tools/lab.py decompile`).
- Bytecode queries (callers through lambdas, every overload):
`python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom`
([docs/decompilation-status.md](docs/decompilation-status.md)).
- A harness runs the oracle against the real 26.3 jars and the Rust probe on the same inputs, then compares
their JSON. Oracle runs are cached by `tools/parity_shim.py`; `--fresh` reruns them.
- Mirror vanilla's `Math` calls with `horizon_core::jmath`, and vanilla's RNG with `horizon_core::random`:
random draws must happen in vanilla's order.
## horizon-client: where things live
`L:` = lib (`crates/horizon-client/src/`), `G:` = bin (`crates/horizon-client/src/game/`). The lib can't see
`Game`; bin code reaches the lib as `horizon_client::<module>`.
| Subsystem | Files |
|---|---|
| Game loop, tick, frame | `game.rs`: `fn run`, `impl ApplicationHandler for Game` (`window_event`, `about_to_wait`), `fn tick`, `fn tick_world`, `fn render`; L: `clock.rs`, `window.rs`, `spans.rs` |
| Rendering | L: `gfx.rs` (`Renderer::new`, `Renderer::render`), `gfx/` (cull, occlusion, translucency, upload, timing, lod, weather, stars, end_sky), `*.wgsl`, `particles.rs`, `block_entity_render.rs`, `item_render.rs`, `fog.rs`, `clouds.rs`, `camera.rs`, `first_person.rs`; G: `render_tick.rs`, `item_draw.rs` |
| Chunks, streaming, light | L: `streaming.rs` (worker pool: generate, light, mesh), `world.rs`, `chunk.rs`, `chunk_map.rs`, `light.rs`, `mesher.rs` + `mesher/`, `vanillagen.rs` (binds horizon-world's generator), `lod.rs` + `lod/`, `ticket_levels.rs`; G: `world_loading.rs`, `postprocess.rs`; game.rs `fn update_world` |
| World generation | `crates/horizon-world/src/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `carver/`) |
| Block behaviour | `crates/horizon-world/src/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `redstone.rs`, `place.rs`, `interact.rs`); game.rs `fn tick_blocks`, `fn process_level_events` |
| Mobs | L: `mobs.rs` (types), `mobs/` (`ai.rs`, `goals.rs`, `brain.rs`, `*_brain.rs`, `nav.rs`, `path.rs`, `species.rs`, `spawning.rs`, `render.rs`, `anim.rs`); G: `creatures.rs` (ticking, spawning, mob events), one file per mob family (`dragon.rs`, `wither.rs`, `villagers.rs`, `piglins.rs`, `golems.rs`...), `natural_spawning.rs` |
| Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` |
| Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` |
| Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` |
| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` |
| UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` |
| Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) |
| LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) |
| Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` |
| Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` |
| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` |
| Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` |
| Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` |
| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` |
| Shader packs | L: `shader_pack.rs` (Horizon WGSL packs), `java_pack.rs` + crate `horizon-shaderpack` (Iris/OptiFine), `gfx/pack_stages.rs`, `gfx/java_stages.rs`; G: `shader_packs.rs` |
| Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) |
| Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` |
| Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` |
## How `Game` is organised
- `struct Game` (game.rs, ~290 fields) holds everything. Its methods are spread over ~180 files: game.rs keeps
the core (tick, render, input, inventory, world open/close) and each `game/<feature>.rs` adds an
`impl Game<'_>` block for one feature, with its own state types. Fields are private to the bin.
- Find a feature's code: `grep -rn "fn tick_<thing>\|fn <verb>_<thing>" crates/horizon-client/src/game*`;
the file is usually `game/<thing>s.rs`. Who calls it: grep the name in game.rs's `fn tick` / `fn tick_world`.
- Fields that say which mode runs: `remote` (this window is a client of a server: multiplayer, LAN guest, or
single player on its server thread), `lan` (`LanHost`: this world is open to the network), `integrated`
(the window's own server thread), `serving` (this `Game` *is* that server thread), `options.dedicated`.
`fn tick` returns `tick_remote()` when `remote` is set; nothing else of the local simulation runs.
- A server's players run through the same gameplay code as the local player: `as_guest` swaps the guest's
state (position, inventory, mode, mining, item use) into `Game` for one call (`game/lan_actions.rs`), and
`levels.rs` swaps whole dimensions in the same way. Changes reach clients through the block log, level
events and the entity tracker (`lan/tracking.rs`, `game/lan_entities.rs`).
- Shared read-only data: `Resources` (`res`: blocks, items, recipes, mob types, biomes) and `PackResources`
(`pack`), both in game.rs.
## The two single-player paths
1. **In-frame (default since #1428):** the window's `Game` ticks the world itself, one level that follows
the player (`fn enter_dimension`). This is what Stable players run and what harnesses test.
2. **Server thread (`--server-thread` or `HORIZON_SERVER_THREAD=1`):** `game/integrated.rs` runs a second
`Game` (`serving`) on a "Server thread" with one level per dimension; the window joins it as a client
through memory (`remote`), exactly as a LAN guest or a dedicated server's player does. Not at parity yet:
open `[server-thread]` issues list the gaps.
LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths
when you touch player-facing gameplay:
```sh
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # in-frame
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --server-thread # server thread
python3 tools/lan_e2e.py --check <name> # host in-frame, guest is a server client
python3 tools/lan_e2e.py --server-thread --check <name> # host on its server thread (portals, levels, distance, lava need it)
python3 tools/parity.py dedicated_server server_entities server_player_damage
```
## Docs worth knowing
[docs/parity-workflow.md](docs/parity-workflow.md) (runner, gate, shards, scopes) ·
[docs/native-client.md](docs/native-client.md) (options, controls, horizon-ctl) ·
[docs/server-levels.md](docs/server-levels.md) (levels per dimension) ·
[docs/rust-parity.md](docs/rust-parity.md) (what is ported) · [docs/known-issues.md](docs/known-issues.md) ·
[docs/release-flow.md](docs/release-flow.md) · [docs/README.md](docs/README.md) (index).
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Generated
+1
View File
@@ -1395,6 +1395,7 @@ dependencies = [
name = "horizon-bench"
version = "0.1.0"
dependencies = [
"horizon-telemetry",
"serde",
"serde_json",
]
+3 -3
View File
@@ -46,7 +46,7 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these.
- **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status).
- **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings).
- **Resource packs, shader packs and data packs:** resource packs work, Java shader packs run their full-screen effects (experimental), and data packs load functions, predicates and item modifiers.
- **Playing with others:** invite friends from the pause menu with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
- **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods).
Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders:
@@ -56,8 +56,8 @@ Screenshots, captured in the Rust client itself with vanilla assets and no mods
<td colspan="2"><img src="docs/media/sunset.webp" alt="Sunset over a savanna river valley and a plains village"></td>
</tr>
<tr>
<td width="50%"><img src="docs/media/menu-title.webp" alt="Horizon's title screen over a veiled snowy landscape"></td>
<td width="50%"><img src="docs/media/settings.webp" alt="The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs"></td>
<td width="50%"><img src="docs/media/survival.webp" alt="Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience"></td>
<td width="50%"><img src="docs/media/settings.webp" alt="Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs"></td>
</tr>
<tr>
<td width="50%"><img src="docs/media/village.webp" alt="A plains village among savanna hills, with farms, villagers and an iron golem"></td>
+12
View File
@@ -36,3 +36,15 @@ SOFTWARE.
developers, with one upstream fix applied
([gfx-rs/wgpu#10124](https://github.com/gfx-rs/wgpu/pull/10124)). It is licensed under MIT or
Apache-2.0; both licenses are in that folder (`LICENSE.MIT`, `LICENSE.APACHE`).
## Pixelify Sans
`crates/horizon-theme/fonts/PixelifySans-*.ttf` is [Pixelify Sans](https://github.com/eifetx/Pixelify-Sans)
by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1.1
(`crates/horizon-theme/fonts/OFL-PixelifySans.txt`).
## Pixelarticons
`crates/horizon-theme/icons/pixel/*.svg` are icons from
[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT
license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`).
+2
View File
@@ -8,3 +8,5 @@ description = "The benchmark report format (docs/benchmark-report.md), shared by
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# The hardware probes shared with telemetry (cores, clocks, drive, VRAM, power, form).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
+51 -19
View File
@@ -16,8 +16,22 @@ pub struct Hardware {
pub cpu: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu_threads: Option<usize>,
/// Physical cores.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu_cores: Option<u16>,
/// Base and top boost clock, where the OS gives them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu_base_mhz: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu_boost_mhz: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ram_mb: Option<u64>,
/// The drive under the game folder: `nvme`, `ssd` or `hdd`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub storage: Option<String>,
/// `laptop` or `desktop`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub form: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gpu: Option<Gpu>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -33,6 +47,9 @@ pub struct Gpu {
pub backend: String,
/// `integrated`, `discrete`, `virtual`, `cpu`, `other`.
pub kind: String,
/// Its own memory in MiB (rounded to 256), for a discrete GPU whose driver says.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vram_mb: Option<u32>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -47,17 +64,50 @@ pub struct Display {
impl Hardware {
pub fn detect() -> Hardware {
let probes = probes();
Hardware {
os: std::env::consts::OS.to_owned(),
os_version: os_version(),
arch: std::env::consts::ARCH.to_owned(),
cpu: cpu(),
cpu_threads: std::thread::available_parallelism().ok().map(|n| n.get()),
cpu_cores: probes.cores,
cpu_base_mhz: probes.base,
cpu_boost_mhz: probes.boost,
ram_mb: ram_bytes().map(|b| b >> 20),
storage: None,
form: probes.form,
gpu: None,
display: None,
}
}
/// [`Hardware::detect`] with the kind of drive `game_dir` is on.
pub fn detect_in(game_dir: &std::path::Path) -> Hardware {
Hardware {
storage: horizon_telemetry::system::storage(game_dir).map(str::to_owned),
..Hardware::detect()
}
}
}
/// What the telemetry probes read (`horizon_telemetry::system`).
struct Probes {
cores: Option<u16>,
base: Option<u32>,
boost: Option<u32>,
form: Option<String>,
}
fn probes() -> Probes {
let s = horizon_telemetry::payload::System::detect();
let some = |n: u32| (n > 0).then_some(n);
Probes {
cores: (s.cores > 0).then_some(s.cores),
base: some(s.cpu_base_mhz),
boost: some(s.cpu_boost_mhz),
form: (!s.form.is_empty()).then_some(s.form),
}
}
/// The one-minute load average: above about the number of threads the machine was busy.
@@ -82,25 +132,7 @@ pub fn load_average() -> Option<f64> {
/// `ac` or `battery`; `None` where it can't be read (and on machines without a battery on Linux).
pub fn power_source() -> Option<&'static str> {
if cfg!(target_os = "macos") {
let batt = output("pmset", &["-g", "batt"])?;
return Some(if batt.contains("'Battery Power'") {
"battery"
} else {
"ac"
});
}
let mut on_battery = None;
for entry in std::fs::read_dir("/sys/class/power_supply").ok()?.flatten() {
let read =
|name: &str| std::fs::read_to_string(entry.path().join(name)).unwrap_or_default();
match read("type").trim() {
"Mains" if read("online").trim() == "1" => return Some("ac"),
"Battery" => on_battery = Some("battery"),
_ => {}
}
}
on_battery
horizon_telemetry::system::power()
}
/// Resident memory of a process, in bytes (macOS, Linux).
+3 -1
View File
@@ -30,7 +30,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = { version = "1.0.151", features = ["raw_value"] }
# Shader packs: pack.toml, and WGSL checked before it reaches wgpu.
toml = "1.1"
naga = { version = "30.0.1", features = ["wgsl-in"] }
# hlsl-out: the gfx.rs tests translate every shader as wgpu's DirectX 12 backend does. A normal feature,
# not a dev-dependency's, so builds, tests and examples share one build of naga, wgpu and this crate.
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] }
# Java (OptiFine/Iris) shader packs, translated to WGSL.
horizon-shaderpack = { path = "../horizon-shaderpack" }
# Sound (ALSA on Linux); the `audio` feature.
@@ -1,7 +1,7 @@
//! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the
//! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line;
//! the `#resources` line names the prepared resources for en_us).
use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language};
use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines};
use std::{error::Error, fmt::Write, path::PathBuf};
fn main() -> Result<(), Box<dyn Error>> {
@@ -12,8 +12,9 @@ fn main() -> Result<(), Box<dyn Error>> {
.find_map(|l| l.strip_prefix("#resources "))
.map(PathBuf::from)
.ok_or("no #resources line")?;
let language = Language::load(&[&root], "en_us");
let translate = |key: &str| language.get(key).map(str::to_owned);
// Use the inventory's filtered translations so missing tooltip keys are caught.
let enchantments = Enchantments::load(&root);
let translate = |key: &str| enchantments.translate(key).map(str::to_owned);
let mut output = String::new();
for line in input.lines().filter(|l| !l.starts_with('#')) {
let stack = parse_stack(line)?.ok_or("empty stack")?;
@@ -14,13 +14,22 @@ fn main() {
for count in [0, 1, 4, 64] {
let mut slot = Some(ItemStack::new("minecraft:stone", count));
let mut dropped = 0;
let mut swings = 0;
let mut packets = 0;
for _ in 0..2 {
if let Some(stack) =
take_held_drop(&mut slot, all, mode == GameMode::Spectator)
{
dropped += stack.count;
swings += 1;
}
println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped);
if mode != GameMode::Spectator {
packets += 1;
}
println!(
"{} {dropped} {swings} {packets}",
slot.as_ref().map_or(0, |s| s.count),
);
}
}
}
@@ -1133,7 +1133,7 @@ fn main() -> horizon_client::Result<()> {
}
#[allow(unused_mut)] // filled only with the rng-trace feature
let mut traces: Vec<String> = Vec::new();
let mut pushes = Vec::new();
let mut pushes = horizon_client::mobs::PendingPushes::default();
let mut born = Vec::new();
for i in 0..mobs.len() {
if mobs[i].removed {
@@ -111,6 +111,8 @@ struct World<'a> {
slime: f32,
starts: Vec<Start>,
players: Vec<([f64; 3], String)>,
/// Where the non-spectators among them are.
nearest: Vec<[f64; 3]>,
respawn: Option<[i32; 3]>,
unloaded: HashSet<(i32, i32)>,
spawn_mobs: bool,
@@ -302,19 +304,8 @@ impl NaturalLevel for World<'_> {
fn structure_spawns(&self) -> &StructureSpawns {
self.s.structures
}
fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option<f64> {
let mut best: Option<f64> = None;
for (p, mode) in &self.players {
if mode == "spectator" {
continue;
}
let d = [p[0] - x, p[1] - y, p[2] - z];
let d = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if best.is_none_or(|b| d < b) {
best = Some(d);
}
}
best
fn nearest_player_positions(&self) -> &[[f64; 3]] {
&self.nearest
}
fn respawn(&self) -> Option<[i32; 3]> {
self.respawn
@@ -730,6 +721,11 @@ fn main() -> horizon_client::Result<()> {
dimension_id: dimension_id.clone(),
slime: get("slime", "0.0").parse()?,
starts,
nearest: players
.iter()
.filter(|(_, mode)| mode != "spectator")
.map(|(p, _)| *p)
.collect(),
players,
respawn,
unloaded,
@@ -0,0 +1,132 @@
//! Random-tick sections companion for tools/test_random_tick_sections_parity.py:
//! the game's `RandomTickSections` choosing the sections of a chunk that
//! `Behaviours::tick_chunk_random` ticks, after the case's edits (see
//! VanillaRandomTickSectionsOracle for the format; the `#resources` line names
//! the prepared resources). The level the ticks run against reads as air
//! everywhere, so nothing ticks for real: its reads are the drawn positions.
use horizon_client::{
blocks::BlockFacts,
chunk::{Chunk, MIN_Y, Section},
random_tick_sections::RandomTickSections,
};
use horizon_core::{
position::{BlockPos, ChunkPos},
random::LegacyRandom,
};
use horizon_world::{
fluid::FluidKind,
level::{GameRules, LevelAccess, LevelEvent, Ticks, data},
registry::BlockStateId,
};
use std::{cell::RefCell, error::Error, fmt::Write, path::PathBuf, sync::Arc};
struct Air {
reads: RefCell<Vec<BlockPos>>,
random: LegacyRandom,
speed: i32,
}
impl LevelAccess for Air {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.reads.borrow_mut().push(pos);
BlockStateId(0)
}
fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option<BlockStateId> {
None
}
fn is_loaded(&self, _: BlockPos) -> bool {
true
}
fn random(&mut self) -> &mut LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
0
}
fn game_rules(&self) -> GameRules {
GameRules {
random_tick_speed: self.speed,
..Default::default()
}
}
fn emit(&mut self, _: LevelEvent) {}
}
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = std::env::args().collect();
let input = std::fs::read_to_string(&args[1])?;
let root = input
.lines()
.find_map(|l| l.strip_prefix("#resources "))
.map(PathBuf::from)
.ok_or("no #resources line")?;
let registry = data::load_registry(&root)?;
let (facts, behaviours) = BlockFacts::load_pair(&root, &registry)?;
let mut output = String::new();
for line in input.lines().filter(|l| !l.starts_with('#')) {
let mut words = line.split(' ');
let mut ticks = Ticks::new(0);
ticks.random_tick_value = words.next().ok_or("no randValue")?.parse()?;
let mut level = Air {
reads: RefCell::default(),
random: LegacyRandom::new(0),
speed: words.next().ok_or("no speed")?.parse()?,
};
let mut chunk = Arc::new(Chunk::empty(0, 0));
let mut cache = RandomTickSections::default();
for word in words {
let op: Vec<&str> = word.split(':').collect();
let int = |i: usize| -> Result<i32, Box<dyn Error>> { Ok(op[i].parse()?) };
match op[0] {
"s" => {
let (section, index) = (int(1)?, int(2)?);
Arc::make_mut(&mut chunk).set(
index & 15,
MIN_Y + section * 16 + (index >> 8),
index >> 4 & 15,
int(3)? as u32,
);
}
"f" => {
let (a, b, m) = (int(2)? as u32, int(3)? as u32, int(4)? as usize);
let values = std::array::from_fn(|i| if i % m == m - 1 { b } else { a });
Arc::make_mut(&mut Arc::make_mut(&mut chunk).sections[int(1)? as usize])
.blocks = Section::from_blocks(&values);
}
"t" => {
output.push('|');
level.reads.borrow_mut().clear();
behaviours.tick_chunk_random(
&mut level,
&mut ticks,
ChunkPos::new(0, 0),
|_, from| cache.get((0, 0), &chunk, &facts).from(from),
);
for pos in level.reads.borrow().iter() {
let state = chunk.block(pos.x, pos.y, pos.z);
let fluid = matches!(
behaviours.fluid(state).kind(),
FluidKind::Lava | FluidKind::FlowingLava
);
write!(
output,
" {},{},{},{}{}",
pos.x,
pos.y,
pos.z,
if behaviours.is_randomly_ticking(state) {
'B'
} else {
'-'
},
if fluid { 'F' } else { '-' },
)?;
}
}
other => return Err(format!("unknown op {other}").into()),
}
}
writeln!(output, " | {}", ticks.random_tick_value)?;
}
std::fs::write(&args[2], output)?;
Ok(())
}
@@ -3,6 +3,7 @@
//! what the render thread pays for it in `Streaming::update`.
//!
//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F]
//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z]
//!
//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x
//! at that speed for T seconds while frames run at F per second. Each phase reports
@@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn cpu_seconds() -> f64 {
std::fs::read_to_string("/proc/self/stat")
.ok()
.and_then(|stat| {
let fields = stat
.rsplit_once(')')?
.1
.split_whitespace()
.collect::<Vec<_>>();
Some((fields[11].parse::<f64>().ok()? + fields[12].parse::<f64>().ok()?) / 100.0)
})
.unwrap_or(0.0)
}
#[derive(Default)]
struct Phase {
updates: Vec<f64>,
local: (u64, u64),
uploads: usize,
stage_samples: [u64; 7],
cpu_start: f64,
}
impl Phase {
fn update(&mut self, streaming: &mut Streaming, world: &mut World) {
if self.updates.is_empty() {
self.cpu_start = cpu_seconds();
}
let before = LOCAL.with(Cell::get);
let started = Instant::now();
let (uploads, _) = streaming.update(world);
@@ -89,6 +109,9 @@ impl Phase {
self.local.1 += after.1 - before.1;
self.uploads += uploads.len();
drop(uploads);
for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) {
*sum += count as u64;
}
}
fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) {
let mut sorted = self.updates.clone();
@@ -106,6 +129,16 @@ impl Phase {
at(0.99),
sorted.last().copied().unwrap_or(0.0),
);
println!(
"BENCH {}",
serde_json::json!({
"phase": name, "wall_s": wall.as_secs_f64(),
"cpu_s": cpu_seconds() - self.cpu_start,
"chunks": streaming.generated_total - generated, "sections": self.uploads,
"updates": self.updates.len(), "update_ms": total,
"mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64),
})
);
if TRACK {
println!(
" update allocations: {} ({:.1} MiB)",
@@ -142,6 +175,22 @@ fn main() -> Result<()> {
let fly = flag("--fly", 0.0);
let seconds = flag("--seconds", 10.0);
let hz = flag("--hz", 240.0);
let dimension = args
.iter()
.position(|a| a == "--dimension")
.and_then(|i| args.get(i + 1))
.map(|d| {
if d.contains(':') {
d.clone()
} else {
format!("minecraft:{d}")
}
})
.unwrap_or_else(|| "minecraft:overworld".into());
let center = (
flag("--center-x", 0.0) as i32,
flag("--center-z", 0.0) as i32,
);
let assets = Arc::new(Assets::load(&root)?);
let render = Arc::new(assets.reload(&root)?);
@@ -154,11 +203,12 @@ fn main() -> Result<()> {
models::load_visibility(&root, assets.registry)?,
)?);
let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?);
let terrain = Arc::new(VanillaTerrain::new(
let terrain = Arc::new(VanillaTerrain::for_dimension(
&root.join("worldgen"),
assets.registry,
&biomes,
seed,
&dimension,
)?);
let context = Arc::new(WorkerContext {
assets,
@@ -170,8 +220,12 @@ fn main() -> Result<()> {
let mut world = World::new(facts.air, seed);
let mut streaming = Streaming::new(terrain, context, threads);
streaming.radius = radius;
streaming.center = (0, 0);
println!("{threads} workers, radius {radius}, seed {seed}");
streaming.center = center;
streaming.nether_shading = dimension == "minecraft:the_nether";
streaming.sky_light = dimension != "minecraft:the_nether";
println!(
"{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}"
);
let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed));
// Fill: update as often as the game would uncapped, until settled.
@@ -198,12 +252,12 @@ fn main() -> Result<()> {
let mut behind = Vec::new();
while started.elapsed().as_secs_f64() < seconds {
let next = Instant::now() + frame;
let x = (started.elapsed().as_secs_f64() * fly) as i32;
streaming.center = (x, 0);
let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32;
streaming.center = (x, center.1);
phase.update(&mut streaming, &mut world);
// Columns within 2 chunks of the player still missing their meshes.
let near = (-2..=2)
.flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz)))
.flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz)))
.filter(|&(cx, cz)| !streaming.is_lit(cx, cz))
.count();
behind.push(near);
@@ -11,6 +11,7 @@ fn bits(value: f32) -> String {
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let mut output = String::new();
let mut parameters = weather::ParameterCache::default();
for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() {
let p: Vec<&str> = line.split_whitespace().collect();
let int = |i: usize| p[i].parse::<i32>().unwrap();
@@ -38,6 +39,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
bits(column.v_offset),
column.light_coords
)?;
assert_eq!(
parameters
.get(x, z)
.column(kind != 0, ticks, x, bottom, top, z, light, partial),
column,
"cached parameters differ from original random source at case {case}"
);
let max_alpha = if kind == 0 { 1.0 } else { 0.8 };
for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) {
write!(
@@ -22,6 +22,11 @@ impl PlayerMotion {
pub fn refresh_attributes(&mut self) -> Result<()> {
live_updates::refresh(self)
}
/// `Player.internalSetAbsorptionAmount`: the amount as given, unclamped
/// (the saved `AbsorptionAmount`, or what a client's server sent).
pub fn internal_set_absorption(&mut self, value: f32) -> Result<()> {
self.store_absorption(value)
}
}
impl HealthWorld for PlayerMotion {
type Error = Box<dyn std::error::Error>;
+19
View File
@@ -140,7 +140,22 @@ fn run(control: &Control, setup: Setup) -> Result<PathBuf, String> {
driver: text(&renderer["driver"]),
backend: text(&renderer["backend"]).to_lowercase(),
kind: text(&renderer["device_type"]),
vram_mb: None,
});
if let Some(gpu) = report.hardware.gpu.as_mut() {
let vendor = horizon_telemetry::system::gpu_vendor(&gpu.name, 0);
let vendor = if gpu.vendor.is_empty() {
vendor
} else {
gpu.vendor.as_str()
}
.to_owned();
if gpu.kind.contains("iscrete") {
gpu.vram_mb = horizon_telemetry::system::vram_mb(&vendor);
}
}
report.hardware.storage =
horizon_telemetry::system::storage(&setup.game_dir).map(str::to_owned);
report.hardware.display = serde_json::from_value(title["display"].clone()).ok();
replace_world(&setup.game_dir)?;
@@ -224,6 +239,10 @@ fn run(control: &Control, setup: Setup) -> Result<PathBuf, String> {
let status = control.status();
let renderer = &status["renderer"];
// On Wayland the window is on a screen only once it has been shown: ask again.
if report.hardware.display.is_none() {
report.hardware.display = serde_json::from_value(status["display"].clone()).ok();
}
let c = &mut report.conditions;
c.scenario = Some(setup.scenario.clone());
c.seed = Some(SEED.to_string());
@@ -32,16 +32,18 @@ pub enum Group {
Move,
Act,
Screens,
Multiplayer,
World,
Scripting,
}
impl Group {
pub const ALL: [Group; 7] = [
pub const ALL: [Group; 8] = [
Group::Session,
Group::Observe,
Group::Move,
Group::Act,
Group::Screens,
Group::Multiplayer,
Group::World,
Group::Scripting,
];
@@ -52,6 +54,7 @@ impl Group {
Group::Move => "Move and look",
Group::Act => "Act on the world",
Group::Screens => "Screens, menus and chat",
Group::Multiplayer => "Multiplayer, LAN and friends",
Group::World => "World and cheats",
Group::Scripting => "Scripting and benchmarks",
}
@@ -117,6 +120,50 @@ const OVER: Param = flag(
"turn with mouse motion spread over this many seconds (eased), as a player would",
);
const FACE: Ty = Ty::Enum(&["down", "up", "north", "south", "west", "east"]);
const BOX: [Param; 6] = [
p("x1", Ty::Int, "corner X"),
p("y1", Ty::Int, "corner Y"),
p("z1", Ty::Int, "corner Z"),
p("x2", Ty::Int, "opposite X"),
p("y2", Ty::Int, "opposite Y"),
p("z2", Ty::Int, "opposite Z"),
];
const PAGES: Ty = Ty::Enum(&[
"main",
"video",
"sound",
"controls",
"keybinds",
"controller",
"controller-binds",
"mouse",
"chat",
"accessibility",
"language",
"font",
"packs",
"mods",
"graphics",
"graphics-advanced",
"extras",
"horizon",
"shader-packs",
"agent",
]);
/// `--confirm`, required by destructive commands: the player agreed.
const CONFIRM: Param = Param {
name: "confirm",
ty: Ty::Bool,
required: true,
flag: true,
help: "true once the player agreed: it cannot be undone",
};
/// MCP tools that delete or overwrite the player's things (`destructiveHint`).
pub const DESTRUCTIVE: &[&str] = &["world-delete", "fill", "setblock"];
/// MCP tools that reach other players or the network (`openWorldHint`): only when the player asks.
pub const OPEN_WORLD: &[&str] = &["connect", "lan", "friends", "chat", "command"];
macro_rules! cmd {
($name:expr, $group:ident, $usage:expr, $summary:expr, $details:expr, [$($ex:expr),* $(,)?], $params:expr, mcp: $mcp:expr, local: $local:expr $(, wire: $wire:expr)?) => {
@@ -164,7 +211,19 @@ pub const COMMANDS: &[Cmd] = &[
&[flag("lines", Ty::Int, "how many lines of latest.log (default 100)"), flag("crash", Ty::Bool, "the newest crash report instead")],
mcp: true, local: true),
cmd!("status", Session, "status", "game, renderer and streaming state (the scripting socket's original summary)",
"", ["horizon-ctl status"], &[], mcp: false, local: false),
"Also what F3 shows: the overlay flags, the renderer, chunk streaming and memory.", ["horizon-ctl status"], &[], mcp: true, local: false),
cmd!("worlds", Session, "worlds", "the saved worlds, newest first: folder, name, mode, last played, version",
"folder is what open, world-rename, world-backup and world-delete take.", ["horizon-ctl worlds"], &[], mcp: true, local: false),
cmd!("world-rename", Session, "world-rename FOLDER NAME", "rename a world, as Edit World does (its folder stays)",
"Needs the title screen (no world open).", ["horizon-ctl world-rename Test \"My Base\""],
&[p("folder", Ty::Str, "world folder from worlds"), p("name", Ty::Rest, "the new name")], mcp: true, local: false),
cmd!("world-backup", Session, "world-backup FOLDER", "zip a world into backups/, as Edit World's Make Backup does",
"Needs the title screen. Replies once the zip is written, with its size.", ["horizon-ctl world-backup Test"],
&[p("folder", Ty::Str, "world folder from worlds")], mcp: true, local: false),
cmd!("world-delete", Session, "world-delete FOLDER --confirm", "delete a world for good, as Select World's Delete does",
"Needs the title screen and --confirm: ask the player first, it cannot be undone (world-backup keeps a copy).",
["horizon-ctl world-delete Test --confirm"],
&[p("folder", Ty::Str, "world folder from worlds"), CONFIRM], mcp: true, local: false),
cmd!("open", Session, "open WORLD [SEED] [creative]", "open or create a world from the title screen",
"Opens saves/WORLD, creating it with SEED (and creative mode) when it doesn't exist.",
["horizon-ctl open Test 12345", "horizon-ctl open Build 0 creative"],
@@ -190,10 +249,10 @@ pub const COMMANDS: &[Cmd] = &[
cmd!("light", Observe, "light X1 Y1 Z1 X2 Y2 Z2", "the stored sky and block light of a box",
"At most 32768 blocks per request. One hex digit per block in `sky` and `block`, x fastest, then z, then y; `.` where no chunk is loaded.",
["horizon-ctl light 0 64 0 15 70 15"],
&[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false),
&BOX, mcp: true, local: false),
cmd!("blocks", Observe, "blocks X1 Y1 Z1 X2 Y2 Z2", "the non-air blocks of a box, with counts per block",
"At most 32768 blocks per request.", ["horizon-ctl blocks 0 60 0 15 70 15"],
&[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false),
&BOX, mcp: true, local: false),
cmd!("find-block", Observe, "find-block BLOCK [RADIUS]", "the nearest loaded blocks of a kind",
"Searches a cube of RADIUS (default 32, at most 64) around the player; returns the count and the 16 nearest.",
["horizon-ctl find-block oak_log", "horizon-ctl find-block diamond_ore 48"],
@@ -264,12 +323,15 @@ pub const COMMANDS: &[Cmd] = &[
"down holds the key until key ... up, release or stop; wait does not release it. move, goto, jump, break and the other actions release the movement keys when they end.",
["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap", "repeat"]), "what to do")], mcp: true, local: false),
cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "",
["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false),
["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: true, local: false),
cmd!("interact-entity", Act, "interact-entity ID", "right-click an entity: trade with a villager, mount a horse, ride a boat, shear a sheep",
"Faces the entity (from entities), right-clicks it with the held item, waits two ticks and replies with the screen.",
["horizon-ctl interact-entity 42"], &[p("id", Ty::Int, "entity id from entities")], mcp: true, local: true),
cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them",
"Buttons by position: south east west north lb rb lt rt select start ls rs up down left right (south is Xbox A / PlayStation cross). Sticks run -1..1 with up positive and stay tilted until centred; triggers 0..1. Merged with any real controller; status lists the connected ones and what is held.",
["horizon-ctl pad south tap", "horizon-ctl pad stick left 0 1", "horizon-ctl pad trigger right 1", "horizon-ctl pad status"],
&[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: false, local: false),
cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false),
&[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: true, local: false),
cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: true, local: false),
cmd!("stop", Act, "stop", "cancel the running action (goto, break...) and release every key", "", ["horizon-ctl stop"], &[], mcp: true, local: false),
// Screens
cmd!("open-inventory", Screens, "open-inventory", "open the inventory screen (crafting grid 100-103, result 200)", "",
@@ -317,7 +379,31 @@ pub const COMMANDS: &[Cmd] = &[
cmd!("respawn", Screens, "respawn", "respawn from the death screen", "", ["horizon-ctl respawn"], &[], mcp: true, local: false),
cmd!("pause", Screens, "pause", "open the pause menu", "", ["horizon-ctl pause"], &[], mcp: true, local: false),
cmd!("resume", Screens, "resume", "leave the pause menu", "", ["horizon-ctl resume"], &[], mcp: true, local: false),
cmd!("options", Screens, "options [PAGE]", "open the options screen, or one of its pages (Horizon's too)",
"Then ui lists its widgets and click, set and type change them, as with the mouse. options-set changes an options.txt value without the screen.",
["horizon-ctl options video", "horizon-ctl options horizon"], &[opt("page", PAGES, "the page (default: the main options)")], mcp: true, local: false),
cmd!("book", Screens, "book [next|back|take|done]", "the open book or lectern: its page text, or press one of its buttons",
"", ["horizon-ctl book", "horizon-ctl book next"], &[opt("action", Ty::Enum(&["next", "back", "take", "done"]), "a button to press")], mcp: true, local: false),
cmd!("signedit", Screens, "signedit X Y Z [front|back]", "open the sign editor of the sign at X Y Z (then type and close)",
"", ["horizon-ctl signedit 3 64 1"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("side", Ty::Enum(&["front", "back"]), "which side")], mcp: true, local: false),
cmd!("mount-menu", Screens, "mount-menu", "open the inventory of the horse, donkey, mule or llama being ridden",
"As the inventory key does while riding; also opens the nearest one's.", ["horizon-ctl mount-menu"], &[], mcp: true, local: false),
cmd!("chat-log", Screens, "chat-log [N]", "the newest N chat messages", "", ["horizon-ctl chat-log 5"], &[], mcp: false, local: false),
// Multiplayer
cmd!("connect", Multiplayer, "connect ADDRESS [NAME]", "join a multiplayer server, or a friend's world by its invite code, from the title screen",
"ADDRESS is HOST[:PORT], or friend:CODE for an invite code. Only when the player asks: it reaches the network.",
["horizon-ctl connect play.example.net", "horizon-ctl connect localhost:25565", "horizon-ctl connect friend:0B33K-Q405Q-..."],
&[p("address", Ty::Str, "HOST[:PORT] or friend:CODE"), opt("name", Ty::Str, "player name when offline")], mcp: true, local: false),
cmd!("disconnect", Multiplayer, "disconnect", "leave the server, back to the server list", "", ["horizon-ctl disconnect"], &[], mcp: true, local: false),
cmd!("servers", Multiplayer, "servers", "the Multiplayer screen's server list: name and address",
"Add, edit and remove them on the Multiplayer screen (click-button Multiplayer, then ui).", ["horizon-ctl servers"], &[], mcp: true, local: false),
cmd!("lan", Multiplayer, "lan open [PORT] [commands] [force] | lan close | lan status", "open the world to LAN (Open to LAN), stop, or see the guests",
"PORT 0 or none picks one; commands lets guests use cheats; force forces the game mode. Only when the player asks.",
["horizon-ctl lan open", "horizon-ctl lan status", "horizon-ctl lan close"],
&[p("action", Ty::Enum(&["open", "close", "status"]), "what to do"), opt("port", Ty::Int, "port for open"), opt("commands", Ty::Bool, "allow cheats"), opt("force", Ty::Bool, "force the game mode")], mcp: true, local: false),
cmd!("friends", Multiplayer, "friends host|stop|status", "Play with Friends: share the open world behind an invite code, stop, or see who joined",
"status gives the code: share it only when the player asks. Friends join with connect friend:CODE.",
["horizon-ctl friends host", "horizon-ctl friends status"], &[p("action", Ty::Enum(&["host", "stop", "status"]), "what to do")], mcp: true, local: false),
// World
cmd!("give", World, "give ITEM [COUNT]", "add items to the inventory", "", ["horizon-ctl give oak_log 16"],
&[p("item", Ty::Str, "item id"), opt("count", Ty::Int, "how many (default 1)")], mcp: true, local: false),
@@ -325,8 +411,20 @@ pub const COMMANDS: &[Cmd] = &[
&[p("ticks", Ty::Int, "day time")], mcp: true, local: false),
cmd!("setblock", World, "setblock X Y Z BLOCK[props]", "set a block (with neighbour updates)", "", ["horizon-ctl setblock 0 64 0 stone"],
&[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], p("block", Ty::Str, "block state such as oak_stairs[facing=east]")], mcp: true, local: false),
cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob", "", ["horizon-ctl summon cow"], &[p("kind", Ty::Str, "mob type")], mcp: true, local: false),
cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect", "", ["horizon-ctl effect speed 30 1"], &[], mcp: false, local: false),
cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob (in front of the player without a position)", "Replies with its id.", ["horizon-ctl summon cow", "horizon-ctl summon pig 10 64 3 baby"],
&[p("kind", Ty::Str, "mob type"), opt("x", Ty::Num, "X"), opt("y", Ty::Num, "Y"), opt("z", Ty::Num, "Z"), opt("baby", Ty::Bool, "a baby")], mcp: true, local: false),
cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect, or clear them all", "", ["horizon-ctl effect speed 30 1", "horizon-ctl effect clear"],
&[p("id", Ty::Str, "effect id such as speed, or clear"), opt("seconds", Ty::Num, "duration"), opt("amplifier", Ty::Int, "level - 1 (default 0)")], mcp: true, local: false),
cmd!("effects", World, "effects", "the player's active status effects", "", ["horizon-ctl effects"], &[], mcp: true, local: false),
cmd!("xp", World, "xp LEVELS", "add experience levels (negative removes)", "", ["horizon-ctl xp 30"], &[p("levels", Ty::Int, "levels to add")], mcp: true, local: false),
cmd!("enchant", World, "enchant ID LEVEL", "enchant the held item (a book stores it)", "", ["horizon-ctl enchant sharpness 5"],
&[p("id", Ty::Str, "enchantment id"), p("level", Ty::Int, "level")], mcp: true, local: false),
cmd!("potion", World, "potion ITEM POTION", "give a potion item", "", ["horizon-ctl potion splash_potion healing"],
&[p("item", Ty::Enum(&["potion", "splash_potion", "lingering_potion", "tipped_arrow"]), "which item"), p("potion", Ty::Str, "potion id")], mcp: true, local: false),
cmd!("fill", World, "fill X1 Y1 Z1 X2 Y2 Z2 BLOCK", "set a box of loaded blocks", "", ["horizon-ctl fill 0 64 0 4 64 4 glass"],
&[BOX[0], BOX[1], BOX[2], BOX[3], BOX[4], BOX[5], p("block", Ty::Str, "block state")], mcp: true, local: false),
cmd!("container", World, "container X Y Z [ITEM COUNT]", "list a container's items, or add items to it", "", ["horizon-ctl container 3 64 1", "horizon-ctl container 3 64 1 diamond 3"],
&[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("item", Ty::Str, "item to add"), opt("count", Ty::Int, "how many")], mcp: true, local: false),
cmd!("render-distance", World, "render-distance N", "chunks, 2..64", "", ["horizon-ctl render-distance 8"], &[p("chunks", Ty::Int, "render distance")], mcp: false, local: false),
cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)",
"Keys and mouse buttons held with key ... down or mouse ... down stay held while it waits. Release them with key ... up, release or stop.",
@@ -340,8 +438,8 @@ pub const COMMANDS: &[Cmd] = &[
cmd!("mcp", Scripting, "mcp", "serve the Model Context Protocol on stdin/stdout, one tool per command",
"Add it to an MCP client as a stdio server: command horizon-ctl, args [\"mcp\"] (with --socket PATH first if needed). The screenshot tool returns the image.",
["horizon-ctl mcp"], &[], mcp: false, local: true),
cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false),
cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false),
cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[p("seconds", Ty::Num, "how long to measure")], mcp: true, local: false),
cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[opt("reset", Ty::Bool, "start counting again")], mcp: true, local: false),
cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary",
"The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).",
["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false),
@@ -366,8 +464,9 @@ pub fn overview() -> String {
}
out.push_str(
"\nEvery reply is one JSON line. Errors are {\"error\": \"...\"}; the exit status is 0 on\n\
success, 1 when the game replied with an error, 2 for a usage error and 3 when the\n\
game cannot be reached or started. Actions (goto, break, place...) block until done.\n\
success, 1 when the game replied with an error, 2 for a usage error, 3 when the\n\
game cannot be reached or started and 4 while No AI is on (the launcher's settings).\n\
Actions (goto, break, place...) block until done.\n\
horizon-ctl help --game lists the running game's own commands, test hooks included.\n\
The socket is $HORIZON_CONTROL, else $XDG_RUNTIME_DIR/horizon-control.sock (on Windows\n\
%TEMP%\\horizon-control.json, a localhost TCP port with a token; any path ending in .json\n\
@@ -402,6 +501,73 @@ pub fn detail(c: &Cmd) -> String {
out
}
/// The generated reference, docs/horizon-ctl-commands.md (`horizon-ctl help --markdown`).
pub fn markdown() -> String {
let cell = |s: &str| s.replace('|', "\\|");
let mut out = String::from(
"<!-- Generated by `horizon-ctl help --markdown` from the command table in \
crates/horizon-client/src/bin/horizon-ctl/commands.rs: edit the table, then regenerate. -->\n\
# horizon-ctl commands\n\n\
Every command `horizon-ctl` takes, its MCP tool in `horizon-ctl mcp` (the launcher's \
`horizon-launcher mcp` offers the same tools as `game_<tool>`, all but `launch`) and its \
arguments. Positional arguments come first, in order; `--flags` after them. \
`horizon-ctl help --game` lists the game's own commands, test hooks included. \
Design rules and the full inventory: [agent-control.md](agent-control.md).\n",
);
for group in Group::ALL {
out.push_str(&format!(
"\n## {}\n\n| Command | MCP tool | What it does | Arguments |\n| --- | --- | --- | --- |\n",
group.title()
));
for c in COMMANDS.iter().filter(|c| c.group == group) {
let tool = if c.mcp {
let mut t = format!("`{}`", tool_name(c));
if DESTRUCTIVE.contains(&c.name) {
t.push_str(" (destructive)");
} else if OPEN_WORLD.contains(&c.name) {
t.push_str(" (network)");
}
t
} else {
"CLI only".to_owned()
};
let args: Vec<String> = c
.params
.iter()
.map(|p| {
let ty = match p.ty {
Ty::Int => "integer".to_owned(),
Ty::Num => "number".to_owned(),
Ty::Str => "string".to_owned(),
Ty::Rest => "text".to_owned(),
Ty::Bool => "boolean".to_owned(),
Ty::Enum(v) => v.join(", "),
};
let name = if p.flag {
format!("--{}", p.name)
} else {
p.name.to_owned()
};
let need = if p.required { ", required" } else { "" };
format!("`{name}` ({ty}{need}): {}", cell(p.help))
})
.collect();
out.push_str(&format!(
"| `{}` | {} | {} | {} |\n",
cell(c.usage),
tool,
cell(&capitalize(c.summary)),
if args.is_empty() {
"none".to_owned()
} else {
args.join("<br>")
}
));
}
}
out
}
fn capitalize(s: &str) -> String {
let mut chars = s.chars();
chars
@@ -640,6 +806,43 @@ mod tests {
assert_eq!(tool_name(find("look-at-entity").unwrap()), "look_at_entity");
}
#[test]
fn the_generated_reference_is_up_to_date() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../docs/horizon-ctl-commands.md"
);
let on_disk = std::fs::read_to_string(path).unwrap_or_default();
assert!(
on_disk == markdown(),
"docs/horizon-ctl-commands.md is out of date: run `horizon-ctl help --markdown > docs/horizon-ctl-commands.md`"
);
for c in COMMANDS {
assert!(
on_disk.contains(&format!("`{}", c.usage.replace('|', "\\|"))),
"{} undocumented",
c.name
);
}
}
#[test]
fn destructive_and_network_tools_exist() {
for name in DESTRUCTIVE.iter().chain(OPEN_WORLD) {
assert!(find(name).is_some_and(|c| c.mcp), "{name}");
}
let delete = find("world-delete").unwrap();
assert_eq!(
line_for(delete, &json!({ "folder": "A", "confirm": true })).unwrap(),
["world-delete", "A", "--confirm"]
);
let lan = find("lan").unwrap();
assert_eq!(
line_for(lan, &json!({ "action": "open", "commands": true })).unwrap(),
["lan", "open", "commands"]
);
}
#[test]
fn help_mentions_every_command() {
let text = overview();
@@ -20,6 +20,8 @@ use serde_json::{Value, json};
const GAME_ERROR: u8 = 1;
const USAGE: u8 = 2;
const UNREACHABLE: u8 = 3;
/// No AI is on (`horizon_core::no_ai`): agent control is off.
const DENIED: u8 = 4;
/// A failure, with the exit status it maps to.
#[derive(Debug)]
@@ -34,6 +36,13 @@ impl Failure {
status: USAGE,
}
}
/// No AI is on in the game's home.
fn denied() -> Self {
Self {
reply: json!({ "error": horizon_core::no_ai::REFUSAL, "kind": "denied" }),
status: DENIED,
}
}
fn unreachable(message: impl Into<String>) -> Self {
Self {
reply: json!({ "error": message.into(), "kind": "connection" }),
@@ -98,6 +107,8 @@ impl Client {
pub struct Session {
pub socket: PathBuf,
pub timeout: Option<Duration>,
/// The game's home, where No AI is read (`horizon_core::no_ai`).
pub home: PathBuf,
client: Option<Client>,
}
@@ -106,9 +117,14 @@ impl Session {
Self {
socket,
timeout,
home: horizon_client::logging::game_home(),
client: None,
}
}
/// A failure while No AI is on: every command refuses (help aside).
pub fn allowed(&self) -> Result<(), Failure> {
horizon_core::no_ai::check(&self.home).map_err(|_| Failure::denied())
}
fn client(&mut self) -> Result<&mut Client, Failure> {
if self.client.is_none() {
self.client = Some(Client::connect(&self.socket, self.timeout)?);
@@ -137,6 +153,7 @@ impl Session {
let Some(name) = words.first().map(String::as_str) else {
return Err(Failure::usage("no command; try horizon-ctl help"));
};
self.allowed()?;
if words.iter().skip(1).any(|w| w == "--help" || w == "-h") {
return Err(Failure::usage(
"use horizon-ctl COMMAND --help outside scripts",
@@ -174,6 +191,18 @@ impl Session {
ready["launch"] = reply;
Ok(ready)
}
"interact-entity" => {
let id = match words {
[_, id] if id.parse::<i64>().is_ok() => id,
_ => return Err(Failure::usage(format!("usage: {}", usage(name)))),
};
self.game(&format!("look-at entity {id}"))?;
self.game("mouse right click")?;
self.game("wait 2")?;
let mut screen = self.game("screen")?;
screen["ok"] = json!(true);
Ok(screen)
}
"hold" => {
let (key, seconds) = match words {
[_, key, _] => (key.clone(), number(2, "SECONDS")?),
@@ -183,7 +212,7 @@ impl Session {
thread::sleep(Duration::from_secs_f64(seconds.max(0.0)));
self.game(&format!("key {key} up"))
}
"logs" => logs(&horizon_client::logging::game_home(), &words[1..]),
"logs" => logs(&self.home, &words[1..]),
"wait-ready" => {
let limit = if words.len() > 1 {
number(1, "SECONDS")?
@@ -417,6 +446,10 @@ fn main() -> ExitCode {
print!("{}", commands::overview());
0
}
Some("help") if args.get(1).is_some_and(|a| a == "--markdown") => {
print!("{}", commands::markdown());
0
}
Some("help") if args.get(1).is_none_or(|a| a != "--game") => match args.get(1) {
None => {
print!("{}", commands::overview());
@@ -451,6 +484,10 @@ fn main() -> ExitCode {
}
}
}
Some("mcp") if session.allowed().is_err() => {
eprintln!("horizon-ctl mcp: {}", horizon_core::no_ai::REFUSAL);
DENIED
}
Some("mcp") => match mcp::serve(&mut session) {
Ok(()) => 0,
Err(e) => {
@@ -581,6 +618,27 @@ mod tests {
assert_eq!(f.status, USAGE);
}
#[test]
fn no_ai_refuses_every_command() {
let home = std::env::temp_dir().join(format!("horizon-ctl-no-ai-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&home);
let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None);
s.home = home.clone();
assert_eq!(
s.run(&["state".to_owned()]).unwrap_err().status,
UNREACHABLE
);
horizon_core::no_ai::set(&home, true).unwrap();
for words in [vec!["state"], vec!["logs"], vec!["launch", "--world", "A"]] {
let words: Vec<String> = words.into_iter().map(str::to_owned).collect();
let f = s.run(&words).unwrap_err();
assert_eq!(f.status, DENIED, "{words:?}");
assert_eq!(f.reply["kind"], "denied");
assert_eq!(f.reply["error"], horizon_core::no_ai::REFUSAL);
}
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn screenshot_paths_become_absolute() {
let mut words = vec!["screenshot".to_owned(), "a.png".to_owned()];
@@ -23,7 +23,13 @@ fn tools() -> Vec<Value> {
schema = json!({ "type": "object", "properties": {} });
description = "Capture the game window and return it as a PNG image.".into();
}
json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema })
let mut tool = json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema });
if commands::DESTRUCTIVE.contains(&c.name) {
tool["annotations"] = json!({ "destructiveHint": true });
} else if commands::OPEN_WORLD.contains(&c.name) {
tool["annotations"] = json!({ "openWorldHint": true });
}
tool
})
.collect()
}
+23
View File
@@ -167,6 +167,7 @@ fn object_style(o: &serde_json::Map<String, Value>) -> Style {
style.underlined = flag("underlined");
style.strikethrough = flag("strikethrough");
style.obfuscated = flag("obfuscated");
style.font = o.get("font").and_then(crate::text::font_id);
style
}
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
@@ -266,4 +267,26 @@ mod tests {
let (v, _) = parse_snbt("[\"a\",{\"text\":\"b\"}]").unwrap();
assert_eq!(to_text(&v, &mut |_| Text::empty()).plain(), "ab");
}
#[test]
fn the_font_is_inherited_and_kept() {
let (v, _) =
parse_snbt(r#"{text:"a",font:"alt",extra:["b",{text:"c",font:"minecraft:uniform"}]}"#)
.unwrap();
let t = to_text(&v, &mut |_| Text::empty());
let fonts: Vec<_> = t.chars().map(|(_, s)| s.font.clone()).collect();
let (alt, uniform) = (
Some("minecraft:alt".into()),
Some("minecraft:uniform".into()),
);
assert_eq!(fonts, [alt.clone(), alt, uniform]);
// Back to JSON with the field, which a re-read keeps.
let again = to_text(&t.component(), &mut |_| Text::empty());
let kept: Vec<_> = again.chars().map(|(_, s)| s.font.clone()).collect();
assert_eq!(kept, fonts);
// Not an identifier: no font.
let (v, _) = parse_snbt(r#"{text:"a",font:"Bad Font"}"#).unwrap();
let t = to_text(&v, &mut |_| Text::empty());
assert_eq!(t.spans[0].style.font, None);
}
}
+52 -2
View File
@@ -13,7 +13,11 @@ use std::{
io::{self, BufRead, BufReader, Read, Write},
net::{Ipv4Addr, TcpListener, TcpStream},
path::{Path, PathBuf},
sync::mpsc,
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
mpsc,
},
thread,
};
@@ -151,6 +155,12 @@ pub struct Server {
path: PathBuf,
requests: mpsc::Receiver<Request>,
sender: mpsc::Sender<Request>,
/// Clients connected now (an MCP server keeps one open; horizon-ctl one per command).
clients: Arc<AtomicUsize>,
/// Set when the server is dropped: the listener stops accepting and exits.
closed: Arc<AtomicBool>,
/// The TCP port, to wake the listener when closing.
port: Option<u16>,
}
/// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime
@@ -174,10 +184,15 @@ impl Server {
}
let (sender, requests) = mpsc::channel();
let local = sender.clone();
let clients = Arc::new(AtomicUsize::new(0));
let counted = clients.clone();
let closed = Arc::new(AtomicBool::new(false));
let mut tcp_port = None;
if uses_tcp(path) {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
let token = random_token();
let port = listener.local_addr()?.port();
tcp_port = Some(port);
write_private(
path,
&serde_json::json!({ "transport": "tcp", "port": port, "token": token })
@@ -186,6 +201,8 @@ impl Server {
spawn_listener(
move || listener.accept().map(|(s, _)| s),
sender,
counted,
closed.clone(),
move |stream: TcpStream| {
let _ = stream.set_nodelay(true);
let mut stream = Stream::Tcp(stream);
@@ -199,6 +216,8 @@ impl Server {
spawn_listener(
move || listener.accept().map(|(s, _)| s),
sender,
counted,
closed.clone(),
|s| Some(Stream::Unix(s)),
)?;
}
@@ -207,6 +226,9 @@ impl Server {
path: path.to_owned(),
requests,
sender: local,
clients,
closed,
port: tcp_port,
})
}
/// Commands from inside the process only (`--benchmark` without `--control`).
@@ -216,8 +238,15 @@ impl Server {
path: PathBuf::new(),
requests,
sender,
clients: Arc::default(),
closed: Arc::default(),
port: None,
}
}
/// How many clients are connected.
pub fn clients(&self) -> usize {
self.clients.load(Ordering::Relaxed)
}
/// Sends commands as a socket client would, from another thread.
pub fn sender(&self) -> mpsc::Sender<Request> {
self.sender.clone()
@@ -234,6 +263,8 @@ impl Server {
fn spawn_listener<S: Send + 'static>(
mut accept_next: impl FnMut() -> io::Result<S> + Send + 'static,
sender: mpsc::Sender<Request>,
clients: Arc<AtomicUsize>,
closed: Arc<AtomicBool>,
accept: impl Fn(S) -> Option<Stream> + Send + Sync + 'static,
) -> io::Result<()> {
let accept = std::sync::Arc::new(accept);
@@ -241,17 +272,24 @@ fn spawn_listener<S: Send + 'static>(
.name("horizon-control".into())
.spawn(move || {
loop {
let Ok(stream) = accept_next() else {
let next = accept_next();
if closed.load(Ordering::Relaxed) {
return;
}
let Ok(stream) = next else {
thread::sleep(std::time::Duration::from_millis(10));
continue;
};
let sender = sender.clone();
let accept = accept.clone();
let clients = clients.clone();
let _ = thread::Builder::new()
.name("horizon-control-client".into())
.spawn(move || {
if let Some(stream) = accept(stream) {
clients.fetch_add(1, Ordering::Relaxed);
serve(stream, &sender);
clients.fetch_sub(1, Ordering::Relaxed);
}
});
}
@@ -287,6 +325,18 @@ fn authenticate(stream: &mut Stream, token: &str) -> bool {
impl Drop for Server {
fn drop(&mut self) {
if self.path.as_os_str().is_empty() {
return;
}
// Wake the listener so it sees `closed` and exits (agent control turned off in-game).
self.closed.store(true, Ordering::Relaxed);
match self.port {
Some(port) => drop(TcpStream::connect((Ipv4Addr::LOCALHOST, port))),
#[cfg(unix)]
None => drop(UnixStream::connect(&self.path)),
#[cfg(not(unix))]
None => {}
}
let _ = std::fs::remove_file(&self.path);
}
}
+2
View File
@@ -193,6 +193,8 @@ impl Enchantments {
|| k.starts_with("item.minecraft.splash_potion")
|| k.starts_with("item.minecraft.lingering_potion")
|| k.starts_with("item.minecraft.tipped_arrow")
|| k.starts_with("item.minecraft.firework_rocket.")
|| k.starts_with("item.minecraft.firework_star.")
|| k.starts_with("trim_")
|| k.starts_with("potion.")
|| k.starts_with("container.")
+73 -5
View File
@@ -98,12 +98,73 @@ impl ItemEntity {
lava_hurt,
}
}
/// Returns false when the item should be removed.
/// `ItemEntity.tick` on a server: an item whose box is inside a block
/// (one placed where it lay) has no physics this tick
/// (`level.noCollision(box.deflate(1.0E-7))`).
pub fn inside_block(&self, world: &World, collision: &BlockCollisionRegistry<'_>) -> bool {
let mut scene = SceneCollisions {
world,
binding: collision,
subject: None,
};
let inner = self.bounds().deflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7));
!crate::collisions::no_collision_empty(&mut scene, inner)
}
/// `Entity.moveTowardsClosestSpace` from the middle of the item's box:
/// towards the nearest side of its block (north, south, west, east or
/// up) without a full collision cube, at `speed` (`nextFloat() * 0.2 +
/// 0.1`).
pub fn move_towards_closest_space(&mut self, world: &World, facts: &BlockFacts, speed: f32) {
let bounds = self.bounds();
let at = Vec3::new(
self.position.x,
(bounds.min_position().y + bounds.max_position().y) / 2.0,
self.position.z,
);
let pos = [
at.x.floor() as i32,
at.y.floor() as i32,
at.z.floor() as i32,
];
let delta = [
at.x - f64::from(pos[0]),
at.y - f64::from(pos[1]),
at.z - f64::from(pos[2]),
];
// (axis, step): NORTH, SOUTH, WEST, EAST, UP.
let mut closest = (1, 1);
let mut nearest = f64::MAX;
for (axis, step) in [(2, -1), (2, 1), (0, -1), (0, 1), (1, 1)] {
let mut n = pos;
n[axis] += step;
if !facts.get(world.block(n[0], n[1], n[2])).full_collision {
let d = if step > 0 {
1.0 - delta[axis]
} else {
delta[axis]
};
if d < nearest {
nearest = d;
closest = (axis, step);
}
}
}
let push = f64::from(closest.1 as f32 * speed);
let v = self.velocity.scale(0.75);
self.velocity = match closest.0 {
0 => Vec3::new(push, v.y, v.z),
1 => Vec3::new(v.x, push, v.z),
_ => Vec3::new(v.x, v.y, push),
};
}
/// Returns false when the item should be removed. `no_physics`: the item
/// moves through blocks this tick ([`ItemEntity::inside_block`]).
pub fn tick(
&mut self,
world: &World,
facts: &BlockFacts,
collision: &BlockCollisionRegistry<'_>,
no_physics: bool,
) -> bool {
self.ticks += 1;
self.previous = self.position;
@@ -140,15 +201,22 @@ impl ItemEntity {
subject: None,
};
let wanted = self.velocity;
let moved = scene
.resolve(self.bounds(), wanted, 0.0, self.on_ground)
.unwrap_or(Vec3::ZERO);
// Entity.move with noPhysics: straight through, the ground as it was.
let moved = if no_physics {
wanted
} else {
scene
.resolve(self.bounds(), wanted, 0.0, self.on_ground)
.unwrap_or(Vec3::ZERO)
};
self.position = Vec3::new(
self.position.x + moved.x,
self.position.y + moved.y,
self.position.z + moved.z,
);
self.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
if !no_physics {
self.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
}
if moved.x != wanted.x {
self.velocity.x = 0.0;
}
+140
View File
@@ -43,6 +43,7 @@ struct Out {
@location(8) back_color: vec4<f32>,
// entity.vsh's lightMapColor, multiplied in after the overlay.
@location(9) light_color: vec4<f32>,
@location(10) @interpolate(flat) weather_rect: vec4<f32>,
}
// Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed.
fn entity_light(normal: vec3<f32>, nether: bool) -> f32 {
@@ -109,6 +110,13 @@ fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
return entity_vertex(position, uv, overlay, color, light, normal);
}
// Retained bolt-local geometry, translated using the same f64 camera
// subtraction as the former CPU path before adding each local f32 position.
@vertex fn vs_lightning(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>,
@location(6) offset: vec3<f32>) -> Out {
return entity_vertex(offset + position, uv, overlay, color, light, normal);
}
struct CloudInfo {
offset: vec4<f32>,
colors: array<vec4<f32>, 4>,
@@ -209,3 +217,135 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
@fragment fn fs_water_mask() -> @location(0) vec4<f32> {
return vec4(0.0);
}
// WEATHER_MATH_BEGIN
// Unsigned 64-bit helpers (low word first). Snow adds a random double to a
// float drift before casting to float. Retaining the 53-bit base avoids early
// rounding, including ties, without requiring optional GPU float64 support.
fn weather_shr_jam(v: vec2<u32>, n: u32) -> vec2<u32> {
if n == 0u { return v; }
if n < 32u {
return vec2((v.x >> n) | (v.y << (32u - n)) | select(0u, 1u, (v.x << (32u - n)) != 0u), v.y >> n);
}
if n == 32u { return vec2(v.y | select(0u, 1u, v.x != 0u), 0u); }
if n < 64u {
return vec2((v.y >> (n - 32u)) | select(0u, 1u, v.x != 0u || (v.y << (64u - n)) != 0u), 0u);
}
return vec2(select(0u, 1u, any(v != vec2(0u))), 0u);
}
fn weather_add64(a: vec2<u32>, b: vec2<u32>) -> vec2<u32> {
let lo = a.x + b.x;
return vec2(lo, a.y + b.y + select(0u, 1u, lo < a.x));
}
fn weather_sub64(a: vec2<u32>, b: vec2<u32>) -> vec2<u32> {
return vec2(a.x - b.x, a.y - b.y - select(0u, 1u, a.x < b.x));
}
fn weather_double_plus_float(base: vec2<u32>, delta: f32) -> f32 {
// The random base is nonnegative and either zero or >= 2^-53.
if all(base == vec2(0u)) { return select(delta, 0.0, delta == 0.0); }
let db = bitcast<u32>(delta);
let mag = db & 0x7fffffffu;
let be = i32((base.y >> 20u) & 2047u) - 1023;
var de = i32(mag >> 23u) - 127;
var dm = (mag & 0x7fffffu) | 0x800000u;
if mag < 0x800000u {
dm = mag;
if dm == 0u { de = -200; }
else {
let shift = countLeadingZeros(dm) - 8u;
dm <<= shift;
de = -126 - i32(shift);
}
}
let e = max(be, de);
// Leading significand bit at 61, with room for addition and guard bits.
var a = vec2(base.x << 9u, ((base.y & 0xfffffu) | 0x100000u) << 9u | (base.x >> 23u));
var b = vec2(0u, dm << 6u);
a = weather_shr_jam(a, u32(e - be));
b = weather_shr_jam(b, u32(e - de));
var sign = 0u;
var value: vec2<u32>;
if (db >> 31u) == 0u { value = weather_add64(a, b); }
else if a.y > b.y || (a.y == b.y && a.x >= b.x) { value = weather_sub64(a, b); }
else { value = weather_sub64(b, a); sign = 0x80000000u; }
if all(value == vec2(0u)) { return 0.0; }
let leading = select(31u - countLeadingZeros(value.x), 63u - countLeadingZeros(value.y), value.y != 0u);
var exponent = e + i32(leading) - 61;
// Normalize the leading bit to 62. After jamming, bit 38 is the guard
// bit and bits 0..37 distinguish a tie from a value above the midpoint.
let shift = 62u - leading;
if shift >= 32u { value = vec2(0u, value.x << (shift - 32u)); }
else if shift != 0u { value = vec2(value.x << shift, (value.y << shift) | (value.x >> (32u - shift))); }
// Vanilla first rounds the addition to double, then casts to float.
// Round at bit 10 (53 retained bits) before the 24-bit rounding below;
// otherwise a double-rounding midpoint can select the wrong float.
let double_guard = (value.x & 512u) != 0u;
let double_sticky = (value.x & 511u) != 0u;
let double_odd = (value.x & 1024u) != 0u;
value.x &= 0xfffffc00u;
if double_guard && (double_sticky || double_odd) {
value = weather_add64(value, vec2(1024u, 0u));
}
if (value.y & 0x80000000u) != 0u {
value = weather_shr_jam(value, 1u);
exponent += 1;
}
var mantissa = value.y >> 7u;
let guard = (value.y & 64u) != 0u;
let sticky = (value.y & 63u) != 0u || value.x != 0u;
if guard && (sticky || (mantissa & 1u) != 0u) { mantissa += 1u; }
if mantissa >= 0x1000000u { mantissa >>= 1u; exponent += 1; }
return bitcast<f32>(sign | (u32(exponent + 127) << 23u) | (mantissa & 0x7fffffu));
}
fn weather_phase(animation: vec4<f32>, bases: vec4<u32>, snow: u32, time: vec4<f32>) -> vec2<f32> {
if snow == 0u {
let ticks = time.x + animation.y;
let t = ticks + time.z;
let step = -t / 32.0;
let offset = step * animation.x;
return vec2(0.0, offset % 32.0);
}
let t = time.x + time.z;
let u_time = t * 0.01;
let du = u_time * animation.z;
let v_time = t * animation.w;
let dv = v_time * 0.001;
let u = weather_double_plus_float(bases.xy, du);
let v = weather_double_plus_float(bases.zw, dv);
let fall_time = time.y + time.z;
let fall = -fall_time / 512.0;
return vec2(u, fall + v);
}
// Atlas sampler is nearest with no mipmaps. Clamp the integer texel inside
// the sprite even when a fractional coordinate rounds up at its far edge.
fn weather_texel(uv: vec2<f32>, rect: vec4<f32>, dimensions: vec2<u32>) -> vec2<i32> {
let size = vec2<f32>(dimensions);
let origin = vec2<i32>(round(rect.xy * size));
let extent = max(vec2<i32>(round(rect.zw * size)), vec2(1));
let local = min(vec2<i32>(floor(fract(uv) * vec2<f32>(extent))), extent - vec2(1));
return origin + local;
}
// WEATHER_MATH_END
struct WeatherTime { values: vec4<f32> }
@group(1) @binding(1) var<uniform> weather_time: WeatherTime;
@vertex fn vs_weather(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) rect: vec4<f32>, @location(3) animation: vec4<f32>,
@location(4) bases: vec4<u32>, @location(5) color: vec4<f32>,
@location(6) light: vec4<u32>, @location(7) snow: u32) -> Out {
let phase = weather_phase(animation, bases, snow, weather_time.values);
var out = entity_vertex(position, uv + phase, 0u, color, light, vec4(0.0));
out.weather_rect = rect;
return out;
}
@fragment fn fs_weather(in: Out) -> @location(0) vec4<f32> {
// Repeat within this sprite, never across the atlas. The atlas uses nearest
// filtering and no mipmaps, so fractional UVs have no seam derivatives.
let texel = weather_texel(in.uv, in.weather_rect, textureDimensions(atlas));
var color = textureLoad(atlas, texel, 0) * in.color;
if color.a < 0.1 { discard; }
color *= in.light_color;
let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
}
+92 -4
View File
@@ -89,6 +89,47 @@ impl Base<'_> {
}
/// `LivingEntity` + `Mob` (+ `AgeableMob`, creeper and skeleton specifics).
/// The mobs whose class extends vanilla's `Animal` (and so save `InLove`):
/// not allays, villagers, golems, dolphins or fish.
fn is_animal(id: &str) -> bool {
matches!(
id.strip_prefix("minecraft:").unwrap_or(id),
"pig"
| "cow"
| "mooshroom"
| "sheep"
| "chicken"
| "rabbit"
| "horse"
| "donkey"
| "mule"
| "zombie_horse"
| "skeleton_horse"
| "llama"
| "trader_llama"
| "goat"
| "panda"
| "polar_bear"
| "fox"
| "wolf"
| "cat"
| "ocelot"
| "parrot"
| "bee"
| "turtle"
| "armadillo"
| "frog"
| "axolotl"
| "hoglin"
| "strider"
| "camel"
| "camel_husk"
| "sniffer"
| "happy_ghast"
| "nautilus"
| "zombie_nautilus"
)
}
pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
let base = Base {
id: &m.kind.id,
@@ -175,12 +216,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (key, value) in [
("Age", Tag::Int(0)),
("ForcedAge", Tag::Int(0)),
("InLove", Tag::Int(0)),
("AgeLocked", Tag::Byte(0)),
] {
map.entry(key.into()).or_insert(value);
}
}
// Animal.addAdditionalSaveData: the love ticks left, whatever the save had.
if is_animal(id) {
map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0)));
}
match id {
"minecraft:creeper" => {
for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] {
@@ -445,10 +489,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.entry(key.into()).or_insert(value);
}
}
// Sheep.addAdditionalSaveData: its wool as it is now.
"minecraft:sheep" => {
for (key, value) in [("Color", Tag::Byte(0)), ("Sheared", Tag::Byte(0))] {
map.entry(key.into()).or_insert(value);
}
map.insert("Color".into(), Tag::Byte((m.extra.color & 15) as i8));
map.insert("Sheared".into(), Tag::Byte(i8::from(m.extra.sheared)));
}
// CopperGolem.addAdditionalSaveData.
"minecraft:copper_golem" => {
@@ -621,6 +665,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32;
m.extra.age_locked = flag(tag, "AgeLocked");
}
if is_animal(&m.kind.id) {
m.extra.in_love = number(tag.get("InLove")).unwrap_or(0) as i32;
}
m.name_visible = flag(tag, "CustomNameVisible");
m.no_ai = flag(tag, "NoAI");
m.no_gravity = flag(tag, "NoGravity");
@@ -832,6 +879,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
}
m.extra.egg_time = number(tag.get("life_ticks")).map_or(-1, |v| v as i32);
}
// Sheep.readAdditionalSaveData: white and unsheared when absent.
if m.species() == crate::mobs::Species::Sheep {
m.extra.color = number(tag.get("Color")).map_or(0, |c| (c as u8) & 15);
m.extra.sheared = flag(tag, "Sheared");
}
if m.species() == crate::mobs::Species::Shulker {
m.extra.variant3 = number(tag.get("AttachFace")).unwrap_or(0).clamp(0, 5) as u8;
m.extra.counter = number(tag.get("Peek")).unwrap_or(0).clamp(0, 100) as i32;
@@ -2051,3 +2103,39 @@ mod axolotl_nbt_tests {
assert_eq!(mm.temptation_cooldown_ticks.value(), Some(42));
}
}
#[cfg(test)]
mod sheep_nbt_tests {
use super::*;
#[test]
fn a_sheep_keeps_its_dyed_and_sheared_wool() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
if !root.join("items.json").exists() {
return;
}
let data = crate::mobs::MobTypes::load(&root).unwrap();
let mut m = Mob::new(
1,
Arc::new(data.types["minecraft:sheep"].clone()),
Vec3::new(0.0, 4.0, 0.0),
0.0,
);
// Summoned white, then dyed red and sheared: the save has it now.
let raw = Tag::compound([("Color", Tag::Byte(0)), ("Sheared", Tag::Byte(0))]);
(m.extra.color, m.extra.sheared) = (14, true);
let tag = mob_to_nbt(&m, [1, 2, 3, 4], Some(&raw));
assert_eq!(
(number(tag.get("Color")), number(tag.get("Sheared"))),
(Some(14), Some(1))
);
let types: HashMap<String, Arc<MobType>> = data
.types
.iter()
.map(|(k, v)| (k.clone(), Arc::new(v.clone())))
.collect();
let back = mob_from_nbt(&tag, &types, 2).unwrap();
assert_eq!((back.extra.color, back.extra.sheared), (14, true));
}
}
+29 -2
View File
@@ -107,6 +107,11 @@ pub struct Extras {
pub sort: bool,
/// A vanilla key name: sorts the part under the cursor.
pub sort_key: String,
/// No AI: every AI feature hidden and off (`horizon_core::no_ai`; the launcher writes it too).
pub no_ai: bool,
/// Agents may control the game the player starts: it opens its control socket for
/// horizon-ctl and MCP clients (off by default; an agent's own launch always opens it).
pub agent_control: bool,
}
impl Default for Extras {
fn default() -> Self {
@@ -135,6 +140,8 @@ impl Default for Extras {
mouse_tweaks_wheel: true,
sort: false,
sort_key: "key.keyboard.unknown".into(),
no_ai: false,
agent_control: false,
}
}
}
@@ -198,6 +205,8 @@ impl Extras {
"mouseTweaksWheel" => e.mouse_tweaks_wheel = flag(e.mouse_tweaks_wheel),
"sort" => e.sort = flag(e.sort),
"sortKey" if value.starts_with("key.") => e.sort_key = value.to_owned(),
horizon_core::no_ai::KEY => e.no_ai = flag(e.no_ai),
"agentControl" => e.agent_control = flag(e.agent_control),
_ => {}
}
}
@@ -205,7 +214,7 @@ impl Extras {
}
pub fn serialize(&self) -> String {
format!(
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n",
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\n",
bool_text(self.fullbright),
bool_text(self.dynamic_lights),
bool_text(self.zoom),
@@ -234,6 +243,9 @@ impl Extras {
bool_text(self.mouse_tweaks_wheel),
bool_text(self.sort),
self.sort_key,
horizon_core::no_ai::KEY,
bool_text(self.no_ai),
bool_text(self.agent_control),
)
}
/// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for
@@ -451,6 +463,9 @@ pub enum Item {
MouseTweaksWheel,
Sort,
SortKey,
/// Not on the Extras page: Horizon Settings shows No AI, its AI Agent page Agent Control.
NoAi,
AgentControl,
}
/// The Extras page: headers and items.
pub fn rows() -> Vec<Result<Item, &'static str>> {
@@ -529,6 +544,8 @@ impl Item {
Item::FpsLows => "Minimum and 1% low",
Item::Keystrokes => "Keystrokes",
Item::KeystrokesCps => "Clicks per second",
Item::NoAi => "No AI",
Item::AgentControl => "Agent Control",
}
}
/// The switch this setting belongs to: it does nothing while that is off.
@@ -542,7 +559,7 @@ impl Item {
MouseTweaksWheel => MouseTweaks,
SortKey => Sort,
Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort
| AutoReconnect => {
| AutoReconnect | NoAi | AgentControl => {
return None;
}
})
@@ -586,6 +603,12 @@ impl Item {
}
Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.",
Item::KeystrokesCps => "Clicks in the last second under each mouse button.",
Item::NoAi => {
"Hides and turns off every AI feature: agent control, horizon-ctl and the MCP servers. The launcher's switch too."
}
Item::AgentControl => {
"Your own AI agent can play this game through horizon-ctl or an MCP client, on this computer only."
}
}
}
/// The frame-time cost the main switch of an extra shows.
@@ -616,6 +639,8 @@ impl Item {
Item::MouseTweaks => e.mouse_tweaks,
Item::MouseTweaksWheel => e.mouse_tweaks_wheel,
Item::Sort => e.sort,
Item::NoAi => e.no_ai,
Item::AgentControl => e.agent_control,
_ => return None,
})
}
@@ -671,6 +696,8 @@ impl Item {
}
Item::MinimapShape => e.minimap_round = !e.minimap_round,
Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back),
Item::NoAi => e.no_ai = !e.no_ai,
Item::AgentControl => e.agent_control = !e.agent_control,
Item::ZoomKey | Item::SortKey => {}
}
}
File diff suppressed because it is too large Load Diff
+303
View File
@@ -0,0 +1,303 @@
//! Play with Friends: Horizon's own sharing of the open world behind an
//! invite code (`game/friends.rs`). The pause menu's Friends button, the icon
//! vanilla's PauseScreen already has, opens it. It is drawn the way a mod adds
//! a screen to vanilla: the menu background, a centred title and text,
//! vanilla's buttons and Done in the footer.
use crate::{
hud::{HudAtlas, HudBatch, rgba},
multiplayer::wrap,
text::Text,
ui,
};
pub const TITLE: &str = "Play with Friends";
/// What the screen shows (game/friends.rs fills it).
#[derive(Clone, Debug, Default)]
pub struct FriendsView {
/// A singleplayer world (not a server): sharing is offered.
pub shown: bool,
pub sharing: bool,
pub code: Option<String>,
/// Who can join and what to do when friends on the internet can't (or,
/// before the code, what the game is doing).
pub status: String,
/// Friends on the internet can reach the host.
pub reachable: bool,
/// Where the troubleshooting is, when they can't.
pub help: Option<String>,
/// The players in the world besides the host.
pub guests: Vec<String>,
pub notice: Option<String>,
/// The code was just copied.
pub copied: bool,
}
/// A button's action.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
Share,
Copy,
Stop,
/// Open the troubleshooting page.
Help,
Done,
}
fn grey() -> u32 {
rgba(160, 160, 160, 255)
}
const WHITE: u32 = u32::MAX;
const HINT: &str = "Friends paste the code after the title screen's Friends button, in Direct Connection, or on the launcher's Play page.";
struct Button {
x: f32,
y: f32,
w: f32,
label: &'static str,
action: Action,
active: bool,
}
/// The centred lines (text, colour, y) and the buttons.
fn layout(
atlas: &HudAtlas,
(w, h): (f32, f32),
view: &FriendsView,
) -> (Vec<(String, u32, f32)>, Vec<Button>) {
let width = (w - 40.0).min(310.0);
let cx = (w / 2.0).floor();
let mut lines = Vec::new();
let mut y = 40.0;
let add = |lines: &mut Vec<(String, u32, f32)>, text: &str, color: u32, y: &mut f32| {
for line in wrap(text, width, atlas) {
lines.push((line, color, *y));
*y += 10.0;
}
};
let mut buttons = Vec::new();
if view.sharing {
lines.push(("Invite Code".to_owned(), grey(), y));
y += 12.0;
match &view.code {
Some(code) => {
for line in code_lines(atlas, code, width) {
lines.push((line, WHITE, y));
y += 10.0;
}
}
None => add(&mut lines, &view.status, WHITE, &mut y),
}
y += 6.0;
buttons.push(Button {
x: cx - 154.0,
y,
w: 150.0,
label: if view.copied { "Copied" } else { "Copy Code" },
action: Action::Copy,
active: view.code.is_some(),
});
buttons.push(Button {
x: cx + 4.0,
y,
w: 150.0,
label: "Stop Sharing",
action: Action::Stop,
active: true,
});
y += 30.0;
if view.code.is_some() {
// Who can join: grey when friends anywhere can, white (it asks
// for something) when only the LAN and VPNs can.
let tint = if view.reachable { grey() } else { WHITE };
add(&mut lines, &view.status, tint, &mut y);
y += 4.0;
}
let here = if view.guests.is_empty() {
"No friends here yet.".to_owned()
} else {
format!("Here now: {}", view.guests.join(", "))
};
add(&mut lines, &here, grey(), &mut y);
if let Some(notice) = &view.notice {
add(&mut lines, notice, WHITE, &mut y);
}
// Where friends paste the code, while it fits above the footer.
if y + 10.0 * wrap(HINT, width, atlas).len() as f32 <= h - 33.0 {
add(&mut lines, HINT, grey(), &mut y);
}
} else {
add(
&mut lines,
"Share this world behind an invite code: it opens to LAN, and friends on the internet join with the code. No server of ours is involved.",
WHITE,
&mut y,
);
y += 4.0;
add(&mut lines, HINT, grey(), &mut y);
buttons.push(Button {
x: cx - 100.0,
y: y + 8.0,
w: 200.0,
label: "Start Sharing",
action: Action::Share,
active: view.shown,
});
}
// HeaderAndFooterLayout's footer: Done, beside Troubleshooting when
// friends on the internet can't reach the host.
if view.sharing && view.help.is_some() {
buttons.push(Button {
x: cx - 154.0,
y: h - 27.0,
w: 150.0,
label: "Troubleshooting...",
action: Action::Help,
active: true,
});
buttons.push(Button {
x: cx + 4.0,
y: h - 27.0,
w: 150.0,
label: "gui.done",
action: Action::Done,
active: true,
});
} else {
buttons.push(Button {
x: cx - 100.0,
y: h - 27.0,
w: 200.0,
label: "gui.done",
action: Action::Done,
active: true,
});
}
(lines, buttons)
}
/// The code's groups packed into lines of at most `width`.
fn code_lines(atlas: &HudAtlas, code: &str, width: f32) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
for group in code.split('-') {
match lines.last_mut() {
Some(l) if HudBatch::text_width(atlas, &format!("{l}-{group}")) <= width => {
l.push('-');
l.push_str(group);
}
_ => lines.push(group.to_owned()),
}
}
lines
}
fn label(key: &str) -> Text {
if key.starts_with("gui.") {
Text::translate(key, &[])
} else {
Text::literal(key)
}
}
pub fn draw(
batch: &mut HudBatch,
atlas: &HudAtlas,
cursor: (f32, f32),
view: &FriendsView,
in_world: bool,
) {
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world);
let title = Text::literal(TITLE);
let tw = atlas.font.width_text(&title);
batch.text_styled(atlas, &title, ((w - tw) / 2.0).floor(), 15.0, WHITE, true);
let (lines, buttons) = layout(atlas, (w, h), view);
for (line, color, y) in lines {
let lw = HudBatch::text_width(atlas, &line);
batch.text(atlas, &line, ((w - lw) / 2.0).floor(), y, color, true);
}
for b in buttons {
let hover = b.active && ui::hovered(cursor, b.x, b.y, b.w, 20.0);
ui::button(
batch,
atlas,
b.x,
b.y,
b.w,
20.0,
&label(b.label),
b.active,
hover,
);
}
}
/// The button under a click, if it is active.
pub fn click(
atlas: &HudAtlas,
size: (f32, f32),
cursor: (f32, f32),
view: &FriendsView,
) -> Option<Action> {
layout(atlas, size, view)
.1
.into_iter()
.find(|b| b.active && ui::hovered(cursor, b.x, b.y, b.w, 20.0))
.map(|b| b.action)
}
#[cfg(test)]
mod tests {
use super::*;
fn atlas() -> HudAtlas {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
#[test]
fn share_then_copy_and_stop() {
let atlas = atlas();
let size = (427.0, 240.0);
let idle = FriendsView {
shown: true,
..FriendsView::default()
};
let (_, buttons) = layout(&atlas, size, &idle);
let share = buttons.iter().find(|b| b.action == Action::Share).unwrap();
assert_eq!(
click(&atlas, size, (share.x + 1.0, share.y + 1.0), &idle),
Some(Action::Share)
);
let sharing = FriendsView {
shown: true,
sharing: true,
status: "Finding how friends can reach you…".into(),
..FriendsView::default()
};
let (_, buttons) = layout(&atlas, size, &sharing);
let copy = buttons.iter().find(|b| b.action == Action::Copy).unwrap();
assert!(!copy.active, "nothing to copy before the code");
let with_code = FriendsView {
code: Some("0B33K-Q405Q-1Z5CV-X6NHY-R12N0-VK8T1-60N00-RA134-952PE-1HA08-910P0-K5M01-ST1NB-JDTB6-K4W1P-0".into()),
status: "Friends on your network or VPN can join. For friends on the internet: turn on UPnP on your router, or forward TCP port 25580 to 10.0.0.2, or use a relay, or a VPN such as Tailscale or ZeroTier (the code already holds your VPN address).".into(),
help: Some("https://example.invalid/help".into()),
..sharing
};
let (lines, buttons) = layout(&atlas, size, &with_code);
assert!(
lines.iter().all(|(_, _, y)| y + 9.0 <= size.1 - 27.0),
"the text stays above the footer"
);
for action in [Action::Copy, Action::Stop, Action::Help, Action::Done] {
let b = buttons.iter().find(|b| b.action == action).unwrap();
assert_eq!(
click(&atlas, size, (b.x + 1.0, b.y + 1.0), &with_code),
Some(action)
);
}
}
#[test]
fn a_server_offers_no_sharing() {
let atlas = atlas();
let view = FriendsView::default();
let (_, buttons) = layout(&atlas, (427.0, 240.0), &view);
let share = buttons.iter().find(|b| b.action == Action::Share).unwrap();
assert!(!share.active);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+7
View File
@@ -403,7 +403,9 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
}
}
pub(super) fn inventory_counts(&self) -> BTreeMap<String, i64> {
@@ -458,8 +460,11 @@ impl Game<'_> {
"sneaking": self.keys.contains(&KeyCode::ShiftLeft),
"sprinting": self.keys.contains(&KeyCode::ControlLeft),
"health": p.health.health(),
"absorption": p.health.absorption(),
"air": p.air,
"food": p.health.food.food,
"saturation": p.health.food.saturation,
"shield_cooldown": self.shield_cooldown,
"xp": { "level": self.experience.level, "progress": self.experience.progress, "total": self.experience.total },
"effects": self.potions.effects.list.iter().map(|e| json!({ "id": e.id, "duration_ticks": e.duration, "amplifier": e.amplifier })).collect::<Vec<_>>(),
})
@@ -477,6 +482,8 @@ impl Game<'_> {
"sleeping": self.sleeping,
// The item in use: its slot and for how many ticks.
"using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })),
// The block being dug: how far along, after how many ticks.
"mining": self.mining.as_ref().map(|m| json!({ "pos": m.pos, "progress": m.progress, "ticks": m.ticks })),
// The arm swings started (LivingEntity.swing).
"swings": self.swings_started,
"time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) },
@@ -0,0 +1,140 @@
//! Agent control as a setting (Horizon Settings > AI Agent): when the control socket is open, who
//! is connected, and the details an agent needs. The socket opens when the game was started for
//! an agent (`--control`, `--control-socket`: horizon-ctl launch, the launcher's MCP `play`) or
//! when the player turned Agent Control on, and never under No AI (`horizon_core::no_ai`).
//! Turning either switch in the game opens or closes it at once.
use super::Game;
use horizon_client::{Result, control};
use std::path::PathBuf;
impl Game<'_> {
/// The endpoint: the one the command line gave, else the default horizon-ctl looks for.
fn agent_socket_path(&self) -> PathBuf {
self.options
.control
.clone()
.unwrap_or_else(control::default_path)
}
/// At startup: open the socket if the game was started for an agent or Agent Control is on.
pub(super) fn start_agent_control(&mut self) -> Result<()> {
self.agent_control_on = self.settings.extras.agent_control;
if self.options.benchmark.is_some() && self.options.control.is_none() {
return Ok(());
}
if self.settings.extras.no_ai {
if self.options.control.is_some() {
log::warn!(
"Horizon: control socket not opened: {}",
horizon_core::no_ai::REFUSAL
);
}
return Ok(());
}
if let Some(path) = &self.options.control {
// Asked for on the command line: failing to listen is an error.
let server = control::Server::start(path)
.map_err(|e| format!("control socket {}: {e}", path.display()))?;
log::info!("Horizon: control socket {}", server.path().display());
self.control = Some(server);
} else if self.agent_control_on {
self.open_agent_socket();
}
Ok(())
}
/// The setting's socket: a failure (another game holds the default endpoint) is logged and
/// shown on the AI Agent page, not fatal.
fn open_agent_socket(&mut self) {
let path = self.agent_socket_path();
match control::Server::start(&path) {
Ok(server) => {
log::info!("Horizon: control socket {}", server.path().display());
self.control = Some(server);
}
Err(e) => log::warn!("Horizon: control socket {}: {e}", path.display()),
}
}
/// After a settings change: No AI closes the socket; Agent Control turned on or off opens or
/// closes it.
pub(super) fn sync_agent_control(&mut self) {
let wanted = self.settings.extras.agent_control;
let changed = wanted != self.agent_control_on;
self.agent_control_on = wanted;
let open = self
.control
.as_ref()
.is_some_and(|c| !c.path().as_os_str().is_empty());
if self.settings.extras.no_ai || (changed && !wanted) {
if open {
log::info!("Horizon: control socket closed");
self.control = None;
}
} else if changed && wanted && self.control.is_none() {
self.open_agent_socket();
}
}
/// An agent's command arrived.
pub(super) fn agent_command_seen(&mut self) {
self.agent_last = Some(std::time::Instant::now());
}
/// The AI Agent page's lines: the state, then where agents connect.
pub(super) fn agent_status_lines(&self) -> Vec<String> {
let server = self
.control
.as_ref()
.filter(|c| !c.path().as_os_str().is_empty());
let mut lines = vec![match server {
Some(s) if s.clients() > 0 => {
let ago = self
.agent_last
.map(|t| format!(", last command {} s ago", t.elapsed().as_secs()))
.unwrap_or_default();
format!(
"Connected: {} agent connection{}{ago}",
s.clients(),
if s.clients() == 1 { "" } else { "s" }
)
}
Some(_) => "Waiting for an agent.".into(),
None => "Off: agents can't reach this game.".into(),
}];
if let Some(s) = server {
if self.options.control.is_some() && !self.agent_control_on {
lines.push("Opened for this session by the program that started the game.".into());
}
// The full path is too wide for the page: Copy Connection Details has it.
let name = s.path().file_name().unwrap_or_default().to_string_lossy();
lines.push(format!(
"Socket: {name} (copy the details for its full path)"
));
}
lines.push("Local only: agents on this computer, never the network.".into());
lines
}
/// What Copy Connection Details puts on the clipboard: the socket, a horizon-ctl line to try,
/// and an MCP client's config for this game.
pub(super) fn agent_details(&self) -> String {
let socket = self.agent_socket_path();
let ctl = std::env::current_exe()
.unwrap_or_default()
.with_file_name(if cfg!(windows) {
"horizon-ctl.exe"
} else {
"horizon-ctl"
});
let config = serde_json::json!({ "mcpServers": { "horizon-game": {
"command": ctl, "args": ["--socket", socket, "mcp"] } } });
format!(
"Horizon agent control (this computer only)\nSocket: {}\nTry it: \"{}\" --socket \"{}\" state\nMCP config:\n{}\n",
socket.display(),
ctl.display(),
socket.display(),
serde_json::to_string_pretty(&config).unwrap_or_default()
)
}
}
+175 -6
View File
@@ -8,12 +8,13 @@ use horizon_client::{
items::ItemStack,
mesher::Vertex,
mobs::{Mob, Part, anim::Poses},
trims::{TrimOverride, TrimRegistry, TrimTexture},
};
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
};
use std::{collections::HashMap, sync::Arc};
use std::{collections::HashMap, path::PathBuf, sync::Arc};
/// Armor stand models and the humanoid layers of every equipment asset.
pub(super) struct ArmorStandAssets {
@@ -25,6 +26,11 @@ pub(super) struct ArmorStandAssets {
pub player: HashMap<&'static str, Part>,
/// asset id -> layer kind (humanoid / humanoid_leggings) -> (texture, undyed colour).
pub equipment: HashMap<String, HashMap<String, (String, Option<u32>)>>,
/// asset id -> `trim_overrides`.
pub trim_overrides: HashMap<String, Vec<TrimOverride>>,
pub trims: TrimRegistry,
/// The resources the trim textures are made from.
pub root: PathBuf,
}
impl ArmorStandAssets {
pub fn load(
@@ -48,6 +54,7 @@ impl ArmorStandAssets {
player.insert("elytra", part);
}
let mut equipment = HashMap::new();
let mut trim_overrides = HashMap::new();
if let Ok(entries) = std::fs::read_dir(root.join("assets/minecraft/equipment")) {
for e in entries.flatten() {
let path = e.path();
@@ -76,6 +83,7 @@ impl ArmorStandAssets {
);
}
}
trim_overrides.insert(format!("minecraft:{name}"), TrimOverride::list(&v));
equipment.insert(format!("minecraft:{name}"), kinds);
}
}
@@ -85,30 +93,67 @@ impl ArmorStandAssets {
layers,
player,
equipment,
trim_overrides,
trims: TrimRegistry::load(root),
root: root.to_owned(),
}
}
/// Trim data of reloaded resources (the models stay).
pub fn reload_trims(&mut self, root: &std::path::Path) {
let fresh = Self::load(root, None);
self.trim_overrides = fresh.trim_overrides;
self.trims = fresh.trims;
self.root = fresh.root;
}
/// `TrimTextureKey`: the trim texture of `stack` on its humanoid
/// layer (`humanoid` or `humanoid_leggings`), if it has a trim.
fn trim_texture(&self, asset: &str, kind: &str, stack: &ItemStack) -> Option<TrimTexture> {
let (material, pattern) = stack.extra.as_ref()?.trim.as_ref()?;
let overrides = self
.trim_overrides
.get(asset)
.map_or(&[][..], Vec::as_slice);
TrimTexture::resolve(&self.trims, overrides, material, pattern, kind)
}
}
impl Game<'_> {
/// `HumanoidArmorLayer` for the player: (model, texture rect, colour) of
/// each worn piece, head to feet.
pub(super) fn player_armor_layers(&self) -> Vec<(&Part, [f32; 4], u32)> {
self.armor_layers(self.armor.each_ref().map(|s| s.as_ref().map(|s| &*s.item)))
self.stack_armor_layers(&self.armor)
}
/// `HumanoidArmorLayer` for worn stacks (head to feet), trims included.
pub(super) fn stack_armor_layers(
&self,
armor: &[Option<ItemStack>; 4],
) -> Vec<(&Part, [f32; 4], u32)> {
self.armor_layers(
armor
.each_ref()
.map(|s| s.as_ref().map(|s| (&*s.item, Some(s)))),
)
}
/// `HumanoidArmorLayer` for another player's model: the armour it wears
/// (`extra.head` .. `extra.feet`).
pub(super) fn worn_armor_layers(&self, m: &Mob) -> Vec<(&Part, [f32; 4], u32)> {
let e = &m.extra;
self.armor_layers([&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref()))
self.armor_layers(
[&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref().map(|i| (i, None))),
)
}
/// The layers of the armour items `worn`, head to feet.
fn armor_layers(&self, worn: [Option<&str>; 4]) -> Vec<(&Part, [f32; 4], u32)> {
/// The layers of the armour items `worn` (with their stacks when known,
/// for trims), head to feet.
fn armor_layers(
&self,
worn: [Option<(&str, Option<&ItemStack>)>; 4],
) -> Vec<(&Part, [f32; 4], u32)> {
let assets = &self.armor_stand_assets;
let mut out = Vec::new();
for (item, layer) in worn
.into_iter()
.zip(["helmet", "chestplate", "leggings", "boots"])
{
let Some(item) = item else {
let Some((item, stack)) = item else {
continue;
};
let Some(asset) = self
@@ -138,9 +183,117 @@ impl Game<'_> {
0xFF00_0000 | (c & 0xFF) << 16 | (c & 0xFF00) | (c >> 16) & 0xFF
});
out.push((part, [r.u0, r.v0, r.u1, r.v1], color));
// EquipmentLayerRenderer: the trim layer over the armour.
if let Some(r) = stack
.and_then(|s| assets.trim_texture(&asset, kind, s))
.and_then(|t| self.gui.atlas.sprites.get(&t.sprite()))
{
out.push((part, [r.u0, r.v0, r.u1, r.v1], 0xFFFF_FFFF));
}
}
out
}
/// `PalettedTextureManager.getOrPrepare` for the trims drawn this frame
/// (the player's armour and the armour stands'): each generated texture
/// goes into an atlas trim slot, a free one, else the least recently
/// drawn.
pub(super) fn prepare_trims(&mut self) {
use horizon_client::hud::TRIM_SLOTS;
let assets = &self.armor_stand_assets;
let items = self.res.items();
let mut wanted: Vec<TrimTexture> = Vec::new();
let guests = self.lan.iter().flat_map(|host| host.hub.guests.iter());
let stacks = self
.armor
.iter()
.chain(guests.flat_map(|g| g.armor.iter()))
.zip(
["helmet", "chestplate", "leggings", "boots"]
.into_iter()
.cycle(),
)
.chain(self.armor_stands.iter().flat_map(|a| {
[5usize, 4, 3, 2]
.map(|slot| &a.equipment[slot])
.into_iter()
.zip(["helmet", "chestplate", "leggings", "boots"])
}));
for (stack, layer) in stacks {
let Some(stack) = stack.as_ref().filter(|s| s.extra.is_some()) else {
continue;
};
let Some(asset) = items
.get(&stack.item)
.and_then(|i| i.equip_asset.as_deref())
else {
continue;
};
let kind = if layer == "leggings" {
"humanoid_leggings"
} else {
"humanoid"
};
if let Some(t) = assets.trim_texture(asset, kind, stack)
&& !wanted.contains(&t)
{
wanted.push(t);
}
}
for t in wanted {
let name = t.sprite();
// Entries the atlas no longer has (rebuilt by a resource reload) are free.
let sprites = &self.gui.atlas.sprites;
self.trim_slots.retain(|(n, _)| sprites.contains_key(n));
if let Some(i) = self.trim_slots.iter().position(|e| e.0 == name) {
let e = self.trim_slots.remove(i);
self.trim_slots.push(e);
continue;
}
let Some((w, h, rgba)) = t.generate(&self.armor_stand_assets.root) else {
continue;
};
let used: Vec<usize> = self.trim_slots.iter().map(|e| e.1).collect();
let slot = match (0..TRIM_SLOTS).find(|i| !used.contains(i)) {
Some(free) => free,
None => {
let (old, slot) = self.trim_slots.remove(0);
self.gui.atlas.sprites.remove(&old);
slot
}
};
let Some(area) = self
.gui
.atlas
.sprites
.get(&format!("horizon/trim{slot}"))
.copied()
else {
continue;
};
if w > area.w || h > area.h {
continue;
}
let (aw, ah) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32);
let (x, y) = ((area.u0 * aw).round(), (area.v0 * ah).round());
self.map_patches.push(horizon_client::font::Patch {
x: x as u32,
y: y as u32,
width: w,
height: h,
rgba,
});
let rect = horizon_client::hud::Rect {
u0: area.u0,
v0: area.v0,
u1: (x + w as f32) / aw,
v1: (y + h as f32) / ah,
w,
h,
};
self.gui.atlas.sprites.insert(name.clone(), rect);
self.trim_slots.push((name, slot));
}
}
/// `ArmorStandItem.useOn`.
pub(super) fn place_armor_stand(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool {
if &*stack.item != "minecraft:armor_stand" || hit.face == [0, -1, 0] {
@@ -564,6 +717,22 @@ impl Game<'_> {
0,
out,
);
// EquipmentLayerRenderer: the trim layer over the armour.
if let Some(trim) = assets
.trim_texture(&asset, kind, stack)
.and_then(|t| uv_of(&t.sprite()))
{
horizon_client::mobs::render::draw(
part,
base,
&layer_poses,
trim,
0xFFFF_FFFF,
packed,
0,
out,
);
}
}
self.cull_entity_vertices(out, entity_start);
}
-303
View File
@@ -1,303 +0,0 @@
//! The live title backdrop (Menu style: Horizon): a frozen landscape that
//! Horizon generates and renders itself behind the title screens, seen
//! through a slow orbiting camera, falling snow, an overcast sky and the cold
//! blur and grade of `gfx::PostGrade`. Nothing is bundled: the chunks come
//! from the vanilla generator for a fixed seed and are cached in
//! `saves/.horizon-title/backdrop` (no level.dat, so no world list entry).
//! The ice-spikes spot is found once with `/locate biome`'s search and kept
//! in `spot.txt` there. The generator is built and the spot found on a
//! worker, so the title keeps drawing its panorama until both are ready.
use super::Game;
use horizon_client::{
Result,
save::{Persistent, SaveDir},
streaming::Streaming,
vanillagen::VanillaTerrain,
world::{Weather, World},
};
use horizon_core::biome::{BiomeZoom, obfuscate_seed};
use std::{
sync::{Arc, Mutex},
time::Instant,
};
/// The world the backdrop is cut from (HORIZON_BACKDROP_SEED overrides it).
const SEED: i64 = 2_026_031_337;
/// The biome the camera looks for.
const BIOME: &str = "minecraft:ice_spikes";
/// Late morning: the snow reads clearly; the grade (`PostGrade::FROST`) makes it cold.
const DAY_TIME: i64 = 4_000;
/// The worker's result: the generator for [`SEED`], or why it failed.
type Built = std::result::Result<Arc<VanillaTerrain>, String>;
#[derive(Default)]
pub(super) struct Backdrop {
pub active: bool,
/// The generator, once the worker has built it; taken when it is installed.
terrain: Arc<Mutex<Option<Built>>>,
/// The generator streams the backdrop's chunks.
installed: bool,
/// The search for the spot, then the spot (block x, z).
spot: Arc<Mutex<Option<Option<(i32, i32)>>>>,
centred: bool,
/// Camera position once the ground under it has loaded.
pub camera: Option<glam::DVec3>,
pub ready: Option<Instant>,
pub started: Option<Instant>,
}
fn seed() -> i64 {
std::env::var("HORIZON_BACKDROP_SEED")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(SEED)
}
impl Game<'_> {
/// How visible the live backdrop is (0 until its first chunks are drawn).
pub(super) fn backdrop_fade(&self) -> f32 {
let Some(at) = self.backdrop.ready else {
return 0.0;
};
let x = (at.elapsed().as_secs_f32() / 1.6).clamp(0.0, 1.0);
x * x * (3.0 - 2.0 * x)
}
/// Whether the frame should draw the backdrop world instead of the panorama.
pub(super) fn backdrop_live(&self) -> bool {
self.title.is_some() && self.backdrop.active && self.backdrop.camera.is_some()
}
/// The orbiting camera: position, yaw and pitch.
pub(super) fn backdrop_view(&self) -> Option<(glam::DVec3, f32, f32)> {
let c = self.backdrop.camera?;
let t = self
.backdrop
.started
.map_or(0.0, |s| s.elapsed().as_secs_f32());
// A full turn in about six minutes.
let yaw = (200.0 + t * 1.0) % 360.0;
let pitch = 6.0 + (t * 0.05).sin() * 2.0;
Some((c, yaw, pitch))
}
/// Called every frame while the title is up.
pub(super) fn update_backdrop(&mut self) -> Result<()> {
let wanted = self.pending_entry.is_none()
&& self.title.is_some()
&& horizon_client::ui_theme::horizon()
&& self.world_renderer_ready
&& self.renderer.is_some()
&& self.options.frames.is_none();
if !wanted {
if self.backdrop.active && self.title.is_some() {
self.stop_backdrop();
}
if self.title.is_none() && self.backdrop.active {
// open_world / connect_server replaced the world and streaming.
self.backdrop = Backdrop::default();
}
return Ok(());
}
if !self.backdrop.active {
self.start_backdrop()?;
}
if !self.backdrop.installed {
let built = self
.backdrop
.terrain
.lock()
.unwrap_or_else(|e| e.into_inner())
.take();
match built {
// Still building: the panorama stays up.
None => return Ok(()),
Some(Ok(terrain)) => self.install_backdrop(terrain)?,
Some(Err(e)) => {
// The panorama stays up for good.
log::warn!("Horizon: title backdrop: {e}");
self.backdrop.installed = true;
return Ok(());
}
}
}
let found = *self.backdrop.spot.lock().unwrap_or_else(|e| e.into_inner());
let Some(Some((x, z))) = found else {
return Ok(());
};
if !self.backdrop.centred {
self.backdrop.centred = true;
self.streaming.center = (x >> 4, z >> 4);
self.streaming.paused = false;
}
self.update_world();
if self.backdrop.camera.is_none()
&& (-2..=2)
.all(|dz| (-2..=2).all(|dx| self.streaming.is_lit((x >> 4) + dx, (z >> 4) + dz)))
{
// Above the tallest block nearby, so no spike pokes through the lens.
let mut top = 64;
for dz in (-12..=12).step_by(3) {
for dx in (-12..=12).step_by(3) {
if let Some(y) = self.surface_y(x + dx, z + dz) {
top = top.max(y);
}
}
}
let ground = self.surface_y(x, z).unwrap_or(top);
let y = (ground + 22).max(top + 4);
self.backdrop.camera = Some(glam::DVec3::new(
f64::from(x) + 0.5,
f64::from(y),
f64::from(z) + 0.5,
));
}
if self.backdrop.camera.is_some()
&& self.backdrop.ready.is_none()
&& self
.renderer
.as_ref()
.is_some_and(|r| r.section_count() > 40)
{
self.backdrop.ready = Some(Instant::now());
log::info!(
"Horizon: title backdrop ready; world rest ready: {}",
self.res.rest.get().is_some()
);
}
Ok(())
}
/// The world tick of the backdrop: time passes for clouds and snow only.
pub(super) fn tick_backdrop(&mut self) {
if self.backdrop.active {
self.world.game_time += 1;
// The snow's fall follows the client tick counter.
self.ticks += 1;
}
}
fn surface_y(&self, x: i32, z: i32) -> Option<i32> {
let air = self.res.facts().air;
(-60..320).rev().find(|&y| self.world.block(x, y, z) != air)
}
/// Start building the generator and finding the spot on a worker
/// (`VanillaTerrain::new` takes seconds on a cold cache).
fn start_backdrop(&mut self) -> Result<()> {
log::info!(
"Horizon: starting title backdrop after {} ms",
self.started.elapsed().as_millis()
);
let seed = seed();
let dir = self.backdrop_root()?.join(format!("{seed}"));
std::fs::create_dir_all(&dir)?;
// The streaming is replaced once the generator is built.
self.streaming.paused = true;
let mut world = World::new(self.res.facts().air, seed);
world.day_time = DAY_TIME;
world.game_time = 6000;
// Light snow: the weather renders as snow in frozen biomes.
world.weather = Weather {
clear_time: 0,
rain_time: i32::MAX / 2,
thunder_time: i32::MAX / 2,
raining: true,
thundering: false,
rain_level: (0.35, 0.35),
thunder_level: (0.0, 0.0),
};
self.world = world;
self.dim = super::Dim::Overworld;
if let Some(r) = self.renderer.as_mut() {
r.clear_sections();
}
self.backdrop = Backdrop {
active: true,
started: Some(Instant::now()),
..Default::default()
};
let (terrain, spot) = (self.backdrop.terrain.clone(), self.backdrop.spot.clone());
let worldgen = self.options.resources.join("worldgen");
let registry = self.pack.assets.registry;
let biomes = self.res.biomes().clone();
let cache = dir.join("spot.txt");
std::thread::Builder::new()
.name("horizon-backdrop".into())
.spawn(move || {
let built = Instant::now();
let inner = match VanillaTerrain::new(&worldgen, registry, &biomes, seed) {
Ok(t) => Arc::new(t),
Err(e) => {
*terrain.lock().unwrap_or_else(|e| e.into_inner()) =
Some(Err(e.to_string()));
return;
}
};
log::info!(
"Horizon: title backdrop generator built in {} ms",
built.elapsed().as_millis()
);
*terrain.lock().unwrap_or_else(|e| e.into_inner()) = Some(Ok(inner.clone()));
// Find (or recall) the spot.
let known = std::fs::read_to_string(&cache).ok().and_then(|t| {
let mut it = t.split_whitespace().map(|v| v.parse::<i32>().ok());
Some((it.next()??, it.next()??))
});
let found = known.or_else(|| {
let allowed = |name: &str| name == BIOME;
let search = horizon_world::worldgen::generator::BiomeSearch {
allowed: &allowed,
origin: [0, 64, 0],
radius: 6400,
horizontal: 32,
vertical: 64,
min_y: -64,
max_y: 320,
};
let found = inner.find_closest_biome(&search);
log::info!("Horizon: title backdrop: {BIOME} at {found:?}");
let (_, p) = found?;
let _ = std::fs::write(&cache, format!("{} {}\n", p[0], p[2]));
Some((p[0], p[2]))
});
*spot.lock().unwrap_or_else(|e| e.into_inner()) =
Some(Some(found.unwrap_or((0, 0))));
})?;
Ok(())
}
fn backdrop_root(&self) -> Result<std::path::PathBuf> {
Ok(std::env::current_dir()?
.join("saves")
.join(".horizon-title")
.join("backdrop"))
}
/// The built generator streams the backdrop's chunks.
fn install_backdrop(&mut self, inner: Arc<VanillaTerrain>) -> Result<()> {
let seed = seed();
let save = Arc::new(SaveDir::new(self.backdrop_root()?.join(format!("{seed}"))));
let (res, pack) = (&*self.res, &self.pack);
let mut streaming = Streaming::new(
Arc::new(Persistent {
inner,
save: save.clone(),
registry: pack.assets.clone(),
biomes: res.biomes().clone(),
}),
pack.context.clone(),
res.threads().min(6),
);
streaming.radius = self.settings.render_distance.clamp(4, 10);
streaming.biome_blend = self.settings.biome_blend;
streaming.smooth_lighting = self.settings.smooth_lighting;
streaming.cutout_leaves = self.settings.cutout_leaves;
streaming.cull_leaves = self.settings.horizon.cull_leaves;
streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed));
streaming.paused = true;
self.streaming = streaming;
self.save = save;
self.backdrop.installed = true;
Ok(())
}
fn stop_backdrop(&mut self) {
self.streaming.paused = true;
self.world = World::new(self.res.facts().air, 0);
if let Some(r) = self.renderer.as_mut() {
r.clear_sections();
}
self.backdrop = Backdrop::default();
}
}
+10 -3
View File
@@ -57,7 +57,7 @@ pub(super) const CHEST_SLOTS: usize = 27;
const WIDTH: f64 = 1.375;
const HEIGHT: f64 = 0.5625;
/// Player.DEFAULT_VEHICLE_ATTACHMENT minus the boat's passenger attachment.
const SEAT: f64 = 0.1875 - 0.6;
pub(super) const SEAT: f64 = 0.1875 - 0.6;
impl Boat {
pub fn new(id: u32, wood: Arc<str>, position: Vec3, yaw: f32) -> Self {
Self {
@@ -295,7 +295,7 @@ impl Game<'_> {
}
}
/// `AbstractBoat.tick` for one boat (`controlled` when the player rides it).
fn tick_boat(&mut self, mut b: Boat, controlled: bool) -> Boat {
pub(super) fn tick_boat(&mut self, mut b: Boat, controlled: bool) -> Boat {
b.previous = b.position;
b.previous_yaw = b.yaw;
b.old_status = b.status;
@@ -448,9 +448,12 @@ impl Game<'_> {
pub(super) fn tick_boats(&mut self) {
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
// A server player's boat is driven by its client (lan_vehicles.rs).
let driven = self.guest_vehicles();
for i in 0..self.boats.len() {
let p = self.boats[i].position;
if Some(self.boats[i].id) == self.riding
|| driven.contains(&self.boats[i].id)
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
{
continue;
@@ -659,7 +662,11 @@ impl Game<'_> {
self.right = false;
return true;
}
if sneaking || self.boats[i].out_of_control >= 60.0 || self.riding.is_some() {
if sneaking
|| self.boats[i].out_of_control >= 60.0
|| self.riding.is_some()
|| self.ridden_by_guest(self.boats[i].id)
{
return false;
}
self.riding = Some(self.boats[i].id);
+49 -21
View File
@@ -294,6 +294,18 @@ impl Game<'_> {
}
// ---- entities -------------------------------------------------------
/// The level `t` is in (`Entity.level`): a server's players have their
/// own, which need not be the one in place; everything else is in the
/// level in place.
pub(super) fn target_level(&self, t: Target) -> Dim {
let conn = match t {
Target::Player => self.lan_acting,
Target::Guest(conn) => Some(conn),
_ => None,
};
conn.and_then(|c| self.command_guest(c))
.map_or(self.dim, |g| Dim::from_id(&g.dimension))
}
pub(super) fn target_position(&self, t: Target) -> Option<[f64; 3]> {
match t {
Target::Player => self
@@ -1191,15 +1203,12 @@ impl Game<'_> {
pos: [f64; 3],
rotation: Option<[f32; 2]>,
) -> bool {
let (conn, at) = match t {
Target::Player => (self.lan_acting, self.dim),
Target::Guest(conn) => (
Some(conn),
self.command_guest(conn)
.map_or(self.dim, |g| super::Dim::from_id(&g.dimension)),
),
_ => (None, self.dim),
let conn = match t {
Target::Player => self.lan_acting,
Target::Guest(conn) => Some(conn),
_ => None,
};
let at = self.target_level(t);
let Some(conn) = conn.filter(|_| at != level && self.options.dedicated.is_some()) else {
return false;
};
@@ -1222,12 +1231,7 @@ impl Game<'_> {
let dest = self.entities(ctx, "destination", false)?[0];
let pos = self.target_position(dest).unwrap_or(self.source_position());
// Into the destination's level.
let level = match dest {
Target::Guest(conn) => self
.command_guest(conn)
.map_or(self.dim, |g| super::Dim::from_id(&g.dimension)),
_ => self.dim,
};
let level = self.target_level(dest);
// TeleportCommand.teleportToEntity: the destination's rotation too.
let rotation = Some(self.target_rotation(dest));
for &t in &targets {
@@ -2281,12 +2285,23 @@ impl Game<'_> {
};
let yaw = ((rot[0] + 180.0).rem_euclid(360.0)) - 180.0;
let pitch = rot[1].clamp(-90.0, 90.0);
self.spawn = Some(Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
));
self.respawn_config = None;
// SetSpawnCommand: a forced point in the source's level.
if self.dim == Dim::Overworld {
self.spawn = Some(Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
));
self.respawn_config = None;
} else {
self.spawn = None;
self.respawn_config = Some(super::respawn_anchor::RespawnConfig {
dim: self.dim,
pos,
yaw,
forced: true,
});
}
let dim = Text::literal(self.dim.id());
let p = pos.map(|v| Text::literal(v.to_string()));
let mut args = vec![
@@ -2322,7 +2337,20 @@ impl Game<'_> {
Some(Arg::Coords(c)) => c.rotation(self.source_rotation()),
_ => [0.0, 0.0],
};
self.level.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]);
// LevelData.setRespawnData: the world's spawn (level.dat `spawn`).
let old = self.level.world_spawn.replace(pos);
self.level.world_spawn_angle = rot;
// A player whose fallback is the world spawn (no spawnpoint of its
// own; a bed or an anchor that is gone falls back to it) respawns at
// the new one.
let floor = |s: Vec3| [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32];
if self.spawn.map(floor) == old {
self.spawn = Some(Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
));
}
let args = [
Text::literal(pos[0].to_string()),
Text::literal(pos[1].to_string()),
@@ -155,14 +155,20 @@ impl Game<'_> {
_ => s.pos,
}
}
/// Evaluate `f` with `source` as the command source.
/// Evaluate `f` with `source` as the command source, in the source's
/// level (`CommandSourceStack.getLevel`): a server puts that level in
/// place for it.
pub(in crate::game) fn with_source<T>(
&mut self,
source: Source,
f: impl FnOnce(&mut Self) -> T,
) -> T {
let previous = self.command_source.replace(source);
let back = self.enter_command_level(source.dimension);
let out = f(self);
if let Some(back) = back {
self.enter_command_level(back);
}
self.command_source = previous;
out
}
@@ -447,11 +453,13 @@ impl Game<'_> {
"at" => targets(self)?
.into_iter()
.filter_map(|t| {
// CommandSourceStack.withLevel(entity.level()).
let level = self.target_level(t);
Some(Source {
pos: self.target_position(t)?,
rot: self.target_rotation(t),
dimension: self.dim,
level: None,
dimension: level,
level: (level != self.dim).then_some(level),
..s
})
})
@@ -810,7 +810,10 @@ impl Game<'_> {
None => break,
},
};
if self.slot_get(slot) != item && self.slot_set(slot, item) {
// ItemStack.isEmpty: air (or a count of 0) is an empty slot.
// SlotAccess.set counts every slot it sets, the same item too.
let item = item.filter(|s| &*s.item != "minecraft:air" && s.count > 0);
if self.slot_set(slot, item) {
changed += 1;
}
}
+44 -1
View File
@@ -42,6 +42,7 @@ const HELP: &[&str] = &[
"chat MESSAGE send chat or a /command to the server",
"disconnect leave the server for the server list",
"respawn respawn after death on a server",
"credits [poem] [SCROLL] roll the credits (with the end poem), or hold them SCROLL pixels in",
"quit save and exit",
];
@@ -117,6 +118,7 @@ impl Game<'_> {
self.answer(request, event_loop);
}
while let Some(request) = self.control.as_ref().and_then(|c| c.try_recv()) {
self.agent_command_seen();
self.answer(request, event_loop);
if self.pending_save.is_some() {
break;
@@ -125,6 +127,11 @@ impl Game<'_> {
if self.control.is_some() {
self.watch_events();
}
if self.screen == Screen::Options
&& self.ui.options.page() == horizon_client::options_ui::Page::Agent
{
self.ui.options.agent_status = self.agent_status_lines();
}
}
fn answer(&mut self, request: horizon_client::control::Request, event_loop: &ActiveEventLoop) {
@@ -165,6 +172,9 @@ impl Game<'_> {
if let Some(value) = self.events_command(&words, reply)? {
return Ok(value);
}
if let Some(value) = self.saves_control(&words, line, reply)? {
return Ok(value);
}
if let Some(value) = self.options_control(&words, line)? {
return Ok(Some(value));
}
@@ -192,6 +202,7 @@ impl Game<'_> {
.chain(super::ui_control::HELP)
.chain(super::options::CONTROL_HELP)
.chain(super::events::HELP)
.chain(super::saves_control::HELP)
.chain(super::pad::HELP)
.collect::<Vec<_>>() }))),
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
@@ -564,6 +575,10 @@ impl Game<'_> {
"graphics" => Page::Graphics,
"graphics-advanced" => Page::GraphicsAdvanced,
"extras" => Page::Extras,
"credits" => Page::Credits,
"horizon" => Page::Horizon,
"agent" => Page::Agent,
"shader-packs" => Page::ShaderPacks,
other => return Err(format!("unknown options page {other}").into()),
};
if self.screen == Screen::Playing && self.title.is_none() {
@@ -639,6 +654,25 @@ impl Game<'_> {
self.connect_server(arg(1)?, &name)?;
ok()
}
"credits" => {
let poem = words.get(1) == Some(&"poem");
let hold = words
.get(1 + usize::from(poem))
.map(|s| s.parse::<f32>())
.transpose()?;
if self.screen != Screen::Win {
let finish = if self.screen == Screen::Options {
super::win::Finish::Options
} else {
super::win::Finish::Closed
};
self.open_win_screen(poem, finish);
}
if let Some(scroll) = hold {
self.hold_win_screen(scroll);
}
ok()
}
"respawn" => {
if self.remote.is_none() || self.screen != Screen::Dead {
return Err("respawn needs the death screen on a server".into());
@@ -721,6 +755,9 @@ impl Game<'_> {
}
fn screen_name(&self) -> &'static str {
if self.screen == Screen::Win {
return "win";
}
if self.title.is_some() {
return "title";
}
@@ -736,7 +773,9 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
}
}
@@ -847,6 +886,8 @@ impl Game<'_> {
"source_attempted": self.lod_source_attempted,
"active_tiles": self.lod.as_ref().map_or(0, |lod| lod.stats().0),
"cached_tiles": self.lod.as_ref().map_or(0, |lod| lod.stats().1),
"far_detail": self.settings.horizon.far_detail.name(),
"resident_quads": self.renderer.as_ref().map_or(0, |r| r.lod_quads()),
"pending_observations": self.lod_observe.len(),
"refined_samples": self.lod.as_ref().map_or(0, |lod| lod.refined_samples()),
});
@@ -903,7 +944,7 @@ impl Game<'_> {
"streaming": self.streaming.stages().into_iter().map(|(k, v)| (k.to_string(), v.into())).collect::<serde_json::Map<_, _>>(),
"dirty_light": self.world.dirty_light.len(),
"renderer": renderer,
"display": self.window.as_ref().and_then(|w| w.current_monitor()).map(|m| json!({
"display": self.window.as_deref().and_then(horizon_client::telemetry::monitor).map(|m| json!({
"width": m.size().width,
"height": m.size().height,
"scale": m.scale_factor(),
@@ -926,6 +967,8 @@ impl Game<'_> {
status["heard"] = json!(self.audio.heard);
// Boats, minecarts, armor stands, item frames and paintings.
status["objects"] = json!(self.objects_status());
status["lightning"] = json!({"bolts": self.bolts.len(), "struck": self.lightning_seen[0],
"flashes": self.lightning_seen[1], "flash": self.flash});
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
status["projectiles"] = json!(self.projectiles_status());
status
+9 -1
View File
@@ -330,6 +330,10 @@ impl Game<'_> {
"held": m.extra.main_hand.as_deref(),
"mount": m.extra.mount,
"rider": m.extra.rider,
// A player's input this tick, and whether it steers.
"ridden": m.rider.map(|r| r.steer),
"controlled": horizon_client::mobs::equine::controlled(m),
"saddled": m.extra.saddled,
"enchants": horizon_client::mobs::gear::gear(m).map(|g| g.slots.iter().map(|s| s.iter().map(|(e, l)| format!("{e}:{l}")).collect::<Vec<_>>()).collect::<Vec<_>>()),
"ints": m.extra.ints,
"pois": [m.extra.home, m.extra.bed, m.extra.meeting],
@@ -339,8 +343,12 @@ impl Game<'_> {
"on_ground": m.on_ground,
"variant": m.extra.variant,
"color": m.extra.color,
"sheared": m.extra.sheared,
"burning": m.fire_ticks > 0,
"size": m.extra.size,
"leash": m.extra.leash.map(|h| format!("{h:?}")),
"tame": m.extra.tame,
"sitting": m.extra.sitting,
"temper": m.extra.variant3,
"chested": m.extra.chested,
"head": m.extra.head.as_deref(),
@@ -500,7 +508,7 @@ impl Game<'_> {
// The level random, lent to the mobs (brain behaviours draw from
// it) and taken back after their ticks.
let mut scratch = self.world.random.clone();
let mut pushes = Vec::new();
let mut pushes = horizon_client::mobs::PendingPushes::default();
let mut keep = Vec::with_capacity(mobs.len());
let mut grid =
horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds));
@@ -291,12 +291,12 @@ impl Game<'_> {
used = self.fixture_use_item(origin, op)?;
} else if let Some(op) = case.get("respawn_at") {
// ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at the origin.
let config = super::respawn_anchor::RespawnConfig {
dim: self.dim,
pos: [origin.x, origin.y, origin.z],
yaw: 0.0,
forced: op["forced"].as_bool().unwrap_or(false),
};
let config = super::respawn_anchor::RespawnConfig::wrapped(
self.dim,
[origin.x, origin.y, origin.z],
op["yaw"].as_f64().map_or(0.0, |v| v as f32),
op["forced"].as_bool().unwrap_or(false),
);
let found =
self.find_respawn_and_use(config, op["consume"].as_bool().unwrap_or(true))?;
used.push(match found {
+3
View File
@@ -2697,9 +2697,12 @@ impl Game<'_> {
velocity: [d.velocity.x, d.velocity.y, d.velocity.z],
data: 0,
meta,
defaults: Vec::new(),
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
needs_sync: false,
leash: None,
})
}
}
@@ -8,6 +8,15 @@ use super::Game;
use horizon_client::{enchant::EffectContext, items::ItemStack};
use horizon_core::random::RandomSource;
/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`).
#[derive(Clone, Copy)]
enum MendSlot {
Main,
Off,
/// An `armor` index (head first).
Armor(usize),
}
impl Game<'_> {
/// `Player.getDestroySpeed` after the tool speed: mining efficiency, haste
/// and mining fatigue.
@@ -314,36 +323,29 @@ impl Game<'_> {
pub(super) fn mending(&mut self, amount: u32) -> u32 {
let mut amount = amount;
loop {
// EnchantmentHelper.getRandomItemWith(REPAIR_WITH_XP, damaged): held and armor.
let mut candidates: Vec<(bool, usize)> = Vec::new();
if let Some(s) = &self.inventory[self.selected]
&& s.damage > 0
&& s.enchantment_level("minecraft:mending") > 0
{
candidates.push((false, self.selected));
}
for (i, s) in self.armor.iter().enumerate() {
if let Some(s) = s
&& s.damage > 0
&& s.enchantment_level("minecraft:mending") > 0
{
candidates.push((true, i));
}
}
// EnchantmentHelper.getRandomItemWith(REPAIR_WITH_XP, damaged), in
// EquipmentSlot order: the main hand, the off hand, then feet, legs,
// chest and head (`armor` holds head first).
let mending = |s: &Option<ItemStack>| {
s.as_ref()
.is_some_and(|s| s.damage > 0 && s.enchantment_level("minecraft:mending") > 0)
};
let candidates: Vec<MendSlot> = [MendSlot::Main, MendSlot::Off]
.into_iter()
.chain((0..self.armor.len()).rev().map(MendSlot::Armor))
.filter(|&slot| mending(self.mend_slot(slot)))
.collect();
if candidates.is_empty() {
return amount;
}
let (armor, i) = candidates[self
let slot = candidates[self
.world
.random
.next_int_bound(candidates.len() as i32)
.unwrap_or(0) as usize];
let stack = if armor {
self.armor[i].clone()
} else {
self.inventory[i].clone()
let Some(stack) = self.mend_slot(slot).clone() else {
return amount;
};
let Some(stack) = stack else { return amount };
let ctx = EffectContext {
items: Some(self.res.items()),
..Default::default()
@@ -356,12 +358,7 @@ impl Game<'_> {
amount as f32,
) as u32;
let repaired = to_repair_xp.min(stack.damage);
let slot = if armor {
&mut self.armor[i]
} else {
&mut self.inventory[i]
};
if let Some(s) = slot.as_mut() {
if let Some(s) = self.mend_slot_mut(slot).as_mut() {
s.damage -= repaired;
}
if repaired == 0 || to_repair_xp == 0 {
@@ -374,6 +371,20 @@ impl Game<'_> {
amount = remaining;
}
}
fn mend_slot(&self, slot: MendSlot) -> &Option<ItemStack> {
match slot {
MendSlot::Main => &self.inventory[self.selected],
MendSlot::Off => &self.offhand,
MendSlot::Armor(i) => &self.armor[i],
}
}
fn mend_slot_mut(&mut self, slot: MendSlot) -> &mut Option<ItemStack> {
match slot {
MendSlot::Main => &mut self.inventory[self.selected],
MendSlot::Off => &mut self.offhand,
MendSlot::Armor(i) => &mut self.armor[i],
}
}
/// Bow enchantments at release: (extra base damage, infinity keeps the arrow).
pub(super) fn bow_enchantments(&mut self) -> (f64, bool) {
let Some(bow) = self.inventory[self.selected].clone() else {
+45 -52
View File
@@ -23,7 +23,7 @@ const GATEWAY_FILE: &str = "horizon-end-gateways.json";
/// A gateway teleport waiting for its destination chunks.
#[derive(Clone, Copy, Debug)]
enum GatewayJob {
pub(super) enum GatewayJob {
/// TheEndGatewayBlockEntity.findOrCreateValidTeleportPos from this gateway.
Find { gateway: [i32; 3] },
/// A known exit (exact, or findExitPosition around it).
@@ -138,47 +138,12 @@ impl Game<'_> {
}
}
/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times,
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
pub(super) fn end_sky_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::with_capacity(6 * 256 * 4);
let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else {
/// SkyRenderer.renderEndFlash, drawn after the renderer's resident sky mesh.
pub(super) fn end_flash_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::new();
// The old combined sky/flash draw also skipped the flash without a sky sprite.
if !self.gui.atlas.sprites.contains_key("environment/end_sky") {
return out;
};
use std::f32::consts::FRAC_PI_2;
let faces = [
glam::Mat4::IDENTITY,
glam::Mat4::from_rotation_x(FRAC_PI_2),
glam::Mat4::from_rotation_x(-FRAC_PI_2),
glam::Mat4::from_rotation_x(std::f32::consts::PI),
glam::Mat4::from_rotation_z(FRAC_PI_2),
glam::Mat4::from_rotation_z(-FRAC_PI_2),
];
let step = 200.0 / 16.0;
for pose in faces {
for a in 0..16 {
for b in 0..16 {
let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32);
let (x1, z1) = (x0 + step, z0 + step);
let corners = [
(x0, z0, [r.u0, r.v0]),
(x0, z1, [r.u0, r.v1]),
(x1, z1, [r.u1, r.v1]),
(x1, z0, [r.u1, r.v0]),
];
for (x, z, uv) in corners {
let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z));
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 2,
color: 0xFF28_2828,
light: 0,
});
}
}
}
}
// SkyRenderer.renderEndFlash: the end_flash sprite at height 100, scale 60.
let intensity = self.end.flash.intensity(self.clock.fraction() as f32);
@@ -377,7 +342,10 @@ impl Game<'_> {
f64::from(p.dimensions.width),
f64::from(p.dimensions.height),
);
if portal {
if portal && self.dim == Dim::End && !self.level.seen_credits {
// EndPortalBlock.entityInside: the first exit shows the credits.
self.show_end_credits()?;
} else if portal {
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
Dim::Overworld
@@ -448,7 +416,15 @@ impl Game<'_> {
f64::from(END_SPAWN[2]) + 0.5,
));
}
// Leaving the End: the respawn position (the world spawn here).
// Leaving the End: the respawn position, a bed's found once it has
// loaded (findRespawnPositionAndUseSpawnBlock, not using it up).
if let Some(c) = self.respawn_config.filter(|c| c.dim == target) {
return Some(Vec3::new(
f64::from(c.pos[0]) + 0.5,
f64::from(c.pos[1]),
f64::from(c.pos[2]) + 0.5,
));
}
let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]);
Some(Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5))
}
@@ -519,7 +495,16 @@ impl Game<'_> {
// Direction.WEST.toYRot().
return Ok((target, Some(90.0)));
}
// ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column.
// ServerPlayer.findRespawnPositionAndUseSpawnBlock: where the bed or
// anchor puts the player, facing it; else onto the spawn column.
let mut target = target;
if let Some(c) = self.respawn_config.filter(|c| c.dim == self.dim) {
if let Some((at, yaw)) = self.find_respawn_and_use(c, false)? {
return Ok((at, Some(yaw)));
}
let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]);
target = Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5);
}
let y = self
.land_column(target.x.floor() as i32, target.z.floor() as i32)
.map_or(target.y, f64::from);
@@ -735,6 +720,20 @@ impl Game<'_> {
fn enter_gateway(&mut self, gateway: [i32; 3]) -> Result<()> {
// TheEndGatewayBlockEntity.triggerCooldown: 40 ticks.
self.end.gateway_cooldown = 40;
let (job, destination) = self.gateway_job(gateway);
let Some(player) = self.player.take() else {
return Ok(());
};
self.end.job = Some(job);
self.end_travel = true;
self.travelling = Some((player, destination));
Ok(())
}
/// Where `gateway` leads (TheEndGatewayBlockEntity.getPortalPosition):
/// its exit, or the search for one, and the spot to load before either
/// is resolved ([`Game::resolve_gateway`]).
pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) {
let known = self.gateway_exits().get(&gateway).copied();
let job = match known {
Some((exit, exact)) => GatewayJob::Known { exit, exact },
@@ -760,13 +759,7 @@ impl Game<'_> {
Vec3::new(d.x, 75.0, d.y)
}
};
let Some(player) = self.player.take() else {
return Ok(());
};
self.end.job = Some(job);
self.end_travel = true;
self.travelling = Some((player, destination));
Ok(())
(job, destination)
}
fn chunk_empty(&self, x: f64, z: f64) -> Option<bool> {
@@ -803,7 +796,7 @@ impl Game<'_> {
/// The teleport position of a gateway job, creating the exit gateway (and
/// an island when the chunk has no landing spot) for new destinations.
fn resolve_gateway(&mut self, job: GatewayJob, target: Vec3) -> Result<Vec3> {
pub(super) fn resolve_gateway(&mut self, job: GatewayJob, target: Vec3) -> Result<Vec3> {
let bottom_center = |p: [i32; 3]| {
Vec3::new(
f64::from(p[0]) + 0.5,
+29 -1
View File
@@ -224,7 +224,7 @@ impl Game<'_> {
}
set.entries().map(|(k, _)| k.0).collect()
}
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT);
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT, minecarts);
/// the player takes `damage_type`.
/// `ServerExplosion.hurtEntities` for the player: damage scaled by
/// distance and exposure, through a raised shield (`hurtServer` blocks
@@ -460,6 +460,34 @@ impl Game<'_> {
);
}
self.tnts = tnts;
// Minecarts: VehicleEntity.hurtServer (explosions ignite TNT carts),
// then the push from their eyes (0.85 of their height).
let ids: Vec<u32> = self.carts.iter().map(|c| c.id).collect();
for id in ids {
let Some(i) = self.carts.iter().position(|c| c.id == id) else {
continue;
};
let bounds = self.carts[i].bounds();
let feet = self.carts[i].position;
let dist = distance([feet.x, feet.y, feet.z]) / diameter;
if dist > 1.0 {
continue;
}
let (lo, hi) = (bounds.min_position(), bounds.max_position());
let exposure = self.seen_percent(center, [lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]);
self.hurt_cart(i, damage(dist, exposure), false, true);
let Some(c) = self.carts.iter_mut().find(|c| c.id == id) else {
continue;
};
let eye_height = f64::from((hi.y - lo.y) as f32 * 0.85f32);
let dir = direction([feet.x, feet.y + eye_height, feet.z]);
let power = (1.0 - dist) * f64::from(exposure);
c.velocity = Vec3::new(
c.velocity.x + dir[0] * power,
c.velocity.y + dir[1] * power,
c.velocity.z + dir[2] * power,
);
}
}
/// `Level.explode` on the server: positions, entities, blocks, fire; then
/// the client's explosion sound.
+59 -12
View File
@@ -1,4 +1,5 @@
//! Play with friends, host side: "Invite friends" opens the world to LAN if
//! Play with friends, host side: "Start Sharing" on the Play with Friends
//! screen (`friends_screen`, the pause menu's Friends button) opens the world to LAN if
//! it isn't (with Open to LAN's defaults) and shares that port behind an
//! invite code (horizon-friends). The code holds this computer's addresses
//! and the key, so friends join with no server of ours; a relay the player
@@ -6,7 +7,12 @@
//! LAN one, unchanged: tunnelled guests are LAN guests that connect from the
//! loopback address.
use super::{Game, lan::LanSettings};
use horizon_client::{Result, front::FriendsView, text::Text};
use horizon_client::{
Result,
friends_screen::{self, Action, FriendsView},
hud::HudBatch,
text::Text,
};
use horizon_friends::{Host, HostConfig, HostEvent, PathMode, host::DEFAULT_PORT, reach, stun};
use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION};
use std::time::{Duration, Instant};
@@ -52,10 +58,12 @@ impl Game<'_> {
if self.friends.is_some() {
return Ok(());
}
if self.remote.is_some() || self.title.is_some() {
// Single player on its server thread shares that server, as Open to
// LAN publishes it; another server can't be shared.
if self.title.is_some() || (self.remote.is_some() && self.integrated.is_none()) {
return Err("open a singleplayer world first".into());
}
let opened_lan = self.lan.is_none();
let opened_lan = self.lan_port().is_none();
if opened_lan {
// ShareToLanScreen's defaults, as the world options screen offers them.
self.lan_open(LanSettings {
@@ -153,7 +161,7 @@ impl Game<'_> {
}
if announce {
self.system_message(Text::literal(
"Your invite code is ready in the pause menu: copy it and send it to your friends.",
"Your invite code is ready: Game Menu, Play with Friends. Copy it and send it to your friends.",
));
}
}
@@ -169,16 +177,55 @@ impl Game<'_> {
}
}
/// What the pause menu shows.
/// Play with Friends. The world is paused under it in singleplayer, so
/// new codes and sessions are read while it is drawn.
pub(super) fn draw_friends_screen(&mut self, batch: &mut HudBatch) {
self.tick_friends();
let view = self.friends_view();
friends_screen::draw(batch, &self.gui.atlas, self.cursor, &view, true);
}
pub(super) fn friends_screen_click(&mut self) {
let view = self.friends_view();
let Some(action) =
friends_screen::click(&self.gui.atlas, self.gui_size(), self.cursor, &view)
else {
return;
};
self.audio.play_button_click();
match action {
Action::Share => {
if let Err(e) = self.friends_start() {
self.system_message(Text::literal(format!("Couldn't share the world: {e}")));
}
}
Action::Copy => self.friends_copy(),
Action::Stop => self.friends_stop(),
// The system browser, as the Shader Packs page opens its folder.
Action::Help => {
if let Some(url) = &view.help {
super::packs::open_folder(std::path::Path::new(url));
}
}
Action::Done => self.screen = super::Screen::Paused,
}
}
/// What Play with Friends shows.
pub(super) fn friends_view(&self) -> FriendsView {
let guests = self
.lan
.as_ref()
.map(|h| h.hub.guests.iter().map(|g| g.name.clone()).collect())
.unwrap_or_default();
let guests = match &self.lan {
Some(h) => h.hub.guests.iter().map(|g| g.name.clone()).collect(),
// On the server thread: the other players the server lists.
None if self.integrated.is_some() => {
let me = self.options.player_name();
let mut names = self.remote_online_names().unwrap_or_default();
names.retain(|n| *n != me);
names
}
None => Vec::new(),
};
let Some(s) = &self.friends else {
return FriendsView {
shown: self.remote.is_none(),
shown: self.remote.is_none() || self.integrated.is_some(),
..FriendsView::default()
};
};
+6 -4
View File
@@ -6,10 +6,12 @@
//! the world's options) with [`Integrated::call`], as vanilla's client calls
//! into its `IntegratedServer`.
//!
//! Opt-in again (`--server-thread` or `HORIZON_SERVER_THREAD=1`): it was the
//! default for one day, but a server's players can't board, ride or hit
//! boats and minecarts yet (#1222), and single player's window is one of
//! them here.
//! Opt-in again (`--server-thread` or `HORIZON_SERVER_THREAD=1`) until a
//! server's players reach parity with the in-frame world: on the server
//! thread, signs open no editor, books don't open, a totem doesn't save its
//! holder and death keeps the inventory (#1380, #1366, #1292, #1284 and the
//! other `[server-thread]` issues). LAN guests and dedicated servers use the
//! same code either way.
use super::{
Game, Options, PackResources, Resources, UiResources,
lan::{LanSettings, Owner},
+79 -14
View File
@@ -14,7 +14,7 @@ use horizon_client::{
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
playerdata,
},
mobs::Mob,
mobs::{Mob, leash::Holder},
text::Text,
};
use horizon_core::geometry::Vec3;
@@ -91,7 +91,7 @@ pub(super) fn entity_uuid(id: u32) -> u128 {
/// The SynchedEntityData index of the baby flag: AgeableMob.DATA_BABY_ID and
/// Zombie.DATA_BABY_ID are both the first entry after Mob's (16); Piglin's
/// comes after AbstractPiglin's zombification flag (17).
fn baby_index(kind: &str) -> Option<u8> {
pub(super) fn baby_index(kind: &str) -> Option<u8> {
match kind {
"minecraft:piglin" => Some(17),
"minecraft:cow"
@@ -139,7 +139,13 @@ fn baby_index(kind: &str) -> Option<u8> {
/// A mob's synched data as ServerEntity sends it (only the values that differ
/// from the defaults the client constructs), with vanilla's entry indices:
/// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses.
fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
/// `defaults` gets the defaults of the entries that can go back to theirs.
fn mob_meta(
m: &Mob,
hub: &Hub,
meta: &mut Vec<(u8, i32, Value)>,
defaults: &mut Vec<(u8, i32, Value)>,
) {
let kind = m.kind.id.as_str();
if m.fire_ticks > 0 {
meta.push((0, serializer::BYTE, Value::Byte(1)));
@@ -159,15 +165,18 @@ fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
if health != 1.0 {
meta.push((9, serializer::FLOAT, Value::Float(health)));
}
defaults.push((9, serializer::FLOAT, Value::Float(1.0)));
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2.
let flags = i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1;
if flags != 0 {
meta.push((15, serializer::BYTE, Value::Byte(flags)));
}
if m.is_baby()
&& let Some(index) = baby_index(kind)
{
meta.push((index, serializer::BOOLEAN, Value::Bool(true)));
// AgeableMob.DATA_BABY_ID (and Zombie's, Piglin's).
if let Some(index) = baby_index(kind) {
if m.is_baby() {
meta.push((index, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((index, serializer::BOOLEAN, Value::Bool(false)));
}
let e = &m.extra;
let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}"));
@@ -178,6 +187,7 @@ fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
if value != 0 {
meta.push((18, serializer::BYTE, Value::Byte(value as i8)));
}
defaults.push((18, serializer::BYTE, Value::Byte(0)));
}
"minecraft:cat" | "minecraft:wolf" => {
// TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4.
@@ -200,6 +210,13 @@ fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
if let Some(v) = id(registry, name) {
meta.push((index, serializer, Value::Id(v)));
}
// Wolf.DATA_COLLAR_COLOR and Cat's, red by default.
let collar = if kind == "minecraft:cat" { 23 } else { 21 };
let red = i32::from(horizon_client::mobs::tame::RED);
if i32::from(e.color & 15) != red {
meta.push((collar, serializer::INT, Value::Int(i32::from(e.color & 15))));
}
defaults.push((collar, serializer::INT, Value::Int(red)));
}
"minecraft:horse"
| "minecraft:donkey"
@@ -390,9 +407,14 @@ impl Game<'_> {
"placed": g.placed,
"loaded": g.loaded,
"game_mode": g.game_mode,
// ItemCooldowns: the ticks the shield an axe disabled stays down.
"shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown),
"sneaking": g.sneaking,
"sleeping": g.bed,
"health": g.health,
// The server's body: its air supply and golden hearts.
"air": g.motion.as_ref().map(|m| m.air),
"absorption": g.motion.as_ref().map(|m| m.health.absorption()),
// FoodData: food level, saturation and exhaustion.
"food": [
f64::from(g.food),
@@ -752,17 +774,37 @@ impl Game<'_> {
}
/// The entities guests track: mobs, items and the rest (game/lan_entities.rs).
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub, out: &mut States) {
/// `mob_players` is the guest each mob sees as its player (game/lan_mobs.rs).
fn lan_entities(
&self,
host_entity: Option<i32>,
mob_players: &HashMap<u32, u32>,
hub: &mut Hub,
out: &mut States,
) {
out.clear();
for m in self.mobs.iter().filter(|m| !m.removed) {
// The lead's holder: the player the mob sees (a guest, else the
// host) or another mob. A fence knot isn't an entity here.
let leash = m.extra.leash.and_then(|h| match h {
Holder::Player => mob_players
.get(&m.id)
.and_then(|conn| hub.guest(*conn))
.map(|g| g.entity_id)
.or(host_entity),
Holder::Mob(id) => Some(id as i32),
Holder::Knot(_) => None,
});
let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str());
e.position = [m.position.x, m.position.y, m.position.z];
(e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw);
e.on_ground = m.on_ground;
e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z];
mob_meta(m, hub, &mut e.meta);
e.needs_sync = m.needs_sync;
mob_meta(m, hub, &mut e.meta, &mut e.defaults);
mob_equipment(m, hub, &mut e.equipment);
self.mob_attributes(m, &mut e.attributes);
e.leash = leash;
}
for d in &self.dropped {
let stack = hub.stack(&Some(d.stack.clone()));
@@ -800,6 +842,16 @@ impl Game<'_> {
self.send_admin_feedback(&mut host, None);
}
let state = self.lan_host_state(&host);
// An animal whose rider left the game (or the level) stops taking
// its input.
for m in &mut self.mobs {
if m.rider.is_some()
&& self.riding != Some(m.id)
&& !host.hub.guests.iter().any(|g| g.vehicle == Some(m.id))
{
m.rider = None;
}
}
// A dedicated server runs the hub without a host player.
if state.is_some() || host.hub.config.dedicated {
let has_guests = !host.hub.guests.is_empty();
@@ -807,11 +859,21 @@ impl Game<'_> {
if has_guests {
let host_entity = state.as_ref().map(|s| s.entity_id);
self.lan_assign_ids();
self.lan_riding(host_entity, &mut host.hub.riding);
self.lan_entities(host_entity, &mut host.hub, &mut states);
let guests: Vec<(u32, i32)> = host
.hub
.guests
.iter()
.filter_map(|g| Some((g.vehicle?, g.entity_id)))
.collect();
self.lan_riding(host_entity, &guests, &mut host.hub.riding);
self.lan_entities(host_entity, &host.mob_players, &mut host.hub, &mut states);
} else {
states.clear();
}
// ServerEntity.sendChanges clears needsSync once it has looked.
for m in &mut self.mobs {
m.needs_sync = false;
}
let entities = states.as_slice();
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
@@ -992,7 +1054,7 @@ impl Game<'_> {
return;
}
// A dedicated server has no host player.
self.lan_entities(None, &mut host.hub, &mut theirs);
self.lan_entities(None, &host.mob_players, &mut host.hub, &mut theirs);
theirs.as_slice()
} else {
entities
@@ -1227,7 +1289,7 @@ impl Game<'_> {
};
let atlas = &self.gui.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
for m in host.models.values() {
for (conn, m) in &host.models {
let entity_start = out.len();
let light = self.world.light(
m.position.x.floor() as i32,
@@ -1242,7 +1304,10 @@ impl Game<'_> {
&lookup,
packed,
self.res.mob_data(),
&self.worn_armor_layers(m),
&host.hub.guest(*conn).map_or_else(
|| self.worn_armor_layers(m),
|g| self.stack_armor_layers(&g.armor),
),
out,
);
self.held_item_geometry(m, camera, alpha, packed, true, out);
+216 -20
View File
@@ -5,7 +5,7 @@
//! blocks, attacking and the commands all behave exactly as they do for the
//! host, and every world change they cause reaches all players through the
//! block log, the level events and the entity tracker.
use super::{Game, GuestUse, Hit, Mining, Screen, lan::LanHost};
use super::{Game, GuestUse, Hit, Mining, Screen, lan::LanHost, respawn_anchor::RespawnConfig};
use horizon_client::{
command::vanilla,
containers::BlockEntity,
@@ -34,6 +34,8 @@ pub(super) struct GuestPlay {
destroy_delay: u32,
using: Option<(usize, u32)>,
use_delay: u32,
/// The shield's ItemCooldowns entry: an axe disabled it for this many ticks.
pub(super) shield_cooldown: u32,
attack_ticks: u32,
/// The main hand's item at the guest's last tick (`Game::attack_item`).
attack_item: Option<std::sync::Arc<str>>,
@@ -49,12 +51,16 @@ pub(super) struct GuestPlay {
/// Swings the guest's actions started this tick, for the players around
/// (`LivingEntity.swing` sends ClientboundSwingAnimationPacket).
swings: u32,
/// The guest's riding jump charge (`LocalPlayer.jumpRidingTicks`).
mount: super::mounts::MountState,
/// The trading screen the guest has open.
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
/// The inventory menu and the crafting table the guest crafts in.
pub(super) crafting: super::lan_crafting::GuestCrafting,
/// The workstation menu the guest has open (game/lan_stations.rs).
pub(super) station: Option<super::lan_stations::GuestStation>,
/// The mount inventory the guest has open (game/lan_mount_menu.rs).
pub(super) mount_window: Option<super::lan_mount_menu::GuestMount>,
/// The lectern the guest reads (game/lan_stations.rs).
pub(super) lectern: Option<super::lan_stations::GuestLectern>,
/// What the guest's body was given for its effects and enchantments.
@@ -113,6 +119,7 @@ pub(super) struct GuestSwap {
destroy_delay: u32,
using: Option<(usize, u32)>,
use_delay: u32,
pub(super) shield_cooldown: u32,
attack_ticks: u32,
attack_item: Option<std::sync::Arc<str>>,
swing: horizon_client::first_person::SwingState,
@@ -213,6 +220,18 @@ impl Game<'_> {
host.hub.guests[i].position[2],
);
host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new);
// The first body after joining burns, breathes and falls on as saved.
if let Some(saved) = host.hub.guests[i].loaded_body.take()
&& let Some(m) = host.hub.guests[i].motion.as_mut()
{
saved.apply(m);
}
// The saved golden hearts go on the first body of a player who
// has been here before.
let saved = host.hub.guests[i].saved_absorption.take();
if let (Some(m), Some(amount)) = (host.hub.guests[i].motion.as_mut(), saved) {
let _ = m.internal_set_absorption(amount);
}
let kept = host.hub.guests[i].logs_kept.take();
if let (Some(m), Some((hurts, attacks))) = (host.hub.guests[i].motion.as_mut(), kept) {
m.hurt_log = hurts;
@@ -286,13 +305,16 @@ impl Game<'_> {
let destroy_delay = std::mem::replace(&mut self.destroy_delay, play.destroy_delay);
let using = std::mem::replace(&mut self.using, play.using.take());
let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay);
let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown);
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
let swing = std::mem::replace(&mut self.swing, play.swing);
std::mem::swap(&mut self.mount, &mut play.mount);
let (left, right) = (self.left, self.right);
self.left = play.digging.is_some();
self.right = play.using.is_some() || self.using.is_some();
let riding = self.riding.take();
// The guest's vehicle (Entity.vehicle) for its turn.
let riding = std::mem::replace(&mut self.riding, g.vehicle);
let host_station = self.station.take();
// The guest's bed, sleep counter and respawn point; the host's
// respawn point, anchor and action bar stay theirs.
@@ -303,6 +325,7 @@ impl Game<'_> {
g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])),
);
let respawn = (self.respawn_config.take(), self.level.spawn);
self.respawn_config = g.respawn_elsewhere.as_ref().map(RespawnConfig::from_saved);
let message = self.message.take();
// The guest's own ender inventory; one the host has open goes back
// into the host's while the guest acts.
@@ -363,6 +386,7 @@ impl Game<'_> {
destroy_delay,
using,
use_delay,
shield_cooldown,
attack_ticks,
attack_item,
swing,
@@ -415,6 +439,7 @@ impl Game<'_> {
destroy_delay,
using,
use_delay,
shield_cooldown,
attack_ticks,
attack_item,
swing,
@@ -464,19 +489,22 @@ impl Game<'_> {
let bed = std::mem::replace(&mut self.sleeping, sleeping);
let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer);
let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]);
(self.respawn_config, self.level.spawn) = respawn;
let guest_respawn = std::mem::replace(&mut self.respawn_config, respawn.0);
self.level.spawn = respawn.1;
// ServerPlayer.displayClientMessage(_, true): the guest's action bar.
let guest_message = std::mem::replace(&mut self.message, message);
self.riding = riding;
let guest_vehicle = std::mem::replace(&mut self.riding, riding);
self.left = left;
self.right = right;
play.mining = std::mem::replace(&mut self.mining, mining);
play.destroy_delay = std::mem::replace(&mut self.destroy_delay, destroy_delay);
play.using = std::mem::replace(&mut self.using, using);
play.use_delay = std::mem::replace(&mut self.use_delay, use_delay);
play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown);
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
play.swing = std::mem::replace(&mut self.swing, swing);
std::mem::swap(&mut self.mount, &mut play.mount);
self.container = container;
self.screen = screen;
self.sign_edit = host_sign;
@@ -488,11 +516,19 @@ impl Game<'_> {
_ => None,
};
self.command_block_screen = host_command_block;
self.mount_menu = host_mount_menu;
// A mount inventory the guest's action opened (shift + use, or the
// inventory key while riding).
let guest_mount = std::mem::replace(&mut self.mount_menu, host_mount_menu).opened_mob();
self.keys = host_keys;
let g = &mut host.hub.guests[i];
let left_vehicle = g.vehicle.filter(|_| guest_vehicle.is_none());
if guest_vehicle.is_none() {
g.vehicle_good = None;
}
g.vehicle = guest_vehicle;
let fell_asleep = bed.is_some() && g.bed.is_none();
(g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn);
g.respawn_elsewhere = guest_respawn.map(|c| c.saved());
g.sleeping = g.bed.is_some();
if let Some((text, _)) = guest_message {
g.send(&C::SystemChat(play::SystemChat {
@@ -549,7 +585,24 @@ impl Game<'_> {
let teleported = std::mem::take(&mut m.teleported);
let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum();
g.motion = Some(Box::new(m));
if moved > 0.0001 || turned || teleported {
// Entity.teleportTo takes a rider out of its vehicle.
let left_vehicle = match g.vehicle.filter(|_| teleported) {
Some(v) => {
(g.vehicle, g.vehicle_good) = (None, None);
Some(v)
}
None => left_vehicle,
};
// ServerPlayer.dismountTo: the client hears it is out of the
// vehicle before the teleport beside it. A rider sits where its
// vehicle puts it (lan_vehicles.rs), with no teleport.
if let Some(vehicle) = left_vehicle {
g.send(&C::SetPassengers(play::SetPassengers {
vehicle: vehicle as i32,
passengers: Vec::new(),
}));
}
if g.vehicle.is_none() && (moved > 0.0001 || turned || teleported) {
host.hub.teleport(i, Some(at));
}
}
@@ -589,6 +642,9 @@ impl Game<'_> {
if opened_table {
self.lan_open_crafting(host, conn);
}
if let Some(mob) = guest_mount {
self.lan_open_mount(host, conn, mob);
}
}
/// `ServerLevel.players()` in turn: the host's own player, then each
@@ -900,16 +956,22 @@ impl Game<'_> {
}
S::Attack(p) => self.guest_attack(host, conn, p.id),
S::Interact(p) => {
if let Some((position, eye)) = self.look_at_entity(host, gi, p.id) {
let _ = (position, eye);
let before = host.hub.guests[gi].vehicle;
if self
.look_at_entity(host, gi, p.id, Some(p.location))
.is_some()
{
let swung = self.as_guest(host, conn, |g| {
let swings = g.swings_started;
let _ = g.use_item();
g.swings_started != swings
});
self.lan_swing_back(host, conn, swung);
self.guest_boarded(host, conn, before);
}
}
S::MoveVehicle(p) => self.guest_move_vehicle(host, conn, &p),
S::PaddleBoat(p) => self.guest_paddle_boat(host, conn, [p.left, p.right]),
S::SetCreativeModeSlot(p) => {
let g = &mut host.hub.guests[gi];
if !g.creative() || !(0..46).contains(&p.slot) {
@@ -938,6 +1000,14 @@ impl Game<'_> {
S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_lectern_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_mount_click(host, conn, &p) => {}
// ServerboundPlayerCommandPacket OPEN_INVENTORY: the ridden
// mount's inventory (`HasCustomInventoryScreen`).
S::PlayerCommand(p) if p.action == 5 => {
self.as_guest(host, conn, |g| {
g.open_ridden_mount_menu();
});
}
S::ContainerButtonClick(p) => {
self.lan_station_button(host, conn, p.container, p.button);
}
@@ -955,7 +1025,8 @@ impl Game<'_> {
}
S::ContainerClose(p)
if self.lan_crafting_closed(host, conn, Some(p.container))
|| self.lan_station_closed(host, conn, Some(p.container)) =>
|| self.lan_station_closed(host, conn, Some(p.container))
|| self.lan_mount_closed(host, conn, Some(p.container)) =>
{
let g = &mut host.hub.guests[gi];
if let Some(c) = g.carried.take() {
@@ -1147,19 +1218,39 @@ impl Game<'_> {
}
}
/// Aim the swapped-in player at an entity; returns its centre and the eye.
/// Aim the swapped-in player at an entity; returns where it aims and the
/// eye. A boat, minecart, armor stand, item frame or painting is aimed at
/// the point the client hit (the interact packet's location) when that
/// is on it, else at its centre.
fn look_at_entity(
&mut self,
host: &mut LanHost,
gi: usize,
id: i32,
location: Option<[f64; 3]>,
) -> Option<([f64; 3], [f64; 3])> {
let object = || {
let (lo, hi, origin) = self.object_target(id)?;
let middle = [0, 1, 2].map(|k| (lo[k] + hi[k]) / 2.0);
let Some(l) = location else {
return Some(middle);
};
let point = [0, 1, 2].map(|k| origin[k] + l[k]);
// A little inside the box, so the ray from the eye meets it.
let inside = [0, 1, 2].map(|k| {
let margin = ((hi[k] - lo[k]) / 2.0).min(0.01);
point[k].clamp(lo[k] + margin, hi[k] - margin)
});
let on = (0..3).all(|k| (point[k] - inside[k]).abs() < 0.1);
Some(if on { inside } else { middle })
};
let centre = match self.mobs.iter().find(|m| m.id as i32 == id) {
Some(m) => [
m.position.x,
m.position.y + m.kind.height * 0.5,
m.position.z,
],
None if self.object_target(id).is_some() => object()?,
// A dragon part or an end crystal (game/dragon.rs).
None => {
let b = self.tracked_special_box(id)?;
@@ -1210,7 +1301,7 @@ impl Game<'_> {
return;
}
let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch);
if self.look_at_entity(host, gi, id).is_none() {
if self.look_at_entity(host, gi, id, None).is_none() {
return;
}
self.as_guest(host, conn, |g| {
@@ -1417,17 +1508,43 @@ impl Game<'_> {
if !host.hub.guests[i].dead {
return;
}
// PlayerList.respawn: a server's player comes back in the Overworld,
// where the world spawn is (respawn anchors and beds aside).
// PlayerList.respawn: a server's player comes back in its respawn
// point's level: the Overworld, where the world spawn and beds are,
// or another one's anchor or forced point, which its block resolves
// once the level has loaded around it.
let server = self.options.dedicated.is_some();
let own = host.hub.guests[i]
.respawn_elsewhere
.as_ref()
.map(RespawnConfig::from_saved);
let elsewhere = own.filter(|_| server);
// In the window's world a guest has no level of its own to wait in:
// its bed is resolved at once when its chunk is there, else it
// comes back on the bed.
let in_frame_bed = own.filter(|c| !server && c.dim == super::Dim::Overworld);
let spawn = in_frame_bed.map_or(spawn, |c| {
[
f64::from(c.pos[0]) + 0.5,
f64::from(c.pos[1]) + 0.6,
f64::from(c.pos[2]) + 0.5,
]
});
let level = elsewhere.map_or(super::Dim::Overworld, |c| c.dim);
let spawn = elsewhere.map_or(spawn, |c| {
[
f64::from(c.pos[0]) + 0.5,
f64::from(c.pos[1]),
f64::from(c.pos[2]) + 0.5,
]
});
let back = self.dim;
let away = self.options.dedicated.is_some()
&& host.hub.guests[i].dimension != super::Dim::Overworld.id();
if away {
let away = server && host.hub.guests[i].dimension != level.id();
if server {
self.server_trips.retain(|t| !t.is(conn));
if let Err(e) = self.enter_level(Some(host), super::Dim::Overworld) {
log::error!("could not open the Overworld: {e}");
return;
}
}
if away && let Err(e) = self.enter_level(Some(host), level) {
log::error!("could not open {}: {e}", level.id());
return;
}
let g = &mut host.hub.guests[i];
g.dead = false;
@@ -1466,6 +1583,28 @@ impl Game<'_> {
collision: Some(self.collision),
};
host.hub.respawn(i, spawn, &ctx);
if let Some(config) = elsewhere {
self.respawn_trip(conn, config);
}
if let Some(c) = in_frame_bed
&& self.dim == super::Dim::Overworld
&& self.world.loaded(c.pos[0], c.pos[2])
{
let found = self
.as_guest(host, conn, |g| g.resolve_server_respawn(c))
.flatten();
let world = self
.level
.world_spawn
.map_or([0.5, 80.0, 0.5], |[x, y, z]| {
[f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]
});
let at = found.map_or(world, |(at, yaw)| {
host.hub.guests[i].yaw = yaw;
[at.x, at.y, at.z]
});
host.hub.teleport(i, Some(at));
}
if away && let Err(e) = self.enter_level(Some(host), back) {
log::error!("could not reopen {}: {e}", back.id());
}
@@ -1475,6 +1614,7 @@ impl Game<'_> {
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
self.lan_merchant_tick(host);
self.lan_stations_tick(host);
self.tick_lan_mount_menus(host);
self.announce_guest_advancements(host);
let conns: Vec<u32> = host
.hub
@@ -1492,6 +1632,9 @@ impl Game<'_> {
continue;
}
let play = host.play.entry(conn).or_default();
// Player.tick's ItemCooldowns.tick, once a tick for each player
// (the shield an axe disabled).
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
let digging = play.digging;
let using = play.using.is_some();
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
@@ -1546,6 +1689,9 @@ impl Game<'_> {
self.guest_dig_feedback(host, conn);
self.guest_pickups(host, gi);
self.guest_orbs(host, gi);
if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead {
self.guest_forget_digging(host, conn);
}
let g = &mut host.hub.guests[gi];
if g.health <= 0.0 && !g.dead {
g.dead = true;
@@ -1676,6 +1822,7 @@ impl Game<'_> {
/// regeneration and the food tick (ServerPlayer.doTick). Their hurt
/// sounds are heard at the guest.
fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) {
self.guest_vehicle_tick(host, conn);
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
@@ -1694,6 +1841,7 @@ impl Game<'_> {
}
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
let at = g.position;
let sneaking = g.sneaking;
let sounds = self.as_guest(host, conn, |game| {
let (rules, motion) = (game.world.health_rules, game.motion);
let health = &motion.health;
@@ -1712,6 +1860,26 @@ impl Game<'_> {
let _ = w.fluid_base_tick();
w.player.ground.on_ground = from_ground;
let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect();
// Entity.move's movementThisTick: each move, from where the
// tick's first one started.
let end = w.player.position;
let start = travelled
.iter()
.fold(end, |p, d| p.subtract(Vec3::new(d[0], d[1], d[2])));
w.player.history.clear();
let mut from = start;
for d in &travelled {
let delta = Vec3::new(d[0], d[1], d[2]);
let to = from.add_vector(delta);
w.player
.history
.add(horizon_world::entity_move::MovementRecord {
from,
to,
original: Some(delta),
});
from = to;
}
for (moved, on_ground) in moves {
let movement = Vec3::new(moved[0], moved[1], moved[2]);
if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 {
@@ -1730,6 +1898,17 @@ impl Game<'_> {
break;
}
}
// A ServerPlayer travels on the server too
// (MoveSimulationType.AUTHORITATIVE_SIDE_AND_SERVER), so every tick
// on a ladder or vine LivingEntity.handleOnClimbable resets its fall
// distance: climbing down doesn't hurt where it lands (#1255).
if w.climbable().unwrap_or(false) {
w.player.fall_distance = 0.0;
}
// Entity.applyEffectsFromBlocks along those moves: magma, cactus,
// lit campfires and grown sweet berry bushes hurt (#1305).
w.player.shift_key_down = sneaking;
let _ = w.server_block_damage(start);
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
@@ -1890,6 +2069,23 @@ impl Game<'_> {
/// `level.destroyBlockProgress(id, pos, -1)` for a guest: its crack on `pos` is gone, for the
/// host and the other guests.
/// A player who dies digs and uses nothing any more: the block it was
/// breaking, or had left to break (`hasDelayedDestroy`), stays, and its
/// crack goes. Respawning gives it a new ServerPlayerGameMode (#1315).
fn guest_forget_digging(&mut self, host: &mut LanHost, conn: u32) {
let Some(play) = host.play.get_mut(&conn) else {
return;
};
let cracked = play.digging.take().filter(|_| play.last_progress >= 0);
play.mining = None;
play.delayed = None;
play.destroy_delay = 0;
play.using = None;
play.last_progress = -1;
if let Some((pos, _)) = cracked {
self.guest_crack_gone(host, conn, pos);
}
}
fn guest_crack_gone(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) {
let Some(id) = host.hub.guest(conn).map(|g| g.entity_id) else {
return;
+18 -1
View File
@@ -36,9 +36,12 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) ->
velocity: [0.0; 3],
data: 0,
meta: Vec::new(),
defaults: Vec::new(),
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
needs_sync: false,
leash: None,
}
}
@@ -89,8 +92,17 @@ fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> {
impl Game<'_> {
/// Who rides what (`Entity.getPassengers`): mobs on mobs, and the
/// host in its boat or minecart.
pub(super) fn lan_riding(&self, host_entity: Option<i32>, riding: &mut Riding) {
pub(super) fn lan_riding(
&self,
host_entity: Option<i32>,
guests: &[(u32, i32)],
riding: &mut Riding,
) {
riding.clear();
// The server's players in their boats and minecarts.
for &(vehicle, guest) in guests {
riding.add(vehicle as i32, guest);
}
for m in self.mobs.iter().filter(|m| !m.removed) {
if let Some(vehicle) = m.extra.mount {
riding.add(vehicle as i32, m.id as i32);
@@ -264,6 +276,7 @@ impl Game<'_> {
self.tridents.iter_mut().for_each(|t| give(&mut t.id));
self.rockets.iter_mut().for_each(|r| give(&mut r.id));
self.crystals.iter_mut().for_each(|c| give(&mut c.id));
self.bolts.iter_mut().for_each(|b| give(&mut b.id));
}
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
@@ -275,6 +288,10 @@ impl Game<'_> {
None => 0,
};
let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z];
// LightningBolt: each client draws and flashes its own.
for b in self.bolts.iter().filter(|b| b.id != 0) {
out.push(state(b.id, "minecraft:lightning_bolt", b.at, 0.0, false));
}
for t in self.tnts.iter().filter(|t| t.id != 0) {
let mut e = state(t.id, "minecraft:tnt", at(t.position), 0.0, t.on_ground);
e.velocity = at(t.velocity);
@@ -0,0 +1,222 @@
//! The horse inventory for a server's players (`ServerPlayer.openHorseInventory`):
//! shift + use on a tamed horse, donkey, mule, camel or llama, or the
//! inventory key while riding one (`ServerboundPlayerCommandPacket`
//! OPEN_INVENTORY), opens `HorseInventoryMenu` over the mount with
//! `ClientboundMountScreenOpenPacket`. Clicks run on the menu engine
//! (`Kind::Mount`) with the mount's saddle, body item and chest copied in and
//! written back, and the slots go to the client after each change, as
//! `broadcastChanges` does.
use super::{Game, lan::LanHost, lan_crafting::input};
use horizon_client::{
items::ItemStack,
menu::{Kind, Menu},
};
use horizon_protocol::packets::play::{self, Clientbound as C};
/// A guest's open mount menu.
pub(super) struct GuestMount {
window: i32,
mob: u32,
columns: usize,
state: i32,
/// The menu's slots and the carried stack the client was last sent.
sent: Option<(Vec<Option<ItemStack>>, Option<ItemStack>)>,
}
impl Game<'_> {
/// `ServerPlayer.openHorseInventory` for mount `mob`: the open menu
/// closes, the client gets the mount screen and the menu's slots.
pub(super) fn lan_open_mount(&mut self, host: &mut LanHost, conn: u32, mob: u32) {
let Some(index) = self.mobs.iter().position(|m| m.id == mob) else {
return;
};
let columns = super::mount_menu::mount_columns(&self.mobs[index]);
self.lan_mount_closed(host, conn, None);
self.lan_station_closed(host, conn, None);
self.lan_crafting_closed(host, conn, None);
self.guest_container_closed(host, conn);
let Some(window) = host.hub.open_mount_window(conn, columns as i32, mob as i32) else {
return;
};
host.play.entry(conn).or_default().mount_window = Some(GuestMount {
window,
mob,
columns,
state: 0,
sent: None,
});
self.lan_send_mount(host, conn);
}
/// `HorseInventoryMenu` over mount `index`, with the player's inventory
/// loaded by the caller.
fn mount_engine_menu(&self, index: usize, columns: usize) -> Menu {
let env = self.menu_env();
let mut menu = Menu::new(Kind::Mount(columns));
menu.mount = Some(self.mobs[index].kind.id.to_string());
let (saddle, body, items) = self.mount_contents(index);
menu.set_slot(&env, 0, saddle);
menu.set_slot(&env, 1, body.flatten());
for (k, item) in items.into_iter().take(columns * 3).enumerate() {
menu.set_slot(&env, 2 + k, item);
}
menu
}
/// The menu's slots (the mount's, then the inventory and the hotbar)
/// and the carried stack, sent when they changed since the last time.
fn lan_send_mount(&mut self, host: &mut LanHost, conn: u32) {
let Some(gm) = host.play.get(&conn).and_then(|p| p.mount_window.as_ref()) else {
return;
};
let (mob, columns) = (gm.mob, gm.columns);
let Some(index) = self.mobs.iter().position(|m| m.id == mob) else {
return;
};
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
return;
};
let (saddle, body, items) = self.mount_contents(index);
let mut slots = vec![saddle, body.flatten()];
slots.extend(items.into_iter().take(columns * 3));
slots.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone()));
let carried = g.carried.clone();
let now = Some((slots, carried));
let Some(gm) = host
.play
.get_mut(&conn)
.and_then(|p| p.mount_window.as_mut())
else {
return;
};
if gm.sent == now {
return;
}
gm.state = (gm.state + 1) & 0x7FFF;
let (window, state) = (gm.window, gm.state);
let (slots, carried) = now.clone().unwrap_or_default();
gm.sent = now;
let content = C::ContainerSetContent(play::ContainerSetContent {
container: window,
state,
items: slots.iter().map(|s| host.hub.stack(s)).collect(),
carried: host.hub.stack(&carried),
});
host.hub.send_to(conn, &content);
}
/// A click on the guest's mount window; false for other windows.
pub(super) fn lan_mount_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
let Some((mob, columns)) = host
.play
.get(&conn)
.and_then(|pl| pl.mount_window.as_ref())
.filter(|m| m.window == p.container)
.map(|m| (m.mob, m.columns))
else {
return false;
};
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& !host.hub.guests[gi].spectator()
&& let Some(index) = self.mobs.iter().position(|m| m.id == mob)
{
let mut menu = self.mount_engine_menu(index, columns);
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
});
self.lan_mount_store(index, columns, &menu);
}
// The client is told what the server has, whatever it predicted.
if let Some(gm) = host
.play
.get_mut(&conn)
.and_then(|pl| pl.mount_window.as_mut())
{
gm.sent = None;
}
self.lan_send_mount(host, conn);
true
}
/// The engine menu's mount slots back on mount `index`.
fn lan_store_slots(menu: &Menu, columns: usize) -> Vec<Option<ItemStack>> {
(0..columns * 3)
.map(|k| menu.slot(2 + k).cloned())
.collect()
}
fn lan_mount_store(&mut self, index: usize, columns: usize, menu: &Menu) {
let (_, body, _) = self.mount_contents(index);
let body = body.map(|_| menu.slot(1).cloned());
let items = Self::lan_store_slots(menu, columns);
self.mount_store(index, menu.slot(0).cloned(), body, items);
}
/// `AbstractContainerMenu.removed` of the guest's mount menu (`window`;
/// None closes it whichever it is): the carried stack goes back to the
/// inventory. False when no such window is open.
pub(super) fn lan_mount_closed(
&mut self,
host: &mut LanHost,
conn: u32,
window: Option<i32>,
) -> bool {
let closed = host
.play
.get_mut(&conn)
.and_then(|p| {
p.mount_window
.take_if(|m| window.is_none_or(|w| m.window == w))
})
.is_some();
if closed
&& let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& let Some(carried) = host.hub.guests[gi].carried.take()
{
self.lan_place_back(host, gi, vec![carried]);
}
closed
}
/// Each tick: a mount menu whose mount died or is out of reach closes
/// (`AbstractMountInventoryMenu.stillValid`: alive, within the entity
/// interaction range plus 4 of the eyes), and the others follow the
/// mount's and the inventory's slots.
pub(super) fn tick_lan_mount_menus(&mut self, host: &mut LanHost) {
let open: Vec<(u32, u32, i32)> = host
.play
.iter()
.filter_map(|(c, p)| p.mount_window.as_ref().map(|m| (*c, m.mob, m.window)))
.collect();
for (conn, mob, window) in open {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
let valid = self.mobs.iter().find(|m| m.id == mob).is_some_and(|m| {
let (w, h) = (f64::from(m.width()) / 2.0, f64::from(m.height()));
let p = [m.position.x, m.position.y, m.position.z];
let lo = [p[0] - w, p[1], p[2] - w];
let hi = [p[0] + w, p[1] + h, p[2] + w];
let d: f64 = (0..3)
.map(|k| (eye[k] - eye[k].clamp(lo[k], hi[k])).powi(2))
.sum();
// Player.ENTITY_INTERACTION_RANGE 3, plus 4.
m.alive() && d < 7.0 * 7.0
});
if valid {
self.lan_send_mount(host, conn);
} else {
self.lan_mount_closed(host, conn, Some(window));
host.hub.send_to(
conn,
&C::ContainerClose(play::ContainerClose { container: window }),
);
}
}
}
}
@@ -0,0 +1,308 @@
//! Boats and minecarts for a server's players: LAN guests, players on a
//! dedicated server, and single player's window on its server thread.
//!
//! A player aims at a vehicle, item frame, armor stand or painting as at a
//! mob (`ServerGamePacketListenerImpl.handleInteract`), and the game's own
//! code for it runs as that player (`AbstractBoat.interact` seats it,
//! `VehicleEntity.hurtServer` breaks the vehicle). A boat is driven by its
//! rider's client (`handleMoveVehicle`, `handlePaddleBoat`); a minecart moves
//! here with the rider's input (`ServerPlayer.getLastClientMoveIntent`).
//! Sneaking gets out (`Player.rideTick`: `wantsToStopRiding`), and the client
//! is teleported where the player lands (`ServerPlayer.dismountTo`).
use super::{Game, Keys, boats::SEAT, lan::LanHost};
use horizon_client::collisions::SceneCollisions;
use horizon_core::geometry::{Aabb, Vec3};
use horizon_protocol::{
packets::play::{self, Clientbound as C},
text::translatable,
};
/// `PlayerInput` flags, as the server player's client last sent them.
pub(super) fn input_keys(flags: u8) -> Keys {
Keys {
forward: flags & 1 != 0,
backward: flags & 2 != 0,
left: flags & 4 != 0,
right: flags & 8 != 0,
jump: flags & 16 != 0,
shift: flags & 32 != 0,
sprint: flags & 64 != 0,
..Keys::default()
}
}
fn corners(b: Aabb) -> ([f64; 3], [f64; 3]) {
let (lo, hi) = (b.min_position(), b.max_position());
([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z])
}
impl Game<'_> {
/// The box of a boat, minecart, armor stand, item frame or painting, and
/// the point an interact packet's location is measured from (the
/// client's `remote_object_hit` uses the same points).
pub(super) fn object_target(&self, id: i32) -> Option<([f64; 3], [f64; 3], [f64; 3])> {
let id = u32::try_from(id).ok()?;
let at = |v: Vec3| [v.x, v.y, v.z];
let centre = |p: [i32; 3]| p.map(|v| f64::from(v) + 0.5);
if let Some(b) = self.boats.iter().find(|b| b.id == id) {
let (lo, hi) = corners(b.bounds());
return Some((lo, hi, at(b.position)));
}
if let Some(c) = self.carts.iter().find(|c| c.id == id) {
let (lo, hi) = corners(c.bounds());
return Some((lo, hi, at(c.position)));
}
if let Some(a) = self.armor_stands.iter().find(|a| a.id == id) {
let (lo, hi) = corners(a.bounds());
return Some((lo, hi, at(a.position)));
}
if let Some(f) = self.item_frames.iter().find(|f| f.id == id) {
let (lo, hi) = f.bounds();
return Some((lo, hi, centre(f.pos)));
}
let p = self.paintings.iter().find(|p| p.id == id)?;
let (lo, hi) = p.bounds();
Some((lo, hi, centre(p.pos)))
}
/// The vehicles the server's players ride: they move with their riders,
/// not in `tick_boats` and `tick_carts`.
pub(super) fn guest_vehicles(&self) -> Vec<u32> {
self.lan.as_ref().map_or_else(Vec::new, |h| {
h.hub.guests.iter().filter_map(|g| g.vehicle).collect()
})
}
/// Whether a server player other than the one acting rides `vehicle`
/// (`Entity.canAddPassenger`: a boat or minecart seats one player here).
pub(super) fn ridden_by_guest(&self, vehicle: u32) -> bool {
self.lan.as_ref().is_some_and(|h| {
h.hub
.guests
.iter()
.any(|g| Some(g.conn) != self.lan_acting && g.vehicle == Some(vehicle))
})
}
/// `Player.rideTick` for a server player, before its moves this tick:
/// it stays in its seat, steers its minecart, or gets out.
pub(super) fn guest_vehicle_tick(&mut self, host: &mut LanHost, conn: u32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let g = &host.hub.guests[gi];
let Some(vehicle) = g.vehicle else {
return;
};
let (keys, dead) = (input_keys(g.input), g.dead || g.health <= 0.0);
let boat = self.boats.iter().position(|b| b.id == vehicle);
let cart = self.carts.iter().any(|c| c.id == vehicle);
let mount = self.mobs.iter().any(|m| m.id == vehicle);
// The vehicle is gone (broken, in another level) or the rider died:
// its client drops it with the entity or the death screen.
if dead || (boat.is_none() && !cart && !mount) {
let g = &mut host.hub.guests[gi];
(g.vehicle, g.vehicle_good) = (None, None);
return;
}
if let Some(i) = boat {
// AbstractBoat.tick on the server for a boat its rider drives:
// only the hurt animation and the damage wear off here.
let b = &mut self.boats[i];
b.hurt_time = (b.hurt_time - 1).max(0);
b.damage = (b.damage - 1.0).max(0.0);
}
// Getting out goes through leave_guest, which tells the client and
// teleports it (ServerPlayer.dismountTo).
let seat = self.as_guest(host, conn, |game| {
if let Some(i) = game.boats.iter().position(|b| Some(b.id) == game.riding) {
if keys.shift {
game.dismount(i);
return None;
}
let p = game.boats[i].position;
return Some([p.x, p.y + SEAT, p.z]);
}
// The minecart moves with the rider's input, and lets it out when
// it sneaks or the cart breaks. An animal takes the rider's input
// for its own tick (`travelRidden`), or lets it off.
if !game.tick_cart_riding(keys) && game.tick_mount_riding(keys) {
game.riding?;
game.position_rider();
}
game.riding?;
let p = game.player.as_ref()?.position;
Some([p.x, p.y, p.z])
});
if let Some(Some(at)) = seat {
let g = &mut host.hub.guests[gi];
g.previous_position = g.position;
g.position = at;
}
}
/// After an interaction: a player that got into a vehicle sits in it,
/// and its last good vehicle position is where the vehicle is.
pub(super) fn guest_boarded(&mut self, host: &mut LanHost, conn: u32, before: Option<u32>) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let Some(vehicle) = host.hub.guests[gi].vehicle else {
return;
};
if before == Some(vehicle) {
return;
}
// The host in the window rides it already.
if self.riding == Some(vehicle) {
host.hub.guests[gi].vehicle = before;
return;
}
let at = self
.boats
.iter()
.find(|b| b.id == vehicle)
.map(|b| b.position)
.or_else(|| {
self.carts
.iter()
.find(|c| c.id == vehicle)
.map(|c| c.position)
});
if let Some(p) = at {
let g = &mut host.hub.guests[gi];
g.vehicle_good = Some([p.x, p.y, p.z]);
g.previous_position = g.position;
g.position = [p.x, p.y + SEAT, p.z];
g.on_ground = false;
return;
}
// An animal: the rider sits where `positionRider` puts it.
let seat = self.as_guest(host, conn, |game| {
game.position_rider();
game.player
.as_ref()
.map(|p| [p.position.x, p.position.y, p.position.z])
});
if let Some(Some(at)) = seat {
let g = &mut host.hub.guests[gi];
g.previous_position = g.position;
g.position = at;
g.on_ground = false;
}
}
/// `ServerGamePacketListenerImpl.handleMoveVehicle`: the boat its rider
/// drives goes where the client says, unless it moved too quickly or
/// wrongly; then it stays, and the client is told where it is.
pub(super) fn guest_move_vehicle(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::MoveVehicleRequest,
) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let [x, y, z] = p.position;
if !(x.is_finite() && y.is_finite() && z.is_finite())
|| !p.yaw.is_finite()
|| !p.pitch.is_finite()
{
host.hub.kick(
conn,
translatable("multiplayer.disconnect.invalid_vehicle_movement", &[]),
);
return;
}
let g = &host.hub.guests[gi];
if g.awaiting_teleport.is_some() || !g.loaded {
return;
}
let owner = host.hub.singleplayer_owner == Some(g.uuid);
let (vehicle, good) = (g.vehicle, g.vehicle_good);
let back = |host: &mut LanHost, position: Vec3, yaw: f32| {
let packet = play::MoveVehicle {
position: [position.x, position.y, position.z],
yaw,
pitch: 0.0,
};
host.hub.send_to(conn, &C::MoveVehicle(packet));
};
// Only a boat is driven by its rider (getControllingPassenger); a
// minecart that is elsewhere on the client is put back.
let Some(i) = vehicle.and_then(|v| self.boats.iter().position(|b| b.id == v)) else {
if let Some(c) = vehicle.and_then(|v| self.carts.iter().find(|c| c.id == v))
&& c.position.distance_squared(Vec3::new(x, y, z)) > 1.0
{
back(host, c.position, c.yaw);
}
return;
};
let b = &self.boats[i];
let old = b.position;
let good = good.map_or(old, |g| Vec3::new(g[0], g[1], g[2]));
let target = Vec3::new(
x.clamp(-3.0E7, 3.0E7),
y.clamp(-2.0E7, 2.0E7),
z.clamp(-3.0E7, 3.0E7),
);
// Moved too quickly: more than 10 blocks past its own motion.
let moved = target.distance_squared(old) - b.velocity.length_squared();
if moved > 100.0 && !owner {
log::warn!("boat {} moved too quickly! {moved}", b.id);
back(host, old, b.yaw);
return;
}
// vehicle.move(PLAYER, target - lastGood) with the boat's collisions:
// where it can't follow the client (a quarter block off, the height
// aside), it moved wrongly.
let bounds = b.bounds();
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
let wanted = target.subtract(good);
let resolved = scene
.resolve(bounds, wanted, 0.0, b.on_ground)
.unwrap_or(wanted);
let reached = old.add_vector(resolved);
let wrongly = (target.x - reached.x).powi(2) + (target.z - reached.z).powi(2) > 0.0625;
let free_before = scene.unobstructed(bounds).unwrap_or(true);
// isEntityCollidingWithAnythingNew: a box that was free is not there.
let moved_box = bounds.move_by(target.subtract(old));
let free_after = scene
.unobstructed(moved_box.deflate(Vec3::new(1.0E-5, 1.0E-5, 1.0E-5)))
.unwrap_or(true);
if free_before && (wrongly || !free_after) {
log::warn!("boat {} moved wrongly", b.id);
back(host, old, b.yaw);
return;
}
let b = &mut self.boats[i];
b.previous = old;
b.velocity = target.subtract(old);
b.position = target;
b.previous_yaw = b.yaw;
b.yaw = p.yaw;
b.on_ground = p.on_ground;
let g = &mut host.hub.guests[gi];
g.vehicle_good = Some([target.x, target.y, target.z]);
g.previous_position = g.position;
g.position = [target.x, target.y + SEAT, target.z];
}
/// `handlePaddleBoat`: the paddles of the boat the player drives.
pub(super) fn guest_paddle_boat(&mut self, host: &LanHost, conn: u32, paddles: [bool; 2]) {
let vehicle = host
.hub
.guests
.iter()
.find(|g| g.conn == conn)
.and_then(|g| g.vehicle);
if let Some(b) = self.boats.iter_mut().find(|b| Some(b.id) == vehicle) {
b.paddling = paddles;
}
}
}
@@ -9,6 +9,10 @@ use horizon_client::{
},
};
/// The host player's connection id in the waypoint managers: its packets
/// go to this client's locator bar rather than to a guest.
const HOST_CONN: u32 = u32::MAX;
/// `waypoint_transmit_range`: hidden by crouching, invisibility or a head worn.
fn transmit_range(crouching: bool, invisible: bool, head: Option<&ItemStack>) -> f64 {
let hiding_head = head.is_some_and(|s| HIDING_HEADS.contains(&&*s.item));
@@ -47,7 +51,7 @@ impl Game<'_> {
self.dim.id(),
waypoints::Player {
uuid: h.uuid,
conn: None,
conn: Some(HOST_CONN),
position: h.position,
spectator: self.spectator(),
transmit_range: transmit_range(
@@ -123,7 +127,12 @@ impl Game<'_> {
}
}
for (conn, packet) in out {
if let Some(g) = host.hub.guest(conn) {
if conn == HOST_CONN {
// The host's own connection: its locator bar.
if let horizon_protocol::packets::play::Clientbound::TrackedWaypoint(w) = &packet {
self.handle_waypoint(w);
}
} else if let Some(g) = host.hub.guest(conn) {
g.send(&packet);
}
}
+21
View File
@@ -232,6 +232,9 @@ impl Game<'_> {
p.world.game_time = self.world.game_time;
p.world.day_time = self.world.day_time;
p.world.weather = self.world.weather;
// The game rules and the difficulty are the server's, not a
// level's: natural regeneration holds in every dimension.
p.world.health_rules = self.world.health_rules;
// The sculk tables' watched blocks are built once per game.
p.world.watched = std::mem::take(&mut self.world.watched);
self.swap_level(&mut p);
@@ -253,6 +256,24 @@ impl Game<'_> {
Ok(())
}
/// Put `dim`'s level in place for a command whose source is there
/// (`execute in`, `execute at` a player in another level), opening it if
/// nobody is in it; returns the level to put back afterwards. Only a
/// server holds other levels.
pub(super) fn enter_command_level(&mut self, dim: Dim) -> Option<Dim> {
if self.options.dedicated.is_none() || dim == self.dim {
return None;
}
let back = self.dim;
match self.enter_level(None, dim) {
Ok(()) => Some(back),
Err(e) => {
log::error!("could not open {}: {e}", dim.id());
None
}
}
}
/// One server tick (`MinecraftServer.tickServer`): each level with
/// players in turn (`tickChildren`), its chunks streamed and loaded and
/// its world ticked. The first pass reads the network and runs the
+37 -75
View File
@@ -5,17 +5,13 @@
//! witches, mooshroom colours, turtles, burnt items), lightning rods, the sky
//! flash, the sounds and the branching additive bolt.
use super::Game;
use horizon_client::{
mesher::Vertex,
mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species},
};
use horizon_core::{
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_client::mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species};
use horizon_core::{position::BlockPos, random::RandomSource};
pub(super) struct Bolt {
at: [f64; 3],
/// The entity id a server's players know it by (0 until it has one).
pub id: u32,
pub at: [f64; 3],
life: i32,
flashes: i32,
seed: i64,
@@ -137,7 +133,9 @@ impl Game<'_> {
let r = &mut self.world.random;
let seed = r.next_long();
let flashes = r.next_int_bound(3).unwrap_or(0) + 1;
self.lightning_seen[0] += 1;
self.bolts.push(Bolt {
id: 0,
at,
life: 2,
flashes,
@@ -146,6 +144,24 @@ impl Game<'_> {
converted: Vec::new(),
});
}
/// `ClientLevel.addEntity` for a server's lightning bolt: on a client it
/// only flashes, sounds and draws (`LightningBolt.tick` off the server).
pub(super) fn spawn_remote_bolt(&mut self, id: u32, at: [f64; 3]) {
self.bolts.retain(|b| b.id != id);
let r = &mut self.world.random;
let seed = r.next_long();
let flashes = r.next_int_bound(3).unwrap_or(0) + 1;
self.lightning_seen[0] += 1;
self.bolts.push(Bolt {
id,
at,
life: 2,
flashes,
seed,
visual_only: true,
converted: Vec::new(),
});
}
/// `spawnFire`: fire at the strike point and `extra` random neighbours.
fn bolt_fire(&mut self, at: [f64; 3], extra: i32) {
if self.ui.difficulty < 2 {
@@ -222,6 +238,9 @@ impl Game<'_> {
}
}
if b.life >= 0 {
if self.flash == 0 {
self.lightning_seen[1] += 1;
}
self.flash = 2;
if !b.visual_only {
self.thunder_hit(b);
@@ -349,71 +368,14 @@ impl Game<'_> {
|| e.stack.item.contains("netherite")
});
}
/// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8
/// segments of 16 blocks, from the bolt's seed.
pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let white = self.gui.atlas.font.white();
let uv = [white.u0, white.v0];
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
for b in &self.bolts {
let o = (glam::DVec3::from_array(b.at) - camera).as_vec3();
let mut random = LegacyRandom::new(b.seed);
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
let (mut x_off, mut z_off) = (0f32, 0f32);
for i in (0..8).rev() {
xs[i] = x_off;
zs[i] = z_off;
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
}
for layer in 0..4 {
let mut random = LegacyRandom::new(b.seed);
for branch in 0..3 {
let trunk = branch == 0;
let start = 7 - branch;
let end = if trunk { 0 } else { start - 3 + 1 };
let mut sx = xs[start] - x_off;
let mut sz = zs[start] - z_off;
for segment in (end..=start).rev() {
let (ex, ez) = (sx, sz);
let spread = if trunk { 11 } else { 31 };
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
let mut top = 0.1 + layer as f32 * 0.2;
let mut bottom = top;
if trunk {
top *= segment as f32 * 0.1 + 1.0;
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
}
for (rx, rz, lx, lz) in [
(false, false, true, false),
(true, false, true, true),
(true, true, false, true),
(false, true, false, false),
] {
let s = |p: bool, r: f32| if p { r } else { -r };
let y0 = segment as f32 * 16.0;
let corners = [
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
];
for c in corners {
out.push(Vertex {
normal: [0; 4],
pos: (o + glam::Vec3::from_array(c)).to_array(),
uv,
layer: 2,
color,
light: 240 | 240 << 8,
});
}
}
}
}
}
}
/// Simulation-order render inputs; seeded geometry lives in the renderer.
pub(super) fn bolt_instances(&self) -> Vec<horizon_client::gfx::lightning::Bolt> {
self.bolts
.iter()
.map(|b| horizon_client::gfx::lightning::Bolt {
at: b.at,
seed: b.seed,
})
.collect()
}
}
+2 -1
View File
@@ -93,7 +93,8 @@ impl Game<'_> {
return false;
}
if tamed && sneaking {
// The horse inventory screen is not available yet.
// AbstractHorse.openCustomInventoryScreen.
self.open_mount_menu(index);
return true;
}
let m = &self.mobs[index];
@@ -0,0 +1,126 @@
//! The locator bar on this client (horizon_client::locator_bar): the
//! waypoints a server tracks for the player (`handleWaypoint`; on a served
//! world the host's own connection in lan/waypoints.rs), the experience
//! bar's priority after a change, and the dots drawn from the last frame's
//! camera.
use super::Game;
use horizon_client::{
hud_layout::GuiDraw,
locator_bar::{ClientWaypoints, View},
};
use horizon_protocol::packets::play::TrackedWaypoint;
/// `Player.getEyeHeight` while standing.
const PLAYER_EYES: f64 = 1.62;
fn uuid(ints: [i32; 4]) -> u128 {
ints.iter()
.fold(0u128, |acc, &i| acc << 32 | u128::from(i as u32))
}
impl Game<'_> {
/// `ClientPacketListener.handleWaypoint`.
pub(super) fn handle_waypoint(&mut self, packet: &TrackedWaypoint) {
self.waypoints.apply(packet);
}
/// A new connection or world starts with no waypoints.
pub(super) fn clear_waypoints(&mut self) {
self.waypoints = ClientWaypoints::default();
}
/// `LocalPlayer.setExperienceValues`: a change of progress shows the
/// experience bar for 100 ticks, except the first one
/// (`experienceDisplayStartTick` starts at `Integer.MIN_VALUE`).
pub(super) fn track_experience_display(&mut self) {
let progress = self.experience.progress;
let (last, seen, _) = &mut self.experience_display;
if progress != *last {
*last = progress;
if *seen {
self.experience_display.2 = self.ticks;
} else {
*seen = true;
}
}
// EnchantmentScreen and AnvilScreen.containerTick keep it up.
if self.station.as_ref().is_some_and(|s| {
matches!(
s.kind,
super::stations::Kind::Enchanting | super::stations::Kind::Anvil
)
}) {
self.experience_display.2 = self.ticks;
}
}
/// `Hud.willPrioritizeExperienceInfo`.
pub(super) fn experience_recent(&self) -> bool {
let (_, _, start) = self.experience_display;
start != 0 && start + 100 > self.ticks
}
/// The local player's UUID, as servers know it.
fn own_uuid(&self) -> u128 {
match &self.remote {
Some(r) => r.profile(),
None => self.level.player_uuid.map_or(0, uuid),
}
}
/// An entity's block position and (interpolated) eyes, by UUID.
fn waypoint_entity(&self, id: u128, alpha: f64) -> Option<([i32; 3], [f64; 3])> {
let at = |p: [f64; 3], q: [f64; 3], eyes: f64| {
let pos: [f64; 3] = std::array::from_fn(|i| q[i] + (p[i] - q[i]) * alpha);
(p.map(|c| c.floor() as i32), [pos[0], pos[1] + eyes, pos[2]])
};
if let Some(r) = &self.remote {
let entity = r.player_entity(id)?;
let m = self.mobs.iter().find(|m| m.id == entity)?;
let v = |v: horizon_core::geometry::Vec3| [v.x, v.y, v.z];
return Some(at(v(m.position), v(m.previous), m.eye_height()));
}
let host = self.lan.as_ref()?;
let g = host.hub.guests.iter().find(|g| g.uuid == id && g.placed)?;
Some(at(g.position, g.previous_position, PLAYER_EYES))
}
/// `LocatorBar.extractRenderState` from the last frame's camera.
pub(super) fn locator_bar_draws(&self, gui_width: i32, gui_height: i32) -> Vec<GuiDraw> {
let (Some((camera_pos, yaw, pitch, fov)), Some(p)) = (self.locator_camera, &self.player)
else {
return Vec::new();
};
let alpha = self.clock.camera_fraction();
// Camera.getViewRotationProjectionMatrix, through view space: the
// depth along the look direction and the height on screen.
let (sy, cy) = (
f64::from(yaw.to_radians()).sin(),
f64::from(yaw.to_radians()).cos(),
);
let (sp, cp) = (
f64::from(pitch.to_radians()).sin(),
f64::from(pitch.to_radians()).cos(),
);
let forward = [-sy * cp, -sp, cy * cp];
let up = [-sy * sp, cp, cy * sp];
let focal = 1.0 / f64::from((fov / 2.0).to_radians()).tan();
let project = |o: [f64; 3]| {
let dot = |a: [f64; 3]| a[0] * o[0] + a[1] * o[1] + a[2] * o[2];
let depth = dot(forward);
let y = dot(up) * focal / depth;
// Points behind the camera land past the far plane (z > 1).
[0.0, y, if depth < 0.0 { 2.0 } else { 0.5 }]
};
let entity = |id: u128| self.waypoint_entity(id, alpha);
let view = View {
gui_width,
gui_height,
camera_uuid: self.own_uuid(),
camera_entity_pos: [p.position.x, p.position.y, p.position.z],
camera_pos,
yaw,
pitch,
fov,
project: &project,
entity: &entity,
styles: &self.waypoint_styles,
tick: self.ticks,
};
self.waypoints.draw(&view)
}
}
+92 -60
View File
@@ -16,7 +16,7 @@ use horizon_client::{
sound_engine::{CartSound, SoundEngine, SoundInstance, Sounds},
};
use horizon_core::{
geometry::{Aabb, Vec3},
geometry::{Aabb, Vec3, trig},
random::RandomSource,
};
use horizon_world::registry::BlockStateId;
@@ -637,6 +637,9 @@ impl Game<'_> {
let r = self.world.random.next_double();
let power = (4.0 + r * 1.5 * speed) as f32;
let at = [c.position.x, c.position.y, c.position.z];
// The cart is the explosion's source: it is gone before the blast
// looks for entities, so it can't hit itself.
self.carts.retain(|x| x.id != c.id);
let _ = self.server_explode(at, power, BlockInteraction::Destroy, false);
}
/// `MinecartHopper.suckInItems`: items above, into the five slots.
@@ -683,8 +686,7 @@ impl Game<'_> {
}
}
}
/// `AbstractMinecart.push(player)` when the player walks into a cart,
/// and carts pushing each other (`pushOtherMinecart`).
/// `AbstractMinecart.push(player)` when the player walks into a cart.
fn push_carts(&mut self) {
let player = self.player.as_ref().map(|p| p.position);
let riding = self.riding;
@@ -719,55 +721,71 @@ impl Game<'_> {
}
}
}
for j in i + 1..self.carts.len() {
let (a, b) = (&self.carts[i], &self.carts[j]);
if !a
.bounds()
.inflate(Vec3::new(0.2, 0.0, 0.2))
.intersects(b.bounds())
{
continue;
}
let (mut xa, mut za) = (b.position.x - a.position.x, b.position.z - a.position.z);
let dd = xa * xa + za * za;
if dd < 1.0e-4 {
continue;
}
let d = dd.sqrt();
let pow = (1.0 / d).min(1.0);
xa = xa / d * pow * f64::from(0.1f32) * 0.5;
za = za / d * pow * f64::from(0.1f32) * 0.5;
let dir =
glam::DVec2::new(b.position.x - a.position.x, b.position.z - a.position.z)
.normalize_or_zero();
let r = a.yaw.to_radians();
let facing =
glam::DVec2::new(f64::from(r.cos()), f64::from(r.sin())).normalize_or_zero();
if dir.dot(facing).abs() < f64::from(0.8f32) {
continue;
}
let (ma, mb) = (a.velocity, b.velocity);
let (fa, fb) = (a.kind == CartKind::Furnace, b.kind == CartKind::Furnace);
let (na, nb) = if fb && !fa {
(
Vec3::new(ma.x * 0.2 + mb.x - xa, ma.y, ma.z * 0.2 + mb.z - za),
Vec3::new(mb.x * 0.95, mb.y, mb.z * 0.95),
)
} else if fa && !fb {
(
Vec3::new(ma.x * 0.95, ma.y, ma.z * 0.95),
Vec3::new(mb.x * 0.2 + ma.x + xa, mb.y, mb.z * 0.2 + ma.z + za),
)
} else {
let (xdd, zdd) = ((mb.x + ma.x) / 2.0, (mb.z + ma.z) / 2.0);
(
Vec3::new(ma.x * 0.2 + xdd - xa, ma.y, ma.z * 0.2 + zdd - za),
Vec3::new(mb.x * 0.2 + xdd + xa, mb.y, mb.z * 0.2 + zdd + za),
)
};
self.carts[i].velocity = na;
self.carts[j].velocity = nb;
}
}
/// `OldMinecartBehavior.pushAndPickupEntities` for carts, at the end of
/// cart `i`'s own tick: each other cart in its box (0.2 wider on each
/// side) gets `push(cart i)`. Running it per cart, after that cart moved
/// and before the next one does, is what splits stacked carts apart.
fn push_from_cart(&mut self, i: usize) {
let reach = f64::from(0.2f32);
let hitbox = self.carts[i].bounds().inflate(Vec3::new(reach, 0.0, reach));
for j in 0..self.carts.len() {
if j == i || !hitbox.intersects(self.carts[j].bounds()) {
continue;
}
// AbstractMinecart.push(entity): `this` is cart j, `entity` cart i.
let (this, other) = (&self.carts[j], &self.carts[i]);
let (mut xa, mut za) = (
other.position.x - this.position.x,
other.position.z - this.position.z,
);
let dd = xa * xa + za * za;
if dd < f64::from(1.0e-4f32) {
continue;
}
let d = dd.sqrt();
xa /= d;
za /= d;
let pow = (1.0 / d).min(1.0);
xa = xa * pow * f64::from(0.1f32) * 0.5;
za = za * pow * f64::from(0.1f32) * 0.5;
// pushOtherMinecart (old movement): only along this cart's facing.
let dir = glam::DVec2::new(
other.position.x - this.position.x,
other.position.z - this.position.z,
)
.normalize_or_zero();
let r = f64::from(this.yaw * 0.017453292f32);
let facing = glam::DVec2::new(f64::from(trig::cos(r)), f64::from(trig::sin(r)))
.normalize_or_zero();
if dir.dot(facing).abs() < f64::from(0.8f32) {
continue;
}
let (mt, mo) = (this.velocity, other.velocity);
let (ft, fo) = (
this.kind == CartKind::Furnace,
other.kind == CartKind::Furnace,
);
let (nt, no) = if fo && !ft {
(
Vec3::new(mt.x * 0.2 + (mo.x - xa), mt.y, mt.z * 0.2 + (mo.z - za)),
Vec3::new(mo.x * 0.95, mo.y, mo.z * 0.95),
)
} else if !fo && ft {
(
Vec3::new(mt.x * 0.95, mt.y, mt.z * 0.95),
Vec3::new(mo.x * 0.2 + (mt.x + xa), mo.y, mo.z * 0.2 + (mt.z + za)),
)
} else {
let (xdd, zdd) = ((mo.x + mt.x) / 2.0, (mo.z + mt.z) / 2.0);
(
Vec3::new(mt.x * 0.2 + (xdd - xa), mt.y, mt.z * 0.2 + (zdd - za)),
Vec3::new(mo.x * 0.2 + (xdd + xa), mo.y, mo.z * 0.2 + (zdd + za)),
)
};
self.carts[j].velocity = nt;
self.carts[i].velocity = no;
}
}
/// Every cart but the ridden one (which ticks with its rider).
@@ -775,13 +793,19 @@ impl Game<'_> {
self.push_carts();
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
let mut i = 0;
while i < self.carts.len() {
// A server player's minecart moves with its rider (lan_vehicles.rs).
let ridden = self.guest_vehicles();
// By id: an exploding cart can destroy or prime others mid-loop.
let ids: Vec<u32> = self.carts.iter().map(|c| c.id).collect();
for id in ids {
let Some(i) = self.carts.iter().position(|c| c.id == id) else {
continue;
};
let p = self.carts[i].position;
if Some(self.carts[i].id) == self.riding
if Some(id) == self.riding
|| ridden.contains(&id)
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
{
i += 1;
continue;
}
let mut c = self.carts[i].clone();
@@ -789,9 +813,12 @@ impl Game<'_> {
if c.kind == CartKind::Hopper {
self.hopper_cart_pickup(&mut c);
}
let Some(i) = self.carts.iter().position(|c| c.id == id) else {
continue;
};
if alive {
self.carts[i] = c;
i += 1;
self.push_from_cart(i);
} else {
self.carts.remove(i);
}
@@ -862,8 +889,13 @@ impl Game<'_> {
p.velocity = Vec3::ZERO;
p.fall_distance = 0.0;
}
let Some(i) = self.carts.iter().position(|x| x.id == c.id) else {
self.riding = None;
return true;
};
if alive {
self.carts[i] = c;
self.push_from_cart(i);
} else {
self.carts.remove(i);
self.riding = None;
@@ -986,7 +1018,7 @@ impl Game<'_> {
let held = self.held().cloned();
match self.carts[i].kind {
CartKind::Rideable => {
if sneaking || self.riding.is_some() {
if sneaking || self.riding.is_some() || self.ridden_by_guest(self.carts[i].id) {
return false;
}
self.riding = Some(self.carts[i].id);
@@ -1118,8 +1150,8 @@ impl Game<'_> {
}
/// `VehicleEntity.hurtServer`: shake, add the damage, break past 40 (at
/// once for creative players); TNT minecarts prime instead when moving
/// or hurt by fire.
fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) {
/// or hurt by fire or an explosion (`damageSourceIgnitesTnt`).
pub(super) fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) {
let c = &mut self.carts[i];
c.hurt_dir = -c.hurt_dir;
c.hurt_time = 10;
@@ -1128,7 +1160,7 @@ impl Game<'_> {
if destroyed {
let mut c = self.carts.remove(i);
let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z;
if c.kind == CartKind::Tnt && (fire || speed >= 0.01) {
if c.kind == CartKind::Tnt && (fire || speed >= f64::from(0.01f32)) {
// MinecartTNT.destroy: prime instead of breaking.
if c.fuse < 0 {
self.prime_cart(&mut c);
+177 -29
View File
@@ -1,12 +1,15 @@
//! The horse inventory (`HorseInventoryMenu`, `HorseInventoryScreen`): the
//! saddle and body armour slots, the 3x5 chest of donkeys and mules and the
//! mount drawn following the cursor. It opens with E while riding a tamed
//! mount or with shift + use on a tamed one.
//! saddle and body armour slots (a llama's carpet), the chest of donkeys,
//! mules and llamas and the mount drawn following the cursor. It opens with
//! E while riding a tamed mount or with shift + use on a tamed one. On a
//! server the screen shows the server's menu (`ClientboundMountScreenOpenPacket`)
//! and its clicks go out as container clicks; a server's players get theirs
//! from game/lan_mount_menu.rs.
use super::{Game, Screen};
use horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
mobs::{Mob, Species, equine},
mobs::{Mob, Species, equine, llama},
};
/// Menu slot ids: the saddle, the body armour and the chest from 710.
@@ -17,11 +20,43 @@ pub(super) const CHEST: usize = 710;
const CHEST_SIZE: usize = 15;
const COLUMNS: usize = 5;
/// `AbstractHorse.getInventoryColumns`: five for a donkey's or mule's chest,
/// a llama's strength for its chest, else none.
pub(super) fn mount_columns(m: &Mob) -> usize {
let species = m.species();
if llama::is_llama(species) {
llama::inventory_columns(m).clamp(0, 5) as usize
} else if m.extra.chested && matches!(species, Species::Donkey | Species::Mule) {
COLUMNS
} else {
0
}
}
/// Whether the mount has a horse inventory (`AbstractHorse`).
pub(super) fn has_mount_menu(species: Species) -> bool {
equine::is_equine(species) || llama::is_llama(species)
}
/// The saddle slot is active (`canUseSlot(SADDLE)` and `CAN_EQUIP_SADDLE`):
/// not on llamas.
fn shows_saddle(species: Species) -> bool {
!llama::is_llama(species)
}
/// The body slot is active: horse armour, or a llama's carpet.
fn shows_body(species: Species) -> bool {
can_wear_horse_armor(species) || llama::is_llama(species)
}
/// The open mount menu: copies of the mount's slots, written back on every change.
#[derive(Default)]
pub(super) struct MountMenu {
open: Option<Open>,
}
impl MountMenu {
/// The mount whose menu is open.
pub(super) fn opened_mob(&self) -> Option<u32> {
self.open.as_ref().map(|o| o.mob)
}
}
struct Open {
mob: u32,
species: Species,
@@ -40,6 +75,9 @@ fn can_wear_horse_armor(species: Species) -> bool {
}
/// Whether `item` fits the body slot of the species (`isEquippableInSlot`).
fn body_armor_fits(species: Species, item: &str) -> bool {
if llama::is_llama(species) {
return item.ends_with("_carpet");
}
can_wear_horse_armor(species) && item.ends_with("_horse_armor")
}
@@ -55,18 +93,16 @@ impl Game<'_> {
pub(super) fn open_mount_menu(&mut self, index: usize) {
let m = &self.mobs[index];
let species = m.species();
if !equine::is_equine(species) {
if !has_mount_menu(species) {
return;
}
let chested = m.extra.chested && matches!(species, Species::Donkey | Species::Mule);
let columns = if chested { COLUMNS } else { 0 };
let mut items = m.extra.items.clone();
items.resize(CHEST_SIZE, None);
let show_armor = can_wear_horse_armor(species);
let show_armor = shows_body(species);
self.mount_menu.open = Some(Open {
mob: m.id,
species,
columns,
columns: mount_columns(m),
saddle: m.saddle_item(),
armor: m
.extra
@@ -75,10 +111,40 @@ impl Game<'_> {
.filter(|_| show_armor)
.map(|i| ItemStack::new(i, 1)),
items,
show_saddle: true,
show_saddle: shows_saddle(species),
show_armor,
});
self.carried = None;
self.show_mount_menu();
}
/// `ClientPacketListener.handleMountScreenOpen`: a server's horse
/// inventory over mount `entity`, its slots to come in the menu's content.
pub(super) fn open_remote_mount_menu(&mut self, entity: u32, columns: usize) -> bool {
let Some(species) = self
.mobs
.iter()
.find(|m| m.id == entity)
.map(Mob::species)
.filter(|s| has_mount_menu(*s))
else {
return false;
};
self.mount_menu.open = Some(Open {
mob: entity,
species,
columns: columns.min(COLUMNS),
saddle: None,
armor: None,
items: vec![None; CHEST_SIZE],
show_saddle: shows_saddle(species),
show_armor: shows_body(species),
});
self.show_mount_menu();
true
}
fn show_mount_menu(&mut self) {
if self.remote.is_none() && self.lan_acting.is_none() {
self.carried = None;
}
self.station = None;
self.container = None;
self.craft_size = 2;
@@ -94,15 +160,39 @@ impl Game<'_> {
return false;
};
let m = &self.mobs[index];
if !equine::is_equine(m.species()) || !m.extra.tame || !m.alive() {
if !has_mount_menu(m.species()) || !m.extra.tame || !m.alive() {
return false;
}
self.open_mount_menu(index);
true
}
/// Riding a mount that has a horse inventory (`HasCustomInventoryScreen`).
pub(super) fn riding_mount_with_menu(&self) -> bool {
self.riding
.and_then(|id| self.mount_mob_index(id))
.is_some_and(|i| has_mount_menu(self.mobs[i].species()))
}
/// A server closed its window: the screen's copy goes.
pub(super) fn mount_menu_reset(&mut self) {
self.mount_menu.open = None;
}
/// The entity type of the open mount menu's mount (`minecraft:horse`).
pub(super) fn mount_menu_entity(&self) -> Option<String> {
let open = self.mount_menu.open.as_ref()?;
let m = self.mobs.iter().find(|m| m.id == open.mob)?;
Some(m.kind.id.to_string())
}
/// The chest columns of the open mount menu (the server's window's).
pub(super) fn mount_menu_columns(&self) -> Option<usize> {
self.mount_menu.open.as_ref().map(|o| o.columns)
}
/// The menu ends when the mount dies or is more than 4 blocks away
/// (`AbstractMountInventoryMenu.stillValid`).
pub(super) fn tick_mount_menu(&mut self) {
// A server's menu ends when the server closes it.
if self.remote.is_some() {
return;
}
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
@@ -126,8 +216,12 @@ impl Game<'_> {
self.mount_sync();
self.mount_menu.open = None;
}
/// Writes the menu slots to the mount, with the equip sounds.
/// Writes the menu slots to the mount, with the equip sounds. A
/// server's menu is the server's to write.
fn mount_sync(&mut self) {
if self.remote.is_some() {
return;
}
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
@@ -135,25 +229,66 @@ impl Game<'_> {
return;
};
let (saddle, armor) = (open.saddle.clone(), open.armor.clone());
let body = open.show_armor.then_some(armor);
let items = open.items.clone();
let m = &mut self.mobs[index];
self.mount_store(index, saddle, body, items);
}
/// The slots of mount `index` as its menu shows them: the saddle, the
/// body item (None when the slot isn't active), the chest.
pub(super) fn mount_contents(
&self,
index: usize,
) -> (
Option<ItemStack>,
Option<Option<ItemStack>>,
Vec<Option<ItemStack>>,
) {
let m = &self.mobs[index];
let species = m.species();
let body =
shows_body(species).then(|| m.extra.head.as_deref().map(|i| ItemStack::new(i, 1)));
let mut items = m.extra.items.clone();
items.resize(mount_columns(m) * 3, None);
(m.saddle_item(), body, items)
}
/// The menu's slots back on mount `index` (`body` None: not its slot),
/// with the equip sound of what was put on (`Equippable.equipSound`).
pub(super) fn mount_store(
&mut self,
index: usize,
saddle: Option<ItemStack>,
body: Option<Option<ItemStack>>,
items: Vec<Option<ItemStack>>,
) {
let m = &self.mobs[index];
let at = m.center();
let sound = if saddle.is_some() && !m.extra.saddled {
Some("minecraft:entity.horse.saddle")
} else if armor.is_some() && m.extra.head.is_none() {
Some("minecraft:entity.horse.armor")
let put_on = if saddle.is_some() && !m.extra.saddled {
saddle.as_ref()
} else {
None
body.as_ref()
.and_then(Option::as_ref)
.filter(|_| m.extra.head.is_none())
};
let sound = put_on.map(|s| {
self.res
.items()
.get(&s.item)
.and_then(|i| i.equip_sound.clone())
.unwrap_or_else(|| "minecraft:item.armor.equip_generic".into())
});
let m = &mut self.mobs[index];
m.set_saddle(saddle);
if open.show_armor {
m.extra.head = armor.map(|a| a.item);
if let Some(body) = body {
m.extra.head = body.map(|a| a.item);
}
let mut items = items;
let keep = m.extra.items.len().max(CHEST_SIZE);
items.resize(keep, None);
m.extra.items = items;
let (x, z) = (at[0].floor() as i32 >> 4, at[2].floor() as i32 >> 4);
self.world.modified.insert((x, z));
if let Some(sound) = sound {
self.audio.play(sound, Some(at), 0.5, 1.0);
self.audio.play(&sound, Some(at), 0.5, 1.0);
}
}
pub(super) fn mount_slots(&self) -> Option<Vec<usize>> {
@@ -214,7 +349,8 @@ impl Game<'_> {
}
/// A click in the mount menu before the generic handling.
pub(super) fn mount_click(&mut self, right: bool) -> bool {
if !self.mount_active() {
// A server's menu: the click goes out like any container click.
if !self.mount_active() || self.remote.is_some() {
return false;
}
let Some(r) = self.renderer.as_ref() else {
@@ -314,12 +450,12 @@ impl Game<'_> {
if open.show_armor {
batch.sprite(atlas, "gui/sprites/container/slot", ox + 7.0, oy + 35.0);
if open.armor.is_none() {
batch.sprite(
atlas,
"gui/sprites/container/slot/horse_armor",
ox + 8.0,
oy + 36.0,
);
let sprite = if llama::is_llama(open.species) {
"gui/sprites/container/slot/llama_armor"
} else {
"gui/sprites/container/slot/horse_armor"
};
batch.sprite(atlas, sprite, ox + 8.0, oy + 36.0);
}
}
let grey = rgba(64, 64, 64, 255);
@@ -448,4 +584,16 @@ mod tests {
"minecraft:iron_chestplate"
));
}
#[test]
fn llamas_wear_carpets_and_no_saddle() {
assert!(body_armor_fits(Species::Llama, "minecraft:red_carpet"));
assert!(!body_armor_fits(
Species::Llama,
"minecraft:iron_horse_armor"
));
assert!(shows_body(Species::TraderLlama));
assert!(!shows_saddle(Species::Llama));
assert!(shows_saddle(Species::Donkey) && !shows_body(Species::Donkey));
}
}
+51 -26
View File
@@ -107,6 +107,10 @@ impl Game<'_> {
let held = self.inventory[self.selected].clone();
let m = &self.mobs[index];
let species = m.species();
// A server player rides it already (`isVehicle`: no seat, no feeding).
if self.ridden_by_guest(m.id) {
return false;
}
if matches!(species, Species::Pig | Species::Strider) {
return self.interact_steerable(index, item);
}
@@ -246,24 +250,9 @@ impl Game<'_> {
self.consume_held();
true
}
/// The rider's input for this tick; returns false when not on a mount.
pub(super) fn tick_mount_riding(&mut self, keys: Keys) -> bool {
let Some(i) = self.mount_index() else {
return false;
};
if keys.shift || !self.mobs[i].alive() {
self.dismount_mount();
return true;
}
let strafe = f32::from(u8::from(keys.left)) - f32::from(u8::from(keys.right));
let forward = f32::from(u8::from(keys.forward)) - f32::from(u8::from(keys.backward));
// LocalPlayer.aiStep: the riding jump charges while space is held.
let held = self.held().map(|s| s.item.clone());
let steer = match self.mobs[i].species() {
Species::Pig => held.as_deref() == Some("minecraft:carrot_on_a_stick"),
Species::Strider => held.as_deref() == Some("minecraft:warped_fungus_on_a_stick"),
_ => false,
};
/// `LocalPlayer.aiStep`'s riding jump: the bar charges while jump is
/// held; on release, the jump's strength (0 when there is none).
pub(super) fn charge_mount_jump(&mut self, i: usize, keys: Keys) -> f32 {
// PlayerRideableJumping: horses, camels and nautili (the dash).
let saddled = self.mobs[i].extra.saddled
&& (equine::is_equine(self.mobs[i].species())
@@ -299,6 +288,27 @@ impl Game<'_> {
}
st.was_jumping = keys.jump;
}
jump
}
/// The rider's input for this tick; returns false when not on a mount.
pub(super) fn tick_mount_riding(&mut self, keys: Keys) -> bool {
let Some(i) = self.mount_index() else {
return false;
};
if keys.shift || !self.mobs[i].alive() {
self.dismount_mount();
return true;
}
let strafe = f32::from(u8::from(keys.left)) - f32::from(u8::from(keys.right));
let forward = f32::from(u8::from(keys.forward)) - f32::from(u8::from(keys.backward));
// LocalPlayer.aiStep: the riding jump charges while space is held.
let held = self.held().map(|s| s.item.clone());
let steer = match self.mobs[i].species() {
Species::Pig => held.as_deref() == Some("minecraft:carrot_on_a_stick"),
Species::Strider => held.as_deref() == Some("minecraft:warped_fungus_on_a_stick"),
_ => false,
};
let jump = self.charge_mount_jump(i, keys);
let m = &mut self.mobs[i];
if jump > 0.0 {
// onPlayerJump: rear while jumping (horses).
@@ -324,7 +334,7 @@ impl Game<'_> {
pitch: self.pitch,
jump: if jump > 0.0 { jump } else { pending },
steer,
sprint: self.keys.contains(&winit::keyboard::KeyCode::ControlLeft),
sprint: keys.sprint || self.keys.contains(&winit::keyboard::KeyCode::ControlLeft),
jumping: keys.jump,
});
true
@@ -453,25 +463,40 @@ impl Game<'_> {
_ => {}
}
}
/// `Hud.extractVehicleHealth` and the jump bar that replaces the
/// experience bar on a saddled jumper. Returns the mount's heart count
/// (`getVehicleMaxHearts`) and whether the jump bar shows.
pub(super) fn draw_mount_hud(&self, batch: &mut HudBatch, w: i32, h: i32) -> (i32, bool) {
/// `Player.jumpableVehicle`: a saddled mount that jumps.
pub(super) fn jumpable_mount(&self) -> bool {
self.mount_index()
.is_some_and(|i| self.mobs[i].extra.saddled)
}
/// `willPrioritizeJumpInfo`: charging a jump or recharging.
pub(super) fn mount_jumping(&self) -> bool {
self.mount.jump_scale > 0.0 || self.mount.jump_ticks < 0
}
/// `Hud.extractVehicleHealth`, and the jump bar when it is the
/// contextual bar (`jump_bar`). Returns the mount's heart count
/// (`getVehicleMaxHearts`).
pub(super) fn draw_mount_hud(
&self,
batch: &mut HudBatch,
w: i32,
h: i32,
jump_bar: bool,
) -> i32 {
let Some(i) = self.mount_index() else {
return (0, false);
return 0;
};
let m = &self.mobs[i];
let atlas = &self.gui.atlas;
let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health);
let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health);
horizon_client::hud_layout::paint(batch, atlas, &draws);
if m.extra.saddled {
if jump_bar {
// JumpableVehicleBar: the cooldown shows while the jump recharges.
let cooldown = i32::from(self.mount.jump_ticks < 0);
let draws =
horizon_client::hud_overlays::jump_bar(w, h, cooldown, self.mount.jump_scale);
horizon_client::hud_layout::paint(batch, atlas, &draws);
}
(hearts, m.extra.saddled)
hearts
}
}
+6 -2
View File
@@ -12,7 +12,7 @@ impl Game<'_> {
pub(super) fn tick_music(&mut self) {
let (music, volume) = self.situational_music();
// LevelLoadingScreen: no new track before the player is in the world.
let loading = self.title.is_none() && self.player.is_none();
let loading = self.title.is_none() && self.player.is_none() && self.win.is_none();
self.music
.tick(music.as_ref(), volume, loading, &mut self.audio);
}
@@ -59,7 +59,11 @@ impl Game<'_> {
None => (empty, 1.0),
};
let situation = Situation {
screen_music: None,
// WinScreen.getBackgroundMusic.
screen_music: self
.win
.is_some()
.then(horizon_client::music::Music::credits),
in_world: eye.is_some(),
in_end: self.dim == super::Dim::End,
boss_music: self.boss_music(),
@@ -72,6 +72,8 @@ pub(super) struct GameLevel<'g, 'a> {
pub(super) w: MobWorld<'g>,
/// Every player in the level ([`Game::level_players`]).
pub(super) players: Vec<LevelPlayer>,
/// Where the non-spectators among them are (`getNearestPlayer`).
pub(super) nearest: Vec<[f64; 3]>,
/// Boxes of the mobs this pass created, not yet in the game's list.
pub(super) pending: std::cell::RefCell<Vec<Aabb>>,
/// The types and boxes of what a spawner created this tick.
@@ -255,14 +257,8 @@ impl NaturalLevel for GameLevel<'_, '_> {
fn structure_spawns(&self) -> &StructureSpawns {
StructureSpawns::shared(&self.game.options.resources)
}
fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option<f64> {
// The nearest player's distance (`nearest_player`), without finding
// which player it is: every spawn attempt asks.
self.players
.iter()
.filter(|p| !p.spectator)
.map(|p| p.distance_sqr(x, y, z))
.reduce(f64::min)
fn nearest_player_positions(&self) -> &[[f64; 3]] {
&self.nearest
}
fn respawn(&self) -> Option<[i32; 3]> {
// The world spawn point lives in the overworld.
@@ -363,10 +359,17 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> {
}
impl<'a> Game<'a> {
pub(super) fn natural_level(&self) -> GameLevel<'_, 'a> {
let players = self.level_players();
let nearest = players
.iter()
.filter(|p| !p.spectator)
.map(|p| [p.position.x, p.position.y, p.position.z])
.collect();
GameLevel {
game: self,
w: self.mob_world_base(&[]),
players: self.level_players(),
players,
nearest,
pending: Default::default(),
pending_ids: Default::default(),
boxes: Default::default(),
+11
View File
@@ -200,6 +200,13 @@ impl Game<'_> {
self.settings.save(&Self::options_path());
self.apply_settings();
self.sync_mods();
self.sync_agent_control();
self.ui.options.agent_status = self.agent_status_lines();
}
Event::CopyAgentDetails => {
use horizon_client::clipboard::Clipboard;
let text = self.agent_details();
self.clipboard.set(&text);
}
Event::Close if self.ui.options.resource_error.is_some() => {}
Event::Close => {
@@ -235,6 +242,10 @@ impl Game<'_> {
let _ = std::fs::create_dir_all(&dir);
super::packs::open_folder(&dir);
}
Event::Credits => self.open_win_screen(false, super::win::Finish::Options),
Event::ReloadShaderPack => {
self.load_shader_pack();
}
}
}
Ok(())
+2
View File
@@ -171,6 +171,8 @@ impl Game<'_> {
}
};
// Everything loaded: switch over.
self.waypoint_styles = horizon_client::locator_bar::WaypointStyles::load(root);
self.armor_stand_assets.reload_trims(root);
self.random_tick_sections.clear();
self.portals.sections.clear();
self.options.resources = root.to_path_buf();
+7 -39
View File
@@ -113,7 +113,7 @@ impl Game<'_> {
}
/// Where focus can land: buttons drawn last frame, every registered
/// target (sliders, fields, rows, Horizon-style widgets), and the slots
/// target (sliders, fields, rows, keyboard keys), and the slots
/// and tabs of inventories (GUI pixels), on screen.
fn pad_targets(&self) -> Vec<Target> {
let mut targets = self.pad_all_targets();
@@ -137,7 +137,7 @@ impl Game<'_> {
})
.collect();
for t in widgets::last_targets() {
// A Horizon button is both a labelled button and a target.
// A button can be both a labelled button and a target.
if let Some(same) = targets.iter_mut().find(|o| o.rect == t.rect) {
same.kind = t.kind;
} else {
@@ -1026,45 +1026,13 @@ impl Game<'_> {
}
}
/// The focus highlight. Classic screens look as vanilla's keyboard focus
/// does: buttons, sliders and slots already draw their highlighted
/// sprite under the (hidden) pointer, and list rows and fields get
/// vanilla's white one-pixel outline (`AbstractSelectionList`'s focused
/// selection, `EditBox`'s highlighted border). Horizon-style screens get
/// the design system's focus colour: a two-dp accent ring.
/// The focus highlight, as vanilla's keyboard focus looks: buttons,
/// sliders and slots already draw their highlighted sprite under the
/// (hidden) pointer, and list rows and fields get vanilla's white
/// one-pixel outline (`AbstractSelectionList`'s focused selection,
/// `EditBox`'s highlighted border).
fn draw_pad_focus(&self, batch: &mut HudBatch, focus: Target) {
let [x, y, w, h] = focus.rect;
// The options' sub-pages keep the classic layout under either style.
let horizon = horizon_client::ui_theme::horizon()
&& if self.screen == Screen::Options {
self.ui.options.page() == Page::Main
} else {
self.title.is_some() || self.screen == Screen::Paused
};
if horizon {
use horizon_client::ui_theme::{self as theme, Ui, color};
let mut ui = Ui::new(&self.gui.atlas, batch, self.cursor);
let k = ui.batch.scale / ui.density;
let (x, y, w, h) = (x * k, y * k, w * k, h * k);
let radius = match focus.kind {
Kind::Button | Kind::Tab(_) | Kind::Slider { .. } => (h + 6.0) / 2.0,
Kind::Field => theme::RADIUS + 3.0,
_ => theme::RADIUS_PLATE + 3.0,
};
for inset in [0.0, 1.0] {
let o = 3.0 - inset;
ui.border(
x - o,
y - o,
w + 2.0 * o,
h + 2.0 * o,
radius - inset,
color::ACCENT,
);
}
ui.finish();
return;
}
if matches!(focus.kind, Kind::Row | Kind::Field) {
let atlas = &self.gui.atlas;
let white = rgba(255, 255, 255, 255);
+7 -3
View File
@@ -297,10 +297,14 @@ impl Game<'_> {
}
}
/// The local player's effects (`tick_mob_effects`), then the potions
/// in flight, which a server without a local player still has.
pub(super) fn tick_effects(&mut self) {
/// in flight, which a server without a local player still has. A frozen
/// tick (`/tick freeze`) leaves the potions where they are
/// (`TickRateManager.isEntityFrozen`); players' effects still run.
pub(super) fn tick_effects(&mut self, running: bool) {
self.tick_mob_effects();
self.tick_thrown_potions();
if running {
self.tick_thrown_potions();
}
}
/// `LivingEntity.tickEffects` (server side) for `self.player`, the local
/// player or a guest acting (`as_guest`), then its attribute modifiers
+505 -95
View File
@@ -7,7 +7,7 @@
//! client predicts its own movement; the server stays authoritative for
//! everything else.
use super::{Dim, Game, Mining, Screen};
use horizon_client::first_person::Hand;
use horizon_client::first_person::{Hand, SwingAnimation};
use horizon_client::{
Result,
chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy},
@@ -40,7 +40,11 @@ use horizon_protocol::{
registry::{Builtin, DimensionType, Dynamic, ceil_log2},
text::{Language, format_java, plain},
};
use horizon_world::{nbt::Tag, registry::BlockStateId};
use horizon_world::{
nbt::Tag,
registry::BlockStateId,
stepped_interpolation::{Path, PosRot, Start, SteppedInterpolation},
};
use std::{
collections::{HashMap, VecDeque},
sync::Arc,
@@ -85,6 +89,15 @@ struct Lerp {
steps: u32,
}
/// `SteppedInterpolationHandler.doInterpolate`'s `setPos` and `setRot` on a
/// mob: its yaw kept continuous (the same turn as vanilla's, without the
/// wrap that would spin it in the frame between ticks), its pitch clamped.
fn place_interpolated(m: &mut Mob, at: PosRot) {
m.position = Vec3::new(at.position[0], at.position[1], at.position[2]);
m.yaw += wrap_degrees(at.yaw - m.yaw);
m.head_pitch = (at.pitch % 360.0).clamp(-90.0, 90.0);
}
pub(super) struct Remote {
pub session: Session,
pub brand: String,
@@ -93,7 +106,7 @@ pub(super) struct Remote {
pub(super) registries: Arc<Dynamic>,
joined: bool,
status: String,
entity_id: i32,
pub(super) entity_id: i32,
dimension: DimensionType,
biome_map: Vec<u16>,
biome_bits: u8,
@@ -123,6 +136,8 @@ pub(super) struct Remote {
use_target: Option<[i32; 3]>,
entities: HashMap<i32, Tracked>,
lerps: HashMap<i32, Lerp>,
/// Living entities' `SteppedInterpolationHandler`s.
stepped: HashMap<i32, SteppedInterpolation>,
/// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it.
head_lerps: HashMap<i32, (f32, u32)>,
/// Item entities waiting for their item data.
@@ -183,6 +198,9 @@ const CHUNK_PACKETS_PER_FRAME: Duration = Duration::from_millis(1);
/// whatever their cost: the packets after a slow machine's chunks never
/// wait more than a tick.
const BACKLOG_LIMIT: Duration = Duration::from_millis(50);
/// The open menu name of a server's horse inventory, then its chest's
/// columns (the packet names no `MenuType`).
const MOUNT_MENU: &str = "horizon:mount";
fn face_direction(face: [i32; 3]) -> u8 {
match face {
@@ -332,6 +350,11 @@ impl Game<'_> {
progress: 0.0,
total: 0,
};
// The connected client never opens a server world (single player also
// joins here), so load the registries its argument parsers and local
// suggestions need before receiving the server's command tree.
self.ui.registries = Default::default();
self.build_registries();
self.ui.registries.permission = 0;
self.ui.chat.clear();
self.screen = Screen::Playing;
@@ -343,6 +366,7 @@ impl Game<'_> {
r.clear_sections();
}
self.apply_settings();
self.clear_waypoints();
self.remote = Some(Remote {
session,
brand: "unknown".into(),
@@ -371,6 +395,7 @@ impl Game<'_> {
use_target: None,
entities: HashMap::new(),
lerps: HashMap::new(),
stepped: HashMap::new(),
head_lerps: HashMap::new(),
pending_items: HashMap::new(),
health: (20.0, 20, 5.0),
@@ -421,6 +446,7 @@ impl Game<'_> {
// Leaving on purpose: nothing for auto-reconnect to retry.
self.extras_left();
}
self.clear_waypoints();
if let Some(mut r) = self.remote.take() {
r.session.disconnect();
}
@@ -921,6 +947,7 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.entities.clear();
r.lerps.clear();
r.stepped.clear();
r.head_lerps.clear();
r.pending_items.clear();
// A new ClientLevel: a new chunk storage, centred on 0, 0.
@@ -1307,11 +1334,15 @@ impl Game<'_> {
}
if let Some(t) = mob_type {
let mut mob = Mob::new(id as u32, t, at, head);
super::remote_mob_data::client_defaults(&mut mob);
(mob.yaw, mob.previous_yaw) = (yaw, yaw);
(mob.head_pitch, mob.previous_head_pitch) = (pitch, pitch);
mob.persistent = true;
self.mobs.retain(|m| m.id != id as u32);
self.mobs.push(mob);
if let Some(r) = self.remote.as_mut() {
r.stepped.remove(&id);
}
}
if let Some(r) = self.remote.as_mut() {
if kind == "minecraft:item" {
@@ -1326,23 +1357,77 @@ impl Game<'_> {
);
}
}
/// A move packet for entity `id`: to the end of `path` (None: a
/// rotation alone), turned to `rotation` if it has one. `far_snaps`:
/// an `EntityPositionSync`, which puts an entity more than 64 blocks
/// away there at once.
fn move_entity(
&mut self,
id: i32,
position: [f64; 3],
path: Option<Path>,
rotation: Option<(f32, f32)>,
on_ground: bool,
far_snaps: bool,
) {
let mob = self.mobs.iter_mut().find(|m| m.id == id as u32);
let tracked = self
.remote
.as_ref()
.and_then(|r| r.entities.get(&id))
.map(|t| t.position);
let position = path
.as_ref()
.map(Path::end)
.or(tracked)
.or_else(|| {
mob.as_ref()
.map(|m| [m.position.x, m.position.y, m.position.z])
})
.unwrap_or([0.0; 3]);
if let Some(r) = self.remote.as_mut() {
if let Some(t) = r.entities.get_mut(&id) {
t.position = position;
}
if let Some(m) = mob {
// A living entity: LivingEntity.createInterpolationHandler's
// SteppedInterpolationHandler, over its type's update interval.
let entity = PosRot {
position: [m.position.x, m.position.y, m.position.z],
yaw: m.yaw,
pitch: m.head_pitch,
};
let far = far_snaps && {
let d = [0, 1, 2].map(|i| position[i] - entity.position[i]);
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 4096.0
};
let handler = r.stepped.entry(id).or_insert_with(|| {
let interval = horizon_client::lan::tracking::settings(&m.kind.id).1;
SteppedInterpolation::new(interval as i32)
});
let snap = if far {
handler.cancel();
let (yaw, pitch) = rotation.unwrap_or((m.yaw, m.head_pitch));
Some(PosRot {
position,
yaw,
pitch,
})
} else {
match handler.interpolate_to(entity, path, rotation) {
Start::Snap(at) => Some(at),
Start::Interpolating | Start::Unchanged => None,
}
};
if let Some(at) = snap {
place_interpolated(m, at);
m.previous = m.position;
}
m.on_ground = on_ground;
return;
}
// AbstractInterpolationHandler.interpolateTo: without a rotation,
// the one it was heading for (or has).
let rotation = rotation
.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation))
.or_else(|| mob.as_ref().map(|m| (m.yaw, m.head_pitch)));
// the one it was heading for.
let rotation = rotation.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation));
r.lerps.insert(
id,
Lerp {
@@ -1355,13 +1440,14 @@ impl Game<'_> {
*p = position;
}
}
if let Some(m) = mob {
m.on_ground = on_ground;
}
self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground);
self.turn_remote_projectile(id, rotation);
}
fn remove_entity(&mut self, id: i32) {
// The vehicle the player rode is gone (Entity.removeVehicle).
if self.riding == Some(id as u32) {
self.riding = None;
}
self.mobs.retain(|m| m.id != id as u32);
self.orbs.retain(|o| o.id != id as u32);
self.dropped.retain(|d| d.id != id as u32);
@@ -1370,6 +1456,7 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.entities.remove(&id);
r.lerps.remove(&id);
r.stepped.remove(&id);
r.head_lerps.remove(&id);
r.pending_items.remove(&id);
}
@@ -1431,6 +1518,19 @@ impl Game<'_> {
// CrafterMenu: the grid, the inventory, then the result (the
// client's own).
"minecraft:crafter_3x3" => slots(9),
// HorseInventoryMenu: the saddle, the body armour, the chest,
// then the inventory.
m if m.starts_with(MOUNT_MENU) => {
let n = m[MOUNT_MENU.len()..].parse::<usize>().ok()? * 3;
match s {
0 => Some(super::mount_menu::SADDLE),
1 => Some(super::mount_menu::ARMOR),
_ if s < 2 + n => Some(super::mount_menu::CHEST + s - 2),
_ if s < 2 + n + 27 => Some(9 + s - 2 - n),
_ if s < 2 + n + 36 => Some(s - 2 - n - 27),
_ => None,
}
}
// A workstation: its inputs, its result, then the inventory.
m => {
let kind = Self::remote_station_kind(m)?;
@@ -1716,17 +1816,36 @@ impl Game<'_> {
.and_then(|r| r.entities.get(&m.id))
.map(|t| t.position);
let Some(base) = base else { return Ok(()) };
let position = m.delta.as_ref().map_or(base, |d| d.end(base));
// VecDeltaCodec.decode: each step's position from the last.
let path = m.delta.as_ref().map(|d| match d {
play::VecDelta::Linear(_) => Path::Linear(d.end(base)),
play::VecDelta::Stepped(steps) => {
let mut at = base;
Path::Stepped(
steps
.iter()
.map(|(delta, ticks)| {
at = play::VecDelta::apply(at, *delta);
(at, *ticks)
})
.collect(),
)
}
});
let rotation = m.rotation.map(|(y, x)| {
(
horizon_protocol::buf::unpack_degrees(y),
horizon_protocol::buf::unpack_degrees(x),
)
});
self.move_entity(m.id, position, rotation, m.on_ground);
self.move_entity(m.id, path, rotation, m.on_ground, false);
}
C::EntityPositionSync(p) => {
self.move_entity(p.id, p.path.end(), Some((p.yaw, p.pitch)), p.on_ground)
let path = match p.path {
play::PositionPath::Linear(at) => Path::Linear(at),
play::PositionPath::Stepped(steps) => Path::Stepped(steps),
};
self.move_entity(p.id, Some(path), Some((p.yaw, p.pitch)), p.on_ground, true)
}
C::TeleportEntity(p) => {
let base = self
@@ -1746,8 +1865,29 @@ impl Game<'_> {
rel(play::relative::Y, 1),
rel(play::relative::Z, 2),
];
self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground);
self.move_entity(
p.id,
Some(Path::Linear(position)),
Some((p.yaw, p.pitch)),
p.on_ground,
false,
);
}
C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers),
// ClientPacketListener.handleEntityLinkPacket: who holds a mob's
// lead (this player, another player or a mob), for the rope.
C::SetEntityLink(p) => {
let me = self.remote.as_ref().map(|r| r.entity_id);
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.source as u32) {
use horizon_client::mobs::leash::Holder;
m.extra.leash = match p.dest {
0 => None,
d if Some(d) == me => Some(Holder::Player),
d => Some(Holder::Mob(d as u32)),
};
}
}
C::MoveVehicle(p) => self.remote_move_vehicle(p.position, p.yaw),
// ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3).
C::RotateHead(p) => {
if let Some(r) = self.remote.as_mut() {
@@ -1783,13 +1923,12 @@ impl Game<'_> {
&& m.species() == horizon_client::mobs::Species::Rabbit
{
for (index, _, value) in &p.values {
match (index, value) {
(15, Value::Byte(flags)) => m.no_ai = flags & 1 != 0,
(16, Value::Bool(baby)) => m.extra.age = if *baby { -1 } else { 0 },
_ => {}
if let (15, Value::Byte(flags)) = (index, value) {
m.no_ai = flags & 1 != 0;
}
}
}
self.remote_mob_data(p.id, &p.values);
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Creeper
{
@@ -1838,11 +1977,27 @@ impl Game<'_> {
// player lies down in the bed, or gets up.
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) {
for (index, _, value) in &p.values {
if let (14, Value::OptPos(bed)) = (index, value) {
if bed.is_some() && self.sleeping.is_none() {
self.sleep_timer = 0;
match (index, value) {
(14, Value::OptPos(bed)) => {
if bed.is_some() && self.sleeping.is_none() {
self.sleep_timer = 0;
}
self.sleeping = *bed;
}
self.sleeping = *bed;
// Entity.DATA_AIR_SUPPLY_ID and
// Player.DATA_PLAYER_ABSORPTION_ID: the bubbles
// and golden hearts the server's player has.
(1, Value::Int(air)) => {
if let Some(pl) = self.player.as_mut() {
pl.air = *air;
}
}
(17, Value::Float(amount)) => {
if let Some(pl) = self.player.as_mut() {
let _ = pl.internal_set_absorption(*amount);
}
}
_ => {}
}
}
}
@@ -2034,6 +2189,7 @@ impl Game<'_> {
self.capture(false);
}
}
C::TrackedWaypoint(p) => self.handle_waypoint(&p),
C::SetExperience(p) => {
self.experience = Experience {
level: p.level,
@@ -2087,6 +2243,10 @@ impl Game<'_> {
);
}
}
// WIN_GAME: the poem and credits, then PERFORM_RESPAWN.
4 if self.screen != Screen::Win => {
self.open_win_screen(true, super::win::Finish::RemoteRespawn);
}
1 => {
self.world.weather.raining = true;
self.world.weather.rain_level = (0.0, 0.0);
@@ -2193,6 +2353,7 @@ impl Game<'_> {
}
}
C::OpenScreen(p) => self.remote_open_screen(p),
C::MountScreenOpen(p) => self.remote_open_mount(p),
C::RecipeBookAdd(p) => self.remote_recipe_book_add(p),
C::RecipeBookRemove(p) => self.remote_recipe_book_remove(p),
C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p),
@@ -2856,6 +3017,7 @@ impl Game<'_> {
fn tick_remote_level(&mut self) -> Result<()> {
self.ticks += 1;
self.track_experience_display();
// Options.broadcastOptions: a changed render distance is sent again.
let view = client_view_distance(self.settings.render_distance);
if let Some(r) = self.remote.as_mut()
@@ -2927,9 +3089,9 @@ impl Game<'_> {
self.capture_loaded_world();
}
let stick = self.pad_move();
let Some(player) = self.player.as_mut() else {
if self.player.is_none() {
return Ok(());
};
}
let playing = self.screen == Screen::Playing;
let held = |k| playing && self.keys.contains(&k);
let keys = Keys {
@@ -2950,7 +3112,14 @@ impl Game<'_> {
| u8::from(keys.jump) << 4
| u8::from(keys.shift) << 5
| u8::from(keys.sprint) << 6;
self.previous_position = player.position;
// A passenger moves with its vehicle (Entity.rideTick), not by itself.
let riding = self.screen != Screen::Dead && self.remote_ride(keys);
let Some(player) = self.player.as_mut() else {
return Ok(());
};
if !riding {
self.previous_position = player.position;
}
let before = (
player.ground.on_ground,
[player.velocity.x, player.velocity.y, player.velocity.z],
@@ -2958,6 +3127,13 @@ impl Game<'_> {
);
let was_flying = player.flying;
player.yaw = self.yaw;
// As the window's own tick has them: the helmet's Respiration
// (decreaseAirSupply) and the dimension's FAST_LAVA, the Nether's
// stronger lava current.
player.respiration = self.armor[0]
.as_ref()
.map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32);
player.fluids.fast_lava = self.dim == Dim::Nether;
let dead = self.screen == Screen::Dead;
// LivingEntity.isImmobile: a sleeper lies still in the bed.
if let Some(head) = self.sleeping {
@@ -2967,7 +3143,7 @@ impl Game<'_> {
f64::from(head[2]) + 0.5,
);
player.velocity = Vec3::ZERO;
} else if !dead {
} else if !dead && !riding {
player.velocity = player.velocity.add_vector(pushed);
MotionWorld {
entities: &ghast_collisions,
@@ -3110,6 +3286,7 @@ impl Game<'_> {
return;
};
let mut lerps = std::mem::take(&mut r.lerps);
let stepped = &mut r.stepped;
let head_lerps = &mut r.head_lerps;
let players = &r.level_players;
let mut using = Vec::new();
@@ -3140,22 +3317,12 @@ impl Game<'_> {
// LivingEntity.updateSwingTime.
m.anim.attack_anim_o = m.anim.attack_anim;
horizon_client::mobs::ai::tick_swing(m);
// Entity.commonTick: LinearInterpolationHandler.interpolate.
if let Some(l) = lerps.get_mut(&(m.id as i32))
&& l.steps > 0
// Entity.tick: the SteppedInterpolationHandler's step.
if let Some(at) = stepped
.get_mut(&(m.id as i32))
.and_then(|h| h.interpolate())
{
let n = f64::from(l.steps);
m.position = Vec3::new(
m.position.x + (l.target[0] - m.position.x) / n,
m.position.y + (l.target[1] - m.position.y) / n,
m.position.z + (l.target[2] - m.position.z) / n,
);
if let Some((yaw, pitch)) = l.rotation {
let alpha = 1.0 / l.steps as f32;
m.yaw += wrap_degrees(yaw - m.yaw) * alpha;
m.head_pitch += (pitch - m.head_pitch) * alpha;
}
l.steps -= 1;
place_interpolated(m, at);
}
// LivingEntity.aiStep: the head's own interpolation.
if let Some((yaw, steps)) = head_lerps.get_mut(&(m.id as i32))
@@ -3253,6 +3420,9 @@ impl Game<'_> {
};
self.tick_remote_objects(&mut step);
self.tick_remote_projectiles(&mut step);
// LightningBolt.tick on a client, and the sky flash fading.
self.flash = self.flash.saturating_sub(1);
self.tick_bolts();
}
lerps.retain(|_, l| l.steps > 0);
if let Some(r) = self.remote.as_mut() {
@@ -3314,6 +3484,8 @@ impl Game<'_> {
p.sprinting,
);
let (yaw, pitch, selected) = (self.yaw, self.pitch, self.selected);
let riding = self.riding.is_some();
let vehicle = self.remote_vehicle_packets();
let Some(r) = self.remote.as_mut() else {
return;
};
@@ -3336,9 +3508,18 @@ impl Game<'_> {
data: 0,
}));
}
if let Some(packet) = r
.position_sender
.update(pos, (yaw, pitch), on_ground, collision)
if riding {
// LocalPlayer.tick: a passenger sends its look, then the vehicle
// it controls.
out.push(S::MovePlayerRot(play::MovePlayerRot {
yaw,
pitch,
flags: u8::from(on_ground) | u8::from(collision) << 1,
}));
out.extend(vehicle);
} else if let Some(packet) =
r.position_sender
.update(pos, (yaw, pitch), on_ground, collision)
{
out.push(packet);
}
@@ -3416,22 +3597,13 @@ impl Game<'_> {
return;
}
let facts = self.res.facts().get(state).clone();
let held = self.held().cloned();
let mut speed = self.res.items().mining_speed(held.as_ref(), &facts.name);
if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) {
speed /= 5.0;
}
let harvest = !facts.requires_tool
|| self
.res
.items()
.correct_for_drops(held.as_ref(), &facts.name);
let progress = if facts.hardness < 0.0 {
0.0
} else if facts.hardness == 0.0 {
// The server's own getDestroyProgress: under water, off the ground,
// with haste, fatigue and efficiency, so the client stops digging
// when the server is done too (#1254).
let progress = if facts.hardness == 0.0 {
1.0
} else {
speed / facts.hardness / if harvest { 30.0 } else { 100.0 }
self.destroy_progress(hit.pos)
};
let same = self
.remote
@@ -3458,10 +3630,8 @@ impl Game<'_> {
sequence: seq,
}));
if progress >= 1.0 {
// startDestroyBlock: instant survival breaks have no destroy delay.
self.predict_break(hit.pos, state, seq);
if let Some(r) = self.remote.as_mut() {
r.destroy_delay = 5;
}
return;
}
if let Some(r) = self.remote.as_mut() {
@@ -3571,6 +3741,21 @@ impl Game<'_> {
fn remote_use_entity(&mut self) -> bool {
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
// A boat, minecart, item frame, armor stand or painting nearer than
// any mob: the server uses it (AbstractBoat.interact boards it).
if let Some(hit) = self.remote_object_hit()
&& self.mob_hit().is_none_or(|(_, d)| hit.distance < d)
&& self.before_block(hit.distance)
{
self.send(S::Interact(play::Interact {
id: hit.id,
hand: 0,
location: hit.location,
secondary: sneaking,
}));
self.swing_arm();
return true;
}
if let Some((i, distance)) = self.mob_hit()
&& self.before_block(distance)
{
@@ -3638,7 +3823,15 @@ impl Game<'_> {
self.predict_use(&changes, seq);
}
if held_block {
self.with_hand(hand, Game::swing_arm);
if reacts
|| held
.as_ref()
.is_some_and(|stack| self.remote_can_place(&hit, stack))
{
self.with_hand(hand, Game::swing_arm);
}
// BlockItem.place returns FAIL when placement is rejected:
// stop this click without trying the item or the other hand.
return true;
}
return reacts;
@@ -3696,7 +3889,11 @@ impl Game<'_> {
/// container, and the blocks it changed. Vanilla's client runs it on its
/// own level first; this runs it on a copy, and `predict_use` keeps the
/// changes it predicts.
fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) {
fn remote_block_reacts(
&mut self,
hit: &super::Hit,
held: Option<&ItemStack>,
) -> (bool, DryUse) {
// Player.isSecondaryUseActive with something in either hand.
let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some();
if self.keys.contains(&KeyCode::ShiftLeft) && hands_full {
@@ -3711,26 +3908,53 @@ impl Game<'_> {
[-1, 0, 0] => Direction::West,
_ => Direction::East,
};
let mut level = DryLevel {
world: &self.world,
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
sounds: Vec::new(),
let player = self.use_context();
self.with_level(|b, level, _| {
let mut level = DryLevel::new(level);
let reacts = b
.use_item_on(
&mut level,
&mut horizon_world::level::Ticks::default(),
horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
player,
held.map(|s| &*s.item),
)
.consumes_action();
(reacts, (level.changed.into_iter().collect(), level.sounds))
})
}
/// Run BlockItem.place on a disposable level before predicting its swing.
/// The real level supplies collision shapes and building-blocking entities;
/// block writes, random draws, scheduled ticks and events stay in the preview.
fn remote_can_place(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool {
if !self.may_build() {
return false;
}
let ctx = horizon_world::level::PlaceContext {
clicked_pos: horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face: horizon_core::geometry::Direction::ALL[face_direction(hit.face) as usize],
hit: Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
inside: hit.face == [0; 3],
yaw: self.yaw,
pitch: self.pitch,
sneaking: self.keys.contains(&KeyCode::ShiftLeft),
item: stack.item.to_string(),
can_use_game_master_blocks: self.can_use_game_master_blocks(),
};
let reacts = self
.res
.behaviours()
.use_item_on(
&mut level,
&mut horizon_world::level::Ticks::default(),
horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
self.use_context(),
held.map(|s| &*s.item),
self.with_level(|b, level, _| {
let mut level = DryLevel::new(level);
matches!(
b.place_block(
&mut level,
&mut horizon_world::level::Ticks::default(),
&ctx
),
horizon_world::level::PlaceOutcome::Placed { .. }
)
.consumes_action();
(reacts, (level.changed.into_iter().collect(), level.sounds))
})
}
/// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether
@@ -3911,6 +4135,14 @@ impl Game<'_> {
id: self.creatures.projectiles[i].id as i32,
}));
self.reset_attack_strength();
} else if let Some(hit) = self.remote_object_hit()
&& self.mob_hit().is_none_or(|(_, d)| hit.distance < d)
&& self.before_block(hit.distance)
{
// VehicleEntity.hurtServer, ItemFrame and ArmorStand hurtServer,
// a painting broken: the server decides.
self.send(S::Attack(play::Attack { id: hit.id }));
self.reset_attack_strength();
} else if let Some((i, distance)) = self.mob_hit()
&& self.before_block(distance)
{
@@ -3985,23 +4217,38 @@ impl Game<'_> {
Ok(true)
}
KeyCode::KeyQ => {
if self.spectator() {
return Ok(true);
}
let all = self.keys.contains(&KeyCode::ControlLeft);
// MultiPlayerGameMode.dropItem: predict removal before sending
// the action, then swing only if a nonempty stack was removed.
let dropped = horizon_client::items::take_held_drop(
&mut self.inventory[self.selected],
all,
false,
);
self.send(S::PlayerAction(play::PlayerAction {
action: if all { 4 } else { 5 },
pos: [0; 3],
direction: 0,
sequence: 0,
}));
// Inventory.removeFromSelected (prediction).
let slot = &mut self.inventory[self.selected];
if let Some(s) = slot {
if all || s.count <= 1 {
*slot = None;
} else {
s.count -= 1;
}
if dropped.is_some() {
self.swing_hand(Hand::Main, SwingAnimation::DEFAULT);
}
self.swing_arm();
Ok(true)
}
// MultiPlayerGameMode.isServerControlledInventory: riding a
// horse or llama, the server opens its inventory
// (ServerboundPlayerCommandPacket OPEN_INVENTORY).
KeyCode::KeyE if self.riding_mount_with_menu() => {
let id = self.remote.as_ref().map_or(0, |r| r.entity_id);
self.send(S::PlayerCommand(play::PlayerCommand {
id,
action: 5,
data: 0,
}));
Ok(true)
}
KeyCode::KeyE => {
@@ -4248,6 +4495,7 @@ impl Game<'_> {
r.menu = None;
r.menu_title = None;
}
self.mount_menu_reset();
// The client's menu has no level access: what it holds is the server's.
self.station = None;
self.craft_size = 2;
@@ -4432,6 +4680,21 @@ impl Game<'_> {
self.screen = Screen::Inventory;
self.capture(false);
}
/// `ClientPacketListener.handleMountScreenOpen`: a horse's or llama's
/// inventory; for another entity the window is closed again.
fn remote_open_mount(&mut self, p: play::MountScreenOpen) {
let columns = usize::try_from(p.columns).unwrap_or(0).min(5);
if !self.open_remote_mount_menu(p.entity as u32, columns) {
self.send(S::ContainerClose(play::ContainerClose {
container: p.container,
}));
return;
}
if let Some(r) = self.remote.as_mut() {
r.menu = Some((p.container, format!("{MOUNT_MENU}{columns}")));
r.menu_title = None;
}
}
/// The type of the menu a server opened (`MenuType`'s id).
pub(super) fn remote_menu_type(&self) -> Option<&str> {
Some(self.remote.as_ref()?.menu.as_ref()?.1.as_str())
@@ -4678,7 +4941,7 @@ pub(super) fn input_ordinal(input: Input) -> i32 {
/// The client's world for a guess at what a click does: reads go to the
/// world, writes stay here and are dropped.
struct DryLevel<'w> {
world: &'w horizon_client::world::World,
base: &'w dyn horizon_world::level::LevelAccess,
changed: HashMap<horizon_core::position::BlockPos, BlockStateId>,
random: horizon_core::random::LegacyRandom,
/// The sounds the use plays (a door's creak).
@@ -4708,6 +4971,17 @@ pub(super) fn hand_operated(name: &str) -> bool {
|| name == "lever"
}
impl<'w> DryLevel<'w> {
fn new(base: &'w dyn horizon_world::level::LevelAccess) -> Self {
Self {
base,
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
sounds: Vec::new(),
}
}
}
impl horizon_world::level::LevelAccess for DryLevel<'_> {
fn emit(&mut self, event: horizon_world::level::LevelEvent) {
if let horizon_world::level::LevelEvent::Sound {
@@ -4724,7 +4998,7 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> {
self.changed
.get(&pos)
.copied()
.unwrap_or_else(|| self.world.block(pos.x, pos.y, pos.z))
.unwrap_or_else(|| self.base.block_state(pos))
}
fn set_raw(
&mut self,
@@ -4736,13 +5010,31 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> {
Some(previous)
}
fn is_loaded(&self, pos: horizon_core::position::BlockPos) -> bool {
self.world.loaded(pos.x, pos.z)
self.base.is_loaded(pos)
}
fn min_y(&self) -> i32 {
self.base.min_y()
}
fn max_y(&self) -> i32 {
self.base.max_y()
}
fn block_light(&self, pos: horizon_core::position::BlockPos) -> i32 {
self.base.block_light(pos)
}
fn sky_light(&self, pos: horizon_core::position::BlockPos) -> i32 {
self.base.sky_light(pos)
}
fn sky_darken(&self) -> i32 {
self.base.sky_darken()
}
fn is_unobstructed(&self, pos: horizon_core::position::BlockPos, state: BlockStateId) -> bool {
self.base.is_unobstructed(pos, state)
}
fn random(&mut self) -> &mut horizon_core::random::LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
self.world.game_time
self.base.game_time()
}
}
@@ -4854,10 +5146,128 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_
}
}
impl Remote {
/// The local player's profile UUID.
pub(super) fn profile(&self) -> u128 {
self.profile
}
/// The entity id of a player in the level, by profile UUID.
pub(super) fn player_entity(&self, uuid: u128) -> Option<u32> {
self.level_players
.iter()
.find(|(_, u)| **u == uuid)
.map(|(id, _)| *id as u32)
}
}
#[cfg(test)]
mod tests {
use super::Game;
#[test]
fn placement_preview_checks_obstruction_without_changing_the_level() {
use super::DryLevel;
use horizon_core::{position::BlockPos, random::LegacyRandom};
use horizon_world::{
level::{
Behaviours, LevelAccess, PlaceContext, PlaceOutcome, Ticks, data::load_registry,
},
registry::BlockStateId,
};
struct Level {
air: BlockStateId,
stone: BlockStateId,
obstructed: bool,
loaded: bool,
ceiling: i32,
}
impl LevelAccess for Level {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
if pos == BlockPos::new(0, 0, 0) {
self.stone
} else {
self.air
}
}
fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option<BlockStateId> {
panic!("preview must not write to the live level");
}
fn is_loaded(&self, _: BlockPos) -> bool {
self.loaded
}
fn max_y(&self) -> i32 {
self.ceiling
}
fn is_unobstructed(&self, pos: BlockPos, _: BlockStateId) -> bool {
assert_eq!(pos, BlockPos::new(0, 1, 0));
!self.obstructed
}
fn random(&mut self) -> &mut LegacyRandom {
panic!("preview must not advance the live level's random source");
}
fn game_time(&self) -> i64 {
0
}
}
// As with the LAN tests, prepared game resources are optional locally.
let resources = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
if !resources.join("block-behaviours.json").exists() {
return;
}
let registry = load_registry(&resources).unwrap();
let behaviours = Behaviours::load(&registry, &resources).unwrap();
let mut base = Level {
air: registry.default_state("minecraft:air").unwrap(),
stone: registry.default_state("minecraft:stone").unwrap(),
obstructed: false,
loaded: true,
ceiling: 320,
};
for item in [
"minecraft:stone",
"minecraft:oak_slab",
"minecraft:oak_door",
// GrowingPlantHeadBlock.getStateForPlacement draws a random age.
"minecraft:twisting_vines",
] {
let ctx = PlaceContext {
clicked_pos: BlockPos::new(0, 0, 0),
face: horizon_core::geometry::Direction::Up,
hit: horizon_core::geometry::Vec3::new(0.5, 1.0, 0.5),
inside: false,
yaw: 0.0,
pitch: 45.0,
sneaking: false,
item: item.into(),
can_use_game_master_blocks: false,
};
for (obstructed, loaded, ceiling) in [
(false, true, 320),
(true, true, 320),
(false, false, 320),
(false, true, 1),
] {
base.obstructed = obstructed;
base.loaded = loaded;
base.ceiling = ceiling;
let valid = !obstructed && loaded && ceiling > 1;
let mut preview = DryLevel::new(&base);
let outcome = behaviours.place_block(&mut preview, &mut Ticks::default(), &ctx);
assert_eq!(
matches!(outcome, PlaceOutcome::Placed { .. }),
valid,
"{item}, obstructed={obstructed}, loaded={loaded}, ceiling={ceiling}"
);
assert_eq!(preview.changed.is_empty(), !valid);
assert_eq!(base.block_state(BlockPos::new(0, 1, 0)), base.air);
}
}
}
#[test]
fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() {
// InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand.
@@ -0,0 +1,136 @@
//! A server's mobs as their synched data has them
//! (ClientPacketListener.handleSetEntityData, then each entity's
//! `onSyncedDataUpdated`): what a client draws from it rather than from its
//! own simulation, which a client of a server doesn't run.
use super::Game;
use horizon_client::mobs::{Mob, Species, tame};
use horizon_protocol::entity_data::Value;
/// The values `apply` takes from one SetEntityData packet, by vanilla's entry
/// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses).
fn apply(m: &mut Mob, values: &[(u8, i32, Value)]) {
let species = m.species();
let baby = super::lan::baby_index(&m.kind.id);
for (index, _, value) in values {
match (*index, value) {
// Entity.DATA_SHARED_FLAGS_ID's FLAG_ONFIRE: Entity.isOnFire on a
// 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_HEALTH_ID: the boss bars and the death
// animation follow it.
(9, Value::Float(health)) => m.health = *health,
(i, Value::Bool(b)) if Some(i) == baby => m.extra.age = if *b { -1 } else { 0 },
_ => {}
}
match (species, *index, value) {
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared.
(Species::Sheep, 18, Value::Byte(wool)) => {
m.extra.color = (*wool & 15) as u8;
m.extra.sheared = wool & 16 != 0;
}
// TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4.
(Species::Wolf | Species::Cat | Species::Parrot, 18, Value::Byte(flags)) => {
m.extra.sitting = flags & 1 != 0;
m.extra.tame = flags & 4 != 0;
}
// Wolf.DATA_COLLAR_COLOR and Cat's.
(Species::Wolf, 21, Value::Int(c)) | (Species::Cat, 23, Value::Int(c)) => {
m.extra.color = (*c & 15) as u8;
}
// AbstractCubeMob.ID_SIZE: its size and box (refreshDimensions).
(Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => {
m.extra.size = (*size).clamp(1, 127);
}
_ => {}
}
}
}
impl Game<'_> {
/// SetEntityData for a mob of the server's.
pub(super) fn remote_mob_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) {
apply(m, values);
}
}
}
/// A mob as a client constructs it before its data arrives: the synched
/// defaults the server leaves out (`getNonDefaultValues`) that differ from
/// what `Mob::new` gives, such as a wolf's and a cat's red collar.
pub(super) fn client_defaults(m: &mut Mob) {
if matches!(m.species(), Species::Wolf | Species::Cat) {
m.extra.color = tame::RED;
}
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_protocol::entity_data::serializer as s;
/// A mob of the prepared resources' type `kind`, as a client spawns it
/// (None without the resources).
fn mob(kind: &str) -> Option<Mob> {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
let types = horizon_client::mobs::MobTypes::load(&root).ok()?;
let t = std::sync::Arc::new(types.types.get(kind)?.clone());
let mut m = Mob::new(1, t, horizon_core::geometry::Vec3::ZERO, 0.0);
client_defaults(&mut m);
Some(m)
}
#[test]
fn a_sheep_takes_its_wool_and_a_calf_its_size() {
let Some(mut m) = mob("minecraft:sheep") else {
return;
};
apply(&mut m, &[(18, s::BYTE, Value::Byte(14 | 16))]);
assert_eq!((m.extra.color, m.extra.sheared), (14, true));
apply(&mut m, &[(18, s::BYTE, Value::Byte(0))]);
assert_eq!((m.extra.color, m.extra.sheared), (0, false));
let mut calf = mob("minecraft:cow").unwrap();
apply(&mut calf, &[(16, s::BOOLEAN, Value::Bool(true))]);
assert!(calf.is_baby());
apply(&mut calf, &[(16, s::BOOLEAN, Value::Bool(false))]);
assert!(!calf.is_baby());
}
#[test]
fn a_wolf_takes_its_owner_flags_and_collar() {
let Some(mut m) = mob("minecraft:wolf") else {
return;
};
assert_eq!(m.extra.color, tame::RED);
apply(
&mut m,
&[
(18, s::BYTE, Value::Byte(4 | 1)),
(21, s::INT, Value::Int(11)),
],
);
assert!(m.extra.tame && m.extra.sitting);
assert_eq!(m.extra.color, 11);
}
#[test]
fn fire_health_and_size_follow_the_server() {
let Some(mut m) = mob("minecraft:slime") else {
return;
};
apply(
&mut m,
&[
(0, s::BYTE, Value::Byte(1)),
(9, s::FLOAT, Value::Float(12.5)),
(18, s::INT, Value::Int(4)),
],
);
assert_eq!((m.fire_ticks, m.health, m.extra.size), (1, 12.5, 4));
apply(&mut m, &[(0, s::BYTE, Value::Byte(0))]);
assert_eq!(m.fire_ticks, 0);
}
}
@@ -52,6 +52,8 @@ impl Game<'_> {
invisible: false,
check_interval: 0,
});
} else if kind == "minecraft:lightning_bolt" {
self.spawn_remote_bolt(id, position);
} else if kind == "minecraft:painting" {
// The variant comes with the entity data; until then the
// registry's first one (VariantUtils.getAny).
@@ -188,7 +190,12 @@ impl Game<'_> {
/// A move's rotation and ground state for an object.
pub(super) fn turn_remote_object(&mut self, id: i32, yaw: Option<f32>, on_ground: bool) {
let id = id as u32;
// The boat the player drives turns here (isLocalInstanceAuthoritative).
let driven = self.riding;
if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
if Some(id) == driven {
return;
}
if let Some(yaw) = yaw {
b.yaw = yaw;
}
@@ -213,7 +220,12 @@ impl Game<'_> {
c.previous_yaw = c.yaw;
c.position = step(c.id, c.position);
}
// The boat the player drives moves here, not where the server says.
let driven = self.riding;
for b in &mut self.boats {
if Some(b.id) == driven {
continue;
}
b.previous = b.position;
b.previous_yaw = b.yaw;
b.position = step(b.id, b.position);
@@ -274,5 +286,6 @@ impl Game<'_> {
self.armor_stands.retain(|a| a.id != id);
self.item_frames.retain(|f| f.id != id);
self.paintings.retain(|p| p.id != id);
self.bolts.retain(|b| b.id != id);
}
}
@@ -0,0 +1,189 @@
//! Boats, minecarts, item frames, armor stands and paintings for a server's
//! client: single player on its server thread, a LAN guest, a player on a
//! dedicated server.
//!
//! The client aims at them like at mobs (`Minecraft.hitResult`, then
//! `ServerboundInteractPacket`), and rides the vehicle the server seats it in
//! (`ClientPacketListener.handleSetEntityPassengersPacket`). A boat is
//! controlled by its rider's client: it ticks here and its moves go to the
//! server (`LocalPlayer.tick`: `ServerboundMoveVehiclePacket`,
//! `AbstractBoat.tick`: `ServerboundPaddleBoatPacket`). A minecart moves on
//! the server with the rider's input, and the rider sits in it.
use super::{Game, Keys, view_vector};
use horizon_core::geometry::Vec3;
use horizon_protocol::packets::play::{self, Serverbound as S};
/// An object under the crosshair: its entity id, how far along the view it
/// was hit, and where (`EntityHitResult.getLocation` minus the entity's
/// position, the interact packet's location).
pub(super) struct ObjectHit {
pub id: i32,
pub distance: f64,
pub location: [f64; 3],
}
impl Game<'_> {
/// The nearest boat, minecart, item frame, armor stand or painting the
/// view hits within reach.
pub(super) fn remote_object_hit(&self) -> Option<ObjectHit> {
let eye = self.eye_position()?;
let dir = view_vector(self.yaw, self.pitch);
let at = |d: f64| {
[
eye[0] + dir[0] * d,
eye[1] + dir[1] * d,
eye[2] + dir[2] * d,
]
};
let block_centre = |p: [i32; 3]| {
[
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
]
};
let mut hits: Vec<(i32, f64, [f64; 3])> = Vec::new();
if let Some((i, d)) = self.painting_hit() {
let p = &self.paintings[i];
hits.push((p.id as i32, d, block_centre(p.pos)));
}
if let Some((i, d)) = self.frame_hit() {
let f = &self.item_frames[i];
hits.push((f.id as i32, d, block_centre(f.pos)));
}
if let Some((i, d, _)) = self.armor_stand_hit() {
let a = &self.armor_stands[i];
let p = a.position;
hits.push((a.id as i32, d, [p.x, p.y, p.z]));
}
if let Some((i, d)) = self.boat_hit() {
let p = self.boats[i].position;
hits.push((self.boats[i].id as i32, d, [p.x, p.y, p.z]));
}
if let Some((i, d)) = self.cart_hit() {
let p = self.carts[i].position;
hits.push((self.carts[i].id as i32, d, [p.x, p.y, p.z]));
}
let (id, distance, origin) = hits.into_iter().min_by(|a, b| a.1.total_cmp(&b.1))?;
let point = at(distance);
Some(ObjectHit {
id,
distance,
location: [
point[0] - origin[0],
point[1] - origin[1],
point[2] - origin[2],
],
})
}
/// `ClientPacketListener.handleSetEntityPassengersPacket`: who rides
/// `vehicle` now. The local player gets in or out; mobs and other
/// players sit where the server keeps them.
pub(super) fn remote_set_passengers(&mut self, vehicle: i32, passengers: &[i32]) {
let Some(me) = self.remote.as_ref().map(|r| r.entity_id) else {
return;
};
let vehicle_id = vehicle as u32;
for m in &mut self.mobs {
if m.extra.mount == Some(vehicle_id) && !passengers.contains(&(m.id as i32)) {
m.extra.mount = None;
} else if passengers.contains(&(m.id as i32)) {
m.extra.mount = Some(vehicle_id);
}
}
if passengers.contains(&me) {
if self.riding != Some(vehicle_id) {
self.riding = Some(vehicle_id);
if let Some(p) = self.player.as_mut() {
p.velocity = Vec3::ZERO;
p.fall_distance = 0.0;
}
}
} else if self.riding == Some(vehicle_id) {
// The server takes the player out, then teleports it.
self.riding = None;
}
}
/// The local player's tick in its vehicle, in place of its own movement:
/// false when it rides nothing.
pub(super) fn remote_ride(&mut self, keys: Keys) -> bool {
let Some(id) = self.riding else {
return false;
};
if let Some(i) = self.mobs.iter().position(|m| m.id == id) {
// An animal moves on the server with the rider's input
// (PlayerInput); here the jump bar charges for the HUD and the
// rider sits where `positionRider` puts it.
self.charge_mount_jump(i, keys);
self.position_rider();
return true;
}
let seat = if let Some(i) = self.boats.iter().position(|b| b.id == id) {
// AbstractBoat.tick on the controlling client: steer and move.
let mut b = self.boats[i].clone();
b.input = [keys.left, keys.right, keys.forward, keys.backward];
let b = self.tick_boat(b, true);
// positionRider: the seat turns with the boat; clampRotation.
self.yaw += b.delta_rotation;
let delta = (self.yaw - b.yaw + 180.0).rem_euclid(360.0) - 180.0;
self.yaw += delta.clamp(-105.0, 105.0) - delta;
let seat = b.position;
self.boats[i] = b;
Some(seat)
} else {
// A minecart: the server moves it, the rider sits in it.
self.carts.iter().find(|c| c.id == id).map(|c| c.position)
};
if let Some(p) = self.player.as_mut() {
self.previous_position = p.position;
if let Some(v) = seat {
p.position = Vec3::new(v.x, v.y + super::boats::SEAT, v.z);
}
p.velocity = Vec3::ZERO;
p.fall_distance = 0.0;
}
true
}
/// `LocalPlayer.tick` for a passenger: the boat it controls goes to the
/// server every tick with its paddles (the rider's own position does not).
pub(super) fn remote_vehicle_packets(&self) -> Vec<S> {
let Some(b) = self
.riding
.and_then(|id| self.boats.iter().find(|b| b.id == id))
else {
return Vec::new();
};
vec![
S::MoveVehicle(play::MoveVehicleRequest {
position: [b.position.x, b.position.y, b.position.z],
yaw: b.yaw,
pitch: 0.0,
on_ground: b.on_ground,
}),
S::PaddleBoat(play::PaddleBoat {
left: b.paddling[0],
right: b.paddling[1],
}),
]
}
/// `ClientPacketListener.handleMoveVehicle`: the server put the boat the
/// player drives back.
pub(super) fn remote_move_vehicle(&mut self, position: [f64; 3], yaw: f32) {
let Some(b) = self
.riding
.and_then(|id| self.boats.iter_mut().find(|b| b.id == id))
else {
return;
};
let at = Vec3::new(position[0], position[1], position[2]);
b.previous = at;
b.position = at;
b.yaw = yaw;
b.previous_yaw = yaw;
b.velocity = Vec3::ZERO;
}
}
@@ -222,6 +222,7 @@ impl Game<'_> {
hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope);
self.screen_fx.build(&ScreenInputs {
sprites: &self.gui.atlas.sprites,
flags: &self.gui.atlas.flags,
aspect: size[0] as f32 / size[1].max(1) as f32,
partial,
block_overlay,
@@ -31,6 +31,33 @@ pub(super) struct RespawnConfig {
pub forced: bool,
}
/// A respawn point as a player's save keeps it (`respawn`): dimension,
/// block, yaw and whether it is forced.
pub(super) type SavedRespawn = (String, [i32; 3], f32, bool);
impl RespawnConfig {
/// `RespawnData.of`: the yaw wrapped to [-180, 180).
pub(super) fn wrapped(dim: Dim, pos: [i32; 3], yaw: f32, forced: bool) -> Self {
Self {
dim,
pos,
yaw: wrap_degrees(f64::from(yaw)) as f32,
forced,
}
}
pub(super) fn from_saved((dim, pos, yaw, forced): &SavedRespawn) -> Self {
Self {
dim: Dim::from_id(dim),
pos: *pos,
yaw: *yaw,
forced: *forced,
}
}
pub(super) fn saved(&self) -> SavedRespawn {
(self.dim.id().to_owned(), self.pos, self.yaw, self.forced)
}
}
/// `RespawnAnchorBlock.RESPAWN_HORIZONTAL_OFFSETS`, then the same a block
/// below, a block above, and straight above.
const HORIZONTAL: [[i32; 3]; 8] = [
@@ -62,7 +89,7 @@ pub(super) enum AnchorUse {
}
impl Game<'_> {
fn is_anchor(&self, state: BlockStateId) -> bool {
pub(super) fn is_anchor(&self, state: BlockStateId) -> bool {
&*self.res.facts().get(state).name == "minecraft:respawn_anchor"
}
fn anchor_charges(&self, state: BlockStateId) -> i32 {
@@ -415,6 +442,16 @@ impl Game<'_> {
let (lz, hz) = (bounds.min(Axis::Z), bounds.max(Axis::Z) - 1.0e-5);
(self.border.contains(lo, lz) && self.border.contains(hi, hz)).then_some(position)
}
/// `Block.isPossibleToRespawnInThis`: neither solid nor liquid; banners,
/// signs and pressure plates override it to always.
fn possible_to_respawn_in(&self, state: BlockStateId) -> bool {
let f = self.res.facts().get(state);
let name = &*f.name;
name.ends_with("_banner")
|| name.ends_with("_sign")
|| name.ends_with("_pressure_plate")
|| !(f.legacy_solid || matches!(name, "minecraft:water" | "minecraft:lava"))
}
/// `RespawnAnchorBlock.findStandUpPosition`: a safe spot around the
/// anchor, else any spot.
pub(super) fn anchor_stand_up(&self, pos: [i32; 3]) -> Option<Vec3> {
@@ -428,8 +465,87 @@ impl Game<'_> {
}
None
}
/// `ServerPlayer.findRespawnAndUseSpawnBlock` for an anchor config in the
/// loaded dimension: the position and yaw, using a charge.
/// `AbstractBedBlock.findStandUpPosition` for a bed whose head is at
/// `pos`, facing `forward`, set from `yaw`: beside the bed on the side
/// the player faced away from, around it, then on it; a safe spot
/// first, else any spot (a bunk bed: around it, a block lower, then on
/// it).
pub(super) fn bed_stand_up(&self, pos: [i32; 3], forward: [i32; 3], yaw: f32) -> Option<Vec3> {
// Direction.getClockWise.
let right = [-forward[2], 0, forward[0]];
// Direction.isFacingAngle.
let radians = yaw * 0.017_453_292;
let (dx, dz) = (
-horizon_core::geometry::trig::sin(f64::from(radians)),
horizon_core::geometry::trig::cos(f64::from(radians)),
);
let facing = right[0] as f32 * dx + right[2] as f32 * dz > 0.0;
let side = if facing {
[-right[0], 0, -right[2]]
} else {
right
};
let (f, s) = ([forward[0], forward[2]], [side[0], side[2]]);
// bedSurroundStandUpOffsets and bedAboveStandUpOffsets.
let surround = [
[s[0], s[1]],
[s[0] - f[0], s[1] - f[1]],
[s[0] - f[0] * 2, s[1] - f[1] * 2],
[-f[0] * 2, -f[1] * 2],
[-s[0] - f[0] * 2, -s[1] - f[1] * 2],
[-s[0] - f[0], -s[1] - f[1]],
[-s[0], -s[1]],
[-s[0] + f[0], -s[1] + f[1]],
[f[0], f[1]],
[s[0] + f[0], s[1] + f[1]],
];
let above = [[0, 0], [-f[0], -f[1]]];
let at = |base: [i32; 3], offsets: &[[i32; 2]], check: bool| {
offsets.iter().find_map(|o| {
self.safe_dismount_location([base[0] + o[0], base[1], base[2] + o[1]], check)
})
};
let below = [pos[0], pos[1] - 1, pos[2]];
// isBunkBed: a bed below.
if self.is_bed(self.world.block(below[0], below[1], below[2])) {
return at(pos, &surround, true)
.or_else(|| at(below, &surround, true))
.or_else(|| at(pos, &above, true))
.or_else(|| at(pos, &surround, false))
.or_else(|| at(below, &surround, false))
.or_else(|| at(pos, &above, false));
}
let all: Vec<[i32; 2]> = surround.into_iter().chain(above).collect();
at(pos, &all, true).or_else(|| at(pos, &all, false))
}
pub(super) fn is_bed(&self, state: BlockStateId) -> bool {
self.res.facts().get(state).name.ends_with("_bed")
}
/// The bed's `facing`, as a step.
fn bed_forward(&self, state: BlockStateId) -> [i32; 3] {
let facing = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("facing").cloned());
match facing.as_deref() {
Some("south") => [0, 0, 1],
Some("west") => [-1, 0, 0],
Some("east") => [1, 0, 0],
_ => [0, 0, -1],
}
}
/// `BedRule.canSetSpawn` of the bed's rule attribute (`bed_rule`,
/// `straw_bed_rule`): only the Overworld's beds set the spawn, straw
/// beds never.
pub(super) fn bed_sets_spawn(&self, state: BlockStateId) -> bool {
self.dim == Dim::Overworld && &*self.res.facts().get(state).name != "minecraft:straw_bed"
}
/// `ServerPlayer.findRespawnAndUseSpawnBlock` for a config in the loaded
/// dimension: the position and yaw, using an anchor's charge; a bed's
/// stand-up spot. A forced point (`spawnpoint`) that is no anchor or bed
/// holds if a player fits in it; anything else is gone.
pub(super) fn find_respawn_and_use(
&mut self,
c: RespawnConfig,
@@ -440,7 +556,19 @@ impl Game<'_> {
&& (c.forced || self.anchor_charges(state) > 0)
&& self.anchor_works())
{
return Ok(None);
// A bed where its bed rule lets it set the spawn.
if self.is_bed(state) && self.bed_sets_spawn(state) {
let facing = self.bed_forward(state);
let stand = self.bed_stand_up(c.pos, facing, c.yaw);
return Ok(stand.map(|p| (p, look_at_yaw(p, c.pos))));
}
let [x, y, z] = c.pos;
let free = c.forced
&& !self.is_anchor(state)
&& self.possible_to_respawn_in(state)
&& self.possible_to_respawn_in(self.world.block(x, y + 1, z));
let at = Vec3::new(f64::from(x) + 0.5, f64::from(y) + 0.1, f64::from(z) + 0.5);
return Ok(free.then_some((at, c.yaw)));
}
let stand = self.anchor_stand_up(c.pos);
if !c.forced
@@ -0,0 +1,123 @@
//! Worlds and the multiplayer server list from the control socket: what the Select World, Edit
//! World and Multiplayer screens do, by world folder. Changing a world needs the title screen
//! (no world open), as those screens do; deleting one needs `--confirm`.
use super::Game;
use horizon_client::{Result, title};
use serde_json::{Value, json};
use std::{path::PathBuf, sync::mpsc::Sender, time::UNIX_EPOCH};
pub(super) const HELP: &[&str] = &[
"worlds the saved worlds, newest first: folder, name, mode, last played, version",
"world-rename FOLDER NAME rename a world (Edit World; its folder stays)",
"world-backup FOLDER zip a world into backups/ (Edit World > Make Backup)",
"world-delete FOLDER --confirm delete a world for good (Select World > Delete)",
"servers the multiplayer server list (servers.dat): name and address",
];
fn saves() -> Result<PathBuf> {
Ok(std::env::current_dir()?.join("saves"))
}
impl Game<'_> {
/// Some(reply) for these commands (Some(None): the reply comes later), None for others.
pub(super) fn saves_control(
&mut self,
words: &[&str],
line: &str,
reply: &Sender<String>,
) -> Result<Option<Option<Value>>> {
let folder = || {
words
.get(1)
.copied()
.ok_or_else(|| format!("{} FOLDER: the folder from worlds", words[0]))
};
let on_title = || {
if self.title.is_some() {
Ok(())
} else {
Err(format!(
"{} needs the title screen: save and leave the world first (pause, then Save and Quit to Title)",
words[0]
))
}
};
let value = match words[0] {
"worlds" => {
let worlds: Vec<Value> = title::list_worlds(&saves()?)
.iter()
.map(|w| {
json!({
"folder": w.folder,
"name": w.name,
"mode": if w.creative { "creative" } else { "survival" },
"last_played": w.modified.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64),
"commands": w.commands,
"version": w.version,
})
})
.collect();
json!({ "worlds": worlds })
}
"world-rename" => {
on_title()?;
let folder = folder()?;
let name = line
.trim_start()
.strip_prefix("world-rename")
.and_then(|rest| rest.trim_start().strip_prefix(folder))
.map(str::trim)
.filter(|n| !n.is_empty())
.ok_or("world-rename FOLDER NAME: missing the new name")?;
title::world_management::rename(&saves()?, folder, name)?;
if let Some(title) = self.title.as_mut() {
title.worlds_changed();
}
json!({ "ok": true, "folder": folder, "name": name })
}
"world-delete" => {
on_title()?;
let folder = folder()?;
if !words.contains(&"--confirm") {
return Err(format!(
"world-delete deletes {folder} for good: ask the player, then add --confirm"
)
.into());
}
title::world_management::delete(&saves()?, folder)?;
if let Some(title) = self.title.as_mut() {
title.worlds_changed();
}
json!({ "ok": true, "deleted": folder })
}
"world-backup" => {
on_title()?;
let folder = folder()?.to_owned();
let saves = saves()?;
let backups = title::world_management::backups_path(&saves);
// A big world takes a while to zip: off the game thread, as Make Backup does.
let reply = reply.clone();
std::thread::spawn(move || {
let answer = match title::world_management::backup(&saves, &folder) {
Ok(bytes) => {
json!({ "ok": true, "folder": folder, "backups": backups, "bytes": bytes })
}
Err(e) => json!({ "error": format!("backup of {folder} failed: {e}") }),
};
let _ = reply.send(answer.to_string());
});
return Ok(Some(None));
}
"servers" => {
let file = horizon_client::multiplayer::servers_file(&saves()?);
let servers: Vec<Value> = horizon_protocol::servers::load(&file)
.iter()
.map(|s| json!({ "name": s.name, "address": s.ip }))
.collect();
json!({ "servers": servers })
}
_ => return Ok(None),
};
Ok(Some(Some(value)))
}
}
+101 -68
View File
@@ -7,6 +7,31 @@ use horizon_client::{
ui,
};
impl Screen {
/// Screen.extractBackground for non-isInGameUi screens, and
/// PauseScreen.extractBackground only when showPauseMenu is true.
pub(super) fn blurs_background(self, pause_menu: bool) -> bool {
match self {
Self::Paused => pause_menu,
Self::Options
| Self::Stats
| Self::Advancements
| Self::WorldOptions
| Self::Friends => true,
Self::Playing
| Self::GameModeSwitcher
| Self::Chat
| Self::Creative
| Self::Inventory
| Self::Dead
| Self::CommandBlock => false,
// WinScreen.extractBackground: the poem fills the screen with the End portal, the
// credits alone blur. Game::menu_blur knows which one rolls.
Self::Win => false,
}
}
}
/// PauseScreen buttons: (x, y, width, label key, action id, active).
/// https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/PauseScreen
fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static str, u8, bool)> {
@@ -43,6 +68,9 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s
}
/// The icon row: report bugs, feedback, friends, player reporting.
/// `FRIENDS_ICON` (vanilla's `CommonButtons.friends`) opens Horizon's
/// Play with Friends; the others stay inactive.
const FRIENDS_ICON: usize = 2;
fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] {
let x0 = ((w - 212.0) * 0.5).floor() + 60.0;
let y = ((h - 166.0) * 0.25).floor() + 98.0;
@@ -69,41 +97,8 @@ impl Game<'_> {
pub(super) fn external_server(&self) -> bool {
self.remote.is_some() && self.integrated.is_none()
}
/// Whether the pause menu is drawn in Horizon's style (over a blurred world).
pub(super) fn horizon_pause(&self) -> bool {
self.screen == Screen::Paused
&& self.pause_menu
&& self.title.is_none()
&& horizon_client::ui_theme::horizon()
}
fn pause_labels(&self) -> (String, &'static str) {
if let Some(server) = &self.integrated {
return (server.world_name.clone(), "Save and quit");
}
if self.external_server() {
("Multiplayer".to_owned(), "Disconnect")
} else {
(self.level.name.clone(), "Save and quit")
}
}
pub(super) fn draw_pause_menu(&mut self, batch: &mut HudBatch) {
if horizon_client::ui_theme::horizon() {
let opened = *self.pause_since.get_or_insert_with(std::time::Instant::now);
let (world, quit) = self.pause_labels();
self.tick_friends();
let friends = self.friends_view();
let mut ui = horizon_client::ui_theme::Ui::new(&self.gui.atlas, batch, self.cursor);
horizon_client::front::pause::draw(
&mut ui,
&world,
quit,
opened,
&friends,
self.external_server(),
);
ui.finish();
return;
}
let friends = self.friends_view().shown;
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
@@ -131,12 +126,41 @@ impl Game<'_> {
hover,
);
}
for (x, y, sprite) in pause_icons(w, h) {
ui::button(batch, atlas, x, y, 20.0, 20.0, &Text::empty(), false, false);
let mut tooltip = None;
for (i, (x, y, sprite)) in pause_icons(w, h).into_iter().enumerate() {
let active = i == FRIENDS_ICON && friends;
let hover = ui::hovered(self.cursor, x, y, 20.0, 20.0);
// The icon has no label: name it for controller focus and the
// control socket's widget tree.
if i == FRIENDS_ICON {
horizon_client::widgets::record(
horizon_client::friends_screen::TITLE,
[x, y, 20.0, 20.0],
active,
);
}
ui::button(
batch,
atlas,
x,
y,
20.0,
20.0,
&Text::empty(),
active,
active && hover,
);
// SpriteIconButton.CenteredIcon: the 15x15 sprite at
// x + width / 2 - 15 / 2 in integer pixels, untinted even
// when the button is inactive.
batch.sprite_scaled(atlas, sprite, x + 3.0, y + 3.0, 15.0, 15.0, u32::MAX);
if i == FRIENDS_ICON && hover {
tooltip = Some(Text::literal(horizon_client::friends_screen::TITLE));
}
}
// SpriteIconButton.withTootip: the label as a tooltip.
if let Some(tip) = tooltip {
ui::tooltip(batch, atlas, &[tip], self.cursor);
}
}
pub(super) fn pause_click(&mut self) -> Result<()> {
@@ -148,29 +172,16 @@ impl Game<'_> {
let b = HudBatch::new(size);
(b.width, b.height)
};
let hit = if horizon_client::ui_theme::horizon() {
let size = self
.renderer
.as_ref()
.map_or([1, 1], |r| [r.config.width, r.config.height]);
let mut b = HudBatch::new(size);
let (world, quit) = self.pause_labels();
horizon_client::front::pause::click(
&self.gui.atlas,
&mut b,
self.cursor.0,
self.cursor.1,
&world,
quit,
&self.friends_view(),
self.external_server(),
)
} else {
pause_buttons(w, h, self.external_server())
.into_iter()
.find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
.map(|b| b.4)
};
let friends = pause_icons(w, h)[FRIENDS_ICON];
let hit = pause_buttons(w, h, self.external_server())
.into_iter()
.find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
.map(|b| b.4)
.or_else(|| {
(self.friends_view().shown
&& ui::hovered(self.cursor, friends.0, friends.1, 20.0, 20.0))
.then_some(10)
});
match hit {
Some(0) => {
self.screen = Screen::Playing;
@@ -180,17 +191,11 @@ impl Game<'_> {
Some(3) => self.open_stats(),
Some(4) => self.open_advancements(true),
Some(9) => self.open_world_options(),
Some(10) => {
if let Err(e) = self.friends_start() {
self.system_message(Text::literal(format!("Couldn't share the world: {e}")));
}
}
Some(11) => self.friends_copy(),
Some(12) => self.friends_stop(),
Some(10) => self.screen = Screen::Friends,
Some(2) => self.close_world()?,
_ => {}
}
if hit.is_some() && !horizon_client::ui_theme::horizon() {
if hit.is_some() {
self.audio.play_button_click();
}
Ok(())
@@ -334,7 +339,35 @@ impl Game<'_> {
#[cfg(test)]
mod tests {
use super::pause_buttons;
use super::{Screen, pause_buttons};
#[test]
fn menu_blur_matches_vanilla_screen_backgrounds() {
for screen in [
Screen::Options,
Screen::Stats,
Screen::Advancements,
Screen::WorldOptions,
] {
assert!(screen.blurs_background(false));
assert!(screen.blurs_background(true));
}
assert!(Screen::Paused.blurs_background(true));
assert!(!Screen::Paused.blurs_background(false));
for screen in [
Screen::Playing,
Screen::GameModeSwitcher,
Screen::Chat,
Screen::Creative,
Screen::Inventory,
Screen::Dead,
Screen::CommandBlock,
Screen::Win,
] {
assert!(!screen.blurs_background(true));
assert!(!screen.blurs_background(false));
}
}
#[test]
fn pause_menu_uses_disconnect_for_servers_and_keeps_world_options() {
+146 -9
View File
@@ -7,9 +7,11 @@
//! another level: a Respawn packet keeping all data, then a teleport to the
//! exit once the destination has loaded around them.
use super::end::GatewayJob;
use super::nether_portal::{PLAYER_DELAY, Plan};
use super::respawn_anchor::RespawnConfig;
use super::{Dim, Game, lan::LanHost};
use horizon_client::lan::hub::TickCtx;
use horizon_client::{lan::hub::TickCtx, text::Text};
use horizon_core::{geometry::Vec3, position::BlockPos};
/// A trip under way: the player is in the destination's level, whose
@@ -22,6 +24,12 @@ pub(super) struct Trip {
end: bool,
/// The Nether portal plan, whose exit is found or built on arrival.
plan: Option<Plan>,
/// Through an End gateway, within the level: its exit, found or built
/// on arrival.
gateway: Option<GatewayJob>,
/// A respawn at this point outside the Overworld, resolved through its
/// block on arrival.
respawn: Option<RespawnConfig>,
/// Sent by a command: the player is already where it goes.
placed: bool,
}
@@ -95,7 +103,7 @@ impl Game<'_> {
if let Some(pos) = self.nether_portal_inside(at) {
self.portals.player.set_inside(pos, PLAYER_DELAY);
}
let (end_portal, _) = self.inside_end_portals(at, WIDTH, HEIGHT);
let (end_portal, gateway) = self.inside_end_portals(at, WIDTH, HEIGHT);
if end_portal {
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
@@ -109,6 +117,19 @@ impl Game<'_> {
self.portals.player.cooldown = 10;
return;
}
// EndGatewayBlock.entityInside: a gateway that is not cooling down
// takes the player at once (no transition time) and cools down
// (triggerCooldown), even for a player still on its own cooldown.
if let Some(g) = gateway
&& self.gateway_enter(g)
{
if self.portals.player.cooldown == 0 {
self.start_gateway_trip(host, conn, g);
}
// setPortalCooldown: after the trip, or again while cooling down.
self.portals.player.cooldown = 10;
return;
}
let rule = if invulnerable {
"players_nether_portal_creative_delay"
} else {
@@ -172,11 +193,16 @@ impl Game<'_> {
_ => 1.0,
};
self.end_portal_travel = end;
let scaled = self.end_destination(target).unwrap_or(Vec3::new(
from.x * scale,
from.y,
from.z * scale,
));
// Leaving the End: the player's own respawn point.
let own = if end {
self.as_guest(host, conn, |g| g.end_destination(target))
.flatten()
} else {
None
};
let scaled = own
.or_else(|| self.end_destination(target))
.unwrap_or(Vec3::new(from.x * scale, from.y, from.z * scale));
self.end_portal_travel = false;
if let Err(e) = self.enter_level(Some(host), target) {
log::error!("could not open {}: {e}", target.id());
@@ -197,6 +223,8 @@ impl Game<'_> {
target: destination,
end,
plan,
gateway: None,
respawn: None,
placed: false,
});
if let Err(e) = self.enter_level(Some(host), source) {
@@ -204,6 +232,93 @@ impl Game<'_> {
}
}
/// A respawned player waits at its point outside the Overworld for the
/// level to load around it.
pub(super) fn respawn_trip(&mut self, conn: u32, config: RespawnConfig) {
let [x, y, z] = config.pos;
self.server_trips.push(Trip {
conn,
dim: config.dim,
target: Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5),
end: false,
plan: None,
gateway: None,
respawn: Some(config),
placed: false,
});
}
/// `findRespawnAndUseSpawnBlock` for the player in place, at its point
/// in the level in place: where it stands up, facing the anchor (with
/// the deplete sound) or the bed; else the point is forgotten
/// (`block.minecraft.spawn.not_valid`).
pub(super) fn resolve_server_respawn(&mut self, config: RespawnConfig) -> Option<(Vec3, f32)> {
let [x, y, z] = config.pos;
let anchor = self.is_anchor(self.world.block(x, y, z));
match self.find_respawn_and_use(config, true) {
Ok(Some((at, yaw))) => {
if !config.forced && anchor {
let [x, y, z] = config.pos.map(f64::from);
self.audio.play(
"minecraft:block.respawn_anchor.deplete",
Some([x, y, z]),
1.0,
1.0,
);
}
Some((at, yaw))
}
Ok(None) | Err(_) => {
self.respawn_config = None;
self.system_message(Text::translate("block.minecraft.spawn.not_valid", &[]));
None
}
}
}
/// TeleportTransition.missingRespawnBlock: the world spawn, in the
/// Overworld.
fn respawn_at_world_spawn(&mut self, host: &mut LanHost, conn: u32) {
let at = self.level.world_spawn.map_or(
self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]),
|[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5],
);
self.level_teleports.push(LevelTeleport {
conn,
dim: Dim::Overworld,
at,
rotation: None,
});
self.run_level_teleports(host);
}
/// `TheEndGatewayBlockEntity.getPortalPosition` and the teleport within
/// the End (keeping the player's motion and look): straight to an exact
/// exit, else once the destination has loaded around the player, who
/// waits there (its exit is found among those blocks, or built).
fn start_gateway_trip(&mut self, host: &mut LanHost, conn: u32, gateway: [i32; 3]) {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let (job, destination) = self.gateway_job(gateway);
let at = [destination.x, destination.y, destination.z];
// Relative.union(DELTA, ROTATION).
host.hub.teleport_keeping_motion(i, at);
if let GatewayJob::Known { exact: true, .. } = job {
return;
}
self.server_trips.push(Trip {
conn,
dim: self.dim,
target: destination,
end: false,
plan: None,
gateway: Some(job),
respawn: None,
placed: false,
});
}
/// The trips into the level in place whose destination has loaded
/// around their target: the exit (the Nether portal found or built, the
/// End platform, the Overworld's spawn column) and the teleport there.
@@ -232,8 +347,28 @@ impl Game<'_> {
}
self.resolve_arrivals();
let yaw = host.hub.guests[i].yaw;
let (position, yaw) = if trip.end {
match self.end_arrival(trip.target) {
let (position, yaw) = if let Some(config) = trip.respawn {
match self.as_guest(host, trip.conn, |g| g.resolve_server_respawn(config)) {
Some(Some(found)) => found,
_ => {
self.respawn_at_world_spawn(host, trip.conn);
continue;
}
}
} else if let Some(job) = trip.gateway {
match self.resolve_gateway(job, trip.target) {
Ok(at) => (at, yaw),
Err(e) => {
log::error!("End gateway exit: {e}");
(trip.target, yaw)
}
}
} else if trip.end {
let arrival = match self.as_guest(host, trip.conn, |g| g.end_arrival(trip.target)) {
Some(arrival) => arrival,
None => self.end_arrival(trip.target),
};
match arrival {
Ok((at, turned)) => (at, turned.unwrap_or(yaw)),
Err(e) => {
log::error!("End arrival: {e}");
@@ -293,6 +428,8 @@ impl Game<'_> {
target: Vec3::new(t.at[0], t.at[1], t.at[2]),
end: false,
plan: None,
gateway: None,
respawn: None,
placed: true,
});
if let Err(e) = self.enter_level(Some(host), source) {
@@ -104,6 +104,21 @@ impl Game<'_> {
self.load_shader_pack();
}
}
/// A file dropped on the window: a shader pack while the Shader Packs
/// page shows (`OptionsUi::drop_shader_pack`).
pub(super) fn drop_shader_pack(&mut self, path: &std::path::Path) {
match self.ui.options.drop_shader_pack(&mut self.settings, path) {
Some(Ok(())) => {
self.settings.save(&Self::options_path());
self.load_shader_pack();
}
Some(Err(e)) => {
log::warn!("Horizon: shader pack {}: {e}", path.display());
self.system_message(Text::literal(format!("Shader pack: {e}")));
}
None => {}
}
}
fn shader_pack_error(&mut self, id: &str, error: &str) {
log::warn!("Horizon: shader pack {id}: {error}");
// The Shader Packs page says why on the pack's row: the first line,
+74 -61
View File
@@ -12,6 +12,8 @@ pub(super) struct StartupMenu {
title: Option<Title>,
options: OptionsUi,
options_open: bool,
/// The credits from Credits & Attribution, and their last frame.
win: Option<(horizon_client::win_screen::WinScreen, Instant)>,
root: PathBuf,
cursor: (f32, f32),
pointer: (f64, f64),
@@ -73,11 +75,6 @@ impl StartupMenu {
&self.root,
);
title.last_server = settings.file.string("lastServer");
if horizon_client::ui_theme::horizon() {
title
.opening
.set(Some(horizon_client::front::Opening::new()));
}
self.title = Some(title);
}
}
@@ -152,9 +149,6 @@ impl StartupMenu {
fn title_key(&mut self, event: &KeyEvent) {
let shortcut = self.shortcut(event);
let Some(title) = &mut self.title else { return };
if title.skip_opening() {
return;
}
if let Some(shortcut) = shortcut {
if title.has_caret_field() {
title.field_shortcut(shortcut, &mut self.clipboard);
@@ -378,7 +372,26 @@ impl Loading {
let _ = std::fs::create_dir_all(&dir);
packs::open_folder(&dir);
}
Event::ButtonClick => {}
Event::Credits => {
if let Some(gui) = &self.gui {
let name = self.options.as_ref().map_or_else(
|| horizon_client::offline_name::generate(0),
Options::player_name,
);
let screen = horizon_client::win_screen::WinScreen::new(
false,
&self.menu.root,
&name,
&gui.atlas.font,
);
self.menu.win = Some((screen, Instant::now()));
}
}
Event::ReloadShaderPack => {
self.save_menu_settings();
}
// The startup menu runs before the game opens a control socket.
Event::ButtonClick | Event::CopyAgentDetails => {}
}
}
}
@@ -422,14 +435,6 @@ impl Loading {
event_loop: &ActiveEventLoop,
event: WindowEvent,
) -> Result<()> {
if let WindowEvent::MouseInput {
state,
button: MouseButton::Left,
..
} = &event
{
horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed);
}
if let WindowEvent::KeyboardInput { event, .. } = &event
&& let PhysicalKey::Code(key) = event.physical_key
{
@@ -450,12 +455,22 @@ impl Loading {
}
self.apply_menu_settings();
}
WindowEvent::DroppedFile(path) => {
match self
.menu
.options
.drop_shader_pack(&mut self.settings, &path)
{
Some(Ok(())) => self.save_menu_settings(),
Some(Err(e)) => log::warn!("Horizon: shader pack {}: {e}", path.display()),
None => {}
}
}
WindowEvent::RedrawRequested => self.draw(),
WindowEvent::ModifiersChanged(modifiers) => self.menu.modifiers = modifiers.state(),
WindowEvent::Focused(false) => {
self.menu.modifiers = ModifiersState::empty();
self.menu.physical_keys.clear();
horizon_client::ui_theme::set_pressed(false);
self.menu.dragging = false;
if let Some(title) = &mut self.menu.title {
title.release();
@@ -473,6 +488,20 @@ impl Loading {
}
}
_ if self.gui.is_none() || self.menu.pending.is_some() => {}
WindowEvent::KeyboardInput { event, .. } if self.menu.win.is_some() => {
if let PhysicalKey::Code(code) = event.physical_key {
let pressed = event.state == ElementState::Pressed;
if code == KeyCode::Escape && pressed {
self.menu.win = None;
} else if let Some(key) = horizon_client::win_screen::Key::from_code(code)
&& let Some((win, _)) = &mut self.menu.win
{
win.key(key, pressed);
}
}
}
WindowEvent::MouseInput { .. } | WindowEvent::MouseWheel { .. }
if self.menu.win.is_some() => {}
WindowEvent::CursorMoved { position, .. } => {
self.menu.pointer = (position.x, position.y);
self.update_menu_cursor();
@@ -508,41 +537,23 @@ impl Loading {
button: MouseButton::Left,
..
} => {
let mut batch = HudBatch::new(self.menu_size());
let batch = HudBatch::new(self.menu_size());
if let (Some(title), Some(gui)) = (&mut self.menu.title, &self.gui) {
if state == ElementState::Released {
title.release();
title.release_field();
} else {
let action = if horizon_client::ui_theme::horizon() {
let action = title.click_horizon(
&gui.atlas,
&mut batch,
self.menu.cursor.0,
self.menu.cursor.1,
);
// Horizon's deeper world-management pages use classic fields.
title.press_field(
&gui.atlas,
self.menu.cursor,
(batch.width, batch.height),
self.menu.modifiers.shift_key(),
);
action
} else {
let (action, _) = title.click(
self.menu.cursor.0,
self.menu.cursor.1,
(batch.width, batch.height),
);
title.press_field(
&gui.atlas,
self.menu.cursor,
(batch.width, batch.height),
self.menu.modifiers.shift_key(),
);
action
};
let (action, _) = title.click(
self.menu.cursor.0,
self.menu.cursor.1,
(batch.width, batch.height),
);
title.press_field(
&gui.atlas,
self.menu.cursor,
(batch.width, batch.height),
self.menu.modifiers.shift_key(),
);
self.menu_action(event_loop, action);
}
}
@@ -610,6 +621,15 @@ impl Loading {
self.progress.line(),
self.progress.fraction(),
);
} else if let Some((win, frame)) = &mut self.menu.win {
let now = Instant::now();
// 20 ticks a second: the startup menu runs no tick rate.
let delta_ticks = now.duration_since(*frame).as_secs_f32() * 20.0;
*frame = now;
win.draw(batch, &gui.atlas, delta_ticks, Default::default());
if win.finished(batch.height) {
self.menu.win = None;
}
} else if self.menu.options_open {
self.menu
.options
@@ -617,18 +637,12 @@ impl Loading {
} else if let Some(title) = &mut self.menu.title {
title.poll_backup();
let _ = title.update_toast(self.settings.notification_display_time);
if horizon_client::ui_theme::horizon() {
let mut ui = horizon_client::ui_theme::Ui::new(&gui.atlas, batch, self.menu.cursor);
title.draw_horizon(&mut ui, 0.0);
ui.finish();
} else {
title.draw(
&gui.atlas,
batch,
self.menu.cursor,
self.settings.file.bool("hideSplashTexts"),
);
}
title.draw(
&gui.atlas,
batch,
self.menu.cursor,
self.settings.file.bool("hideSplashTexts"),
);
}
}
@@ -730,7 +744,6 @@ mod tests {
// Navigate and enter a world name without a registry, biomes, pack
// tables or a Game. Replacing fallback artwork preserves this state.
let title = loading.menu.title.as_mut().unwrap();
title.opening.set(None);
title.mode = horizon_client::title::Mode::Create {
name: String::new(),
seed: "42".into(),
+51 -16
View File
@@ -306,9 +306,18 @@ impl Game<'_> {
}
}
/// `PhantomSpawner.tick`: tired players under an open night sky draw
/// phantoms.
/// phantoms. A custom spawner ticks only while `spawn_mobs` is on
/// (`ServerChunkCache.tickChunks`), and this one only spawns enemies
/// (`ServerLevel.isSpawningMonsters`: `spawn_monsters` too). Every
/// player of the level counts: the game's own and the hosted ones (a
/// server thread's players are all hosted).
pub(super) fn spawn_phantoms(&mut self) {
if !self.ui.rules.bool("spawn_phantoms") || self.dim != Dim::Overworld {
let rules = &self.ui.rules;
if !rules.bool("spawn_mobs")
|| !rules.bool("spawn_monsters")
|| !rules.bool("spawn_phantoms")
|| self.dim != Dim::Overworld
{
return;
}
self.stats.phantom_tick -= 1;
@@ -317,16 +326,42 @@ impl Game<'_> {
}
let r = &mut self.world.random;
self.stats.phantom_tick += (60 + r.next_int_bound(60).unwrap_or(0)) * 20;
if self.sky_darken() < 5 || self.spectator() {
if self.sky_darken() < 5 {
return;
}
let Some(p) = self.player.as_ref() else {
return;
};
let rest = |s: &Stats| s.get("custom", "minecraft:time_since_rest");
// `level.players()`: (block position, time since rest) of each player
// who isn't a spectator.
let mut players = Vec::new();
if let Some(p) = self.player.as_ref()
&& !self.spectator()
{
players.push((p.position, rest(&self.stats)));
}
if let Some(host) = self.lan.as_ref() {
let level = self.dim.id();
for g in host.hub.guests.iter().filter(|g| {
g.placed
&& g.dimension == level
&& g.game_mode != horizon_client::lan::guest::SPECTATOR
}) {
let since = host.play.get(&g.conn).map_or(0, |p| rest(&p.stats));
players.push((
Vec3::new(g.position[0], g.position[1], g.position[2]),
since,
));
}
}
for (position, since) in players {
self.spawn_phantoms_near(position, since);
}
}
/// One player's turn of `PhantomSpawner.tick`.
fn spawn_phantoms_near(&mut self, position: Vec3, since_rest: i32) {
let pos = [
p.position.x.floor() as i32,
p.position.y.floor() as i32,
p.position.z.floor() as i32,
position.x.floor() as i32,
position.y.floor() as i32,
position.z.floor() as i32,
];
if pos[1] < 63 || !self.can_see_sky(pos) {
return;
@@ -336,15 +371,15 @@ impl Game<'_> {
if r.next_float() * 3.0 >= 2.0 {
return;
}
let rest = self.stats.get("custom", "minecraft:time_since_rest").max(1);
if r.next_int_bound(rest).unwrap_or(0) < 72000 {
if r.next_int_bound(since_rest.max(1)).unwrap_or(0) < 72000 {
return;
}
let at = [
pos[0] - 10 + r.next_int_bound(21).unwrap_or(10),
pos[1] + 20 + r.next_int_bound(15).unwrap_or(0),
pos[2] - 10 + r.next_int_bound(21).unwrap_or(10),
];
// `playerPos.above(20 + nextInt(15)).east(-10 + nextInt(21)).south(...)`:
// the height is drawn first.
let up = 20 + r.next_int_bound(15).unwrap_or(0);
let east = -10 + r.next_int_bound(21).unwrap_or(10);
let south = -10 + r.next_int_bound(21).unwrap_or(10);
let at = [pos[0] + east, pos[1] + up, pos[2] + south];
if !self
.res
.facts()
+150
View File
@@ -0,0 +1,150 @@
//! `WinScreen` in the game: the poem and credits after leaving the End for
//! the first time (`EndPortalBlock.entityInside` -> `ServerPlayer.showEndCredits`,
//! or a server's `WIN_GAME` event), and the credits from Credits &
//! Attribution.
use super::{Game, Screen};
use horizon_client::{
Result,
hud::{EndPortalFill, HudBatch},
win_screen::{Key, WinScreen},
};
use std::time::Instant;
use winit::{
event::{ElementState, KeyEvent},
keyboard::{KeyCode, PhysicalKey},
};
/// What closing the screen does (`WinScreen.onFinished`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Finish {
/// `PERFORM_RESPAWN` in single player: the player, out of the End since
/// the credits began, arrives in the Overworld.
Respawn,
/// `PERFORM_RESPAWN` sent to the server.
RemoteRespawn,
/// Back to Credits & Attribution.
Options,
/// Back to the game (`horizon-ctl credits`).
Closed,
}
pub(super) struct Win {
screen: WinScreen,
finish: Finish,
/// The last drawn frame, for the scroll's game-time delta.
frame: Instant,
}
impl Game<'_> {
pub(super) fn open_win_screen(&mut self, poem: bool, finish: Finish) {
let screen = WinScreen::new(
poem,
&self.options.resources,
&self.options.player_name(),
&self.gui.atlas.font,
);
self.win = Some(Win {
screen,
finish,
frame: Instant::now(),
});
self.keys.clear();
self.screen = Screen::Win;
self.capture(false);
}
/// `ServerPlayer.showEndCredits`: the player leaves the End now (no
/// longer in any level until the credits end) and has seen the credits.
pub(super) fn show_end_credits(&mut self) -> Result<()> {
self.level.seen_credits = true;
self.open_win_screen(true, Finish::Respawn);
self.end_portal_travel = true;
let result = self.enter_dimension(super::Dim::Overworld);
self.end_portal_travel = false;
result
}
/// Stop the scroll `scroll` pixels in (`horizon-ctl credits ... SCROLL`).
pub(super) fn hold_win_screen(&mut self, scroll: f32) {
if let Some(win) = self.win.as_mut() {
win.screen.hold(scroll);
}
}
/// `WinScreen.isPauseScreen`: only the credits without the poem pause.
pub(super) fn win_screen_pauses(&self) -> bool {
self.win.as_ref().is_some_and(|w| !w.screen.poem)
}
/// The player waits out of the world while the poem rolls.
pub(super) fn win_screen_holds_arrival(&self) -> bool {
self.win
.as_ref()
.is_some_and(|w| w.finish == Finish::Respawn)
}
pub(super) fn draw_win_screen(&mut self, batch: &mut HudBatch) {
let Some(win) = self.win.as_mut() else {
return;
};
let now = Instant::now();
// DeltaTracker.getGameTimeDeltaTicks: the frame's length in ticks.
let delta_ticks =
now.duration_since(win.frame).as_secs_f32() / self.clock.tick_duration().as_secs_f32();
win.frame = now;
let sprite = |n: &str| {
self.gui
.atlas
.sprites
.get(n)
.map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0])
};
let fill = EndPortalFill {
sprites: [
sprite("environment/end_sky"),
sprite("entity/end_portal/end_portal"),
],
game_time: (self.world.game_time % 24000) as f32 / 24000.0,
};
win.screen.draw(batch, &self.gui.atlas, delta_ticks, fill);
}
/// `WinScreen.keyPressed` / `keyReleased`; Escape closes it (`onClose`).
pub(super) fn win_key(&mut self, event: &KeyEvent) -> Result<()> {
let PhysicalKey::Code(code) = event.physical_key else {
return Ok(());
};
let pressed = event.state == ElementState::Pressed;
if code == KeyCode::Escape && pressed {
return self.close_win_screen();
}
let Some(key) = Key::from_code(code) else {
return Ok(());
};
if let Some(win) = self.win.as_mut() {
win.screen.key(key, pressed);
}
Ok(())
}
/// `WinScreen.tick`: done once everything has rolled past the top.
pub(super) fn tick_win_screen(&mut self) -> Result<()> {
let height = self.gui_size().1;
if self.win.as_ref().is_some_and(|w| w.screen.finished(height)) {
self.close_win_screen()?;
}
Ok(())
}
/// `WinScreen.respawn` (`onFinished`) and `removed`: the credits music stops.
pub(super) fn close_win_screen(&mut self) -> Result<()> {
let Some(win) = self.win.take() else {
return Ok(());
};
let credits = horizon_client::music::Music::credits();
self.music
.stop_playing_music(&credits, None, &mut self.audio);
match win.finish {
Finish::Options => self.screen = Screen::Options,
Finish::Closed if self.title.is_some() => self.screen = Screen::Playing,
Finish::Respawn | Finish::RemoteRespawn | Finish::Closed => {
if win.finish == Finish::RemoteRespawn {
self.remote_respawn();
}
self.screen = Screen::Playing;
self.capture(true);
}
}
Ok(())
}
}
File diff suppressed because it is too large Load Diff
+596
View File
@@ -0,0 +1,596 @@
//! Animated block sprites, drawn on the GPU as vanilla 26.3 draws them:
//! `SpriteContents.AnimatedTexture` keeps every frame in video memory, and
//! each tick `animate_sprite_blit` or `animate_sprite_interpolate` draws the
//! frame shown (mixed with the next one for `interpolate`) into the atlas.
//!
//! Every frame's mip chain is uploaded once, at the sprite's own size. A tick
//! that changes sprites writes one small job per changed sprite and runs one
//! compute dispatch per mip level (`animate.wgsl`), which repeats the chain
//! into the array's larger layers by whole pixels and mixes interpolated
//! frames. Blending on the CPU at the array's size and copying every changed
//! sprite level by level (a copy command each, a blit each in Mesa) was about
//! a fifth of the render thread on an integrated GPU.
use super::upload::Uploads;
use crate::mipmap::Settings;
use crate::sprites::{FrameBlend, SpriteAnimation};
use wgpu::util::DeviceExt;
/// Bytes of `animate.wgsl`'s `Job`.
const JOB_BYTES: usize = 20;
/// `animate.wgsl`'s workgroup edge.
const WORKGROUP: u32 = 8;
struct Sprite {
animation: SpriteAnimation,
/// What its layer shows (`None`: the frame the array was created with,
/// rewritten on the first tick).
shown: Option<FrameBlend>,
/// Its layer in its sprite array.
layer: u32,
/// Each frame's mip chain: its offset in words in the group's frames.
frames: Vec<u32>,
/// Edge of the chains' first level.
edge: u32,
group: usize,
}
/// The animated sprites of one sprite array whose frames share one buffer.
struct Group {
/// Where its jobs start in `SpriteAnimator::jobs`, in bytes.
offset: u64,
/// One bind group per mip level of the array.
levels: Vec<wgpu::BindGroup>,
/// This tick's jobs.
jobs: Vec<u8>,
}
pub(super) struct SpriteAnimator {
sprites: Vec<Sprite>,
groups: Vec<Group>,
jobs: wgpu::Buffer,
pipeline: wgpu::ComputePipeline,
/// Edge of the arrays' layers.
size: u32,
/// The sprite layers (across the arrays) the last `animate` rewrote, at
/// every mip level: a Java pack's atlas copies them.
pub changed: Vec<u32>,
}
impl SpriteAnimator {
/// `textures` are the sprite arrays, `split` layers each, `size` pixels
/// wide; `animations` hold their frames at that size.
pub fn new(
device: &wgpu::Device,
animations: &[SpriteAnimation],
size: u32,
settings: &[Settings],
textures: &[wgpu::Texture],
split: u32,
) -> Self {
let limits = device.limits();
let limit = limits
.max_storage_buffer_binding_size
.min(limits.max_buffer_size);
let mut frames: Vec<Vec<u8>> = Vec::new();
// Each group's sprite array and frames buffer.
let mut keys: Vec<(u32, usize)> = Vec::new();
let mut counts: Vec<usize> = Vec::new();
let mut sprites = Vec::with_capacity(animations.len());
for animation in animations {
let chains: Vec<_> = (0..animation.frame_count())
.map(|frame| source_chain(animation.pixels(frame), size, settings, animation.layer))
.collect();
let bytes: u64 = chains.iter().map(|(chain, _)| chain.len() as u64).sum();
if bytes > limit {
log::warn!(
"Horizon: layer {}'s animation ({bytes} bytes) does not fit in a storage buffer; it stays still",
animation.layer
);
continue;
}
if frames
.last()
.is_none_or(|data| data.len() as u64 + bytes > limit)
{
frames.push(Vec::new());
}
let buffer = frames.len() - 1;
let data = &mut frames[buffer];
let offsets = chains
.iter()
.map(|(chain, _)| {
let offset = (data.len() / 4) as u32;
data.extend_from_slice(chain);
offset
})
.collect();
let key = (animation.layer / split, buffer);
let group = keys.iter().position(|&k| k == key).unwrap_or_else(|| {
keys.push(key);
counts.push(0);
keys.len() - 1
});
counts[group] += 1;
sprites.push(Sprite {
animation: animation.clone(),
shown: None,
layer: animation.layer % split,
frames: offsets,
edge: chains[0].1,
group,
});
}
let frames: Vec<_> = frames
.iter()
.map(|data| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Animated sprite frames"),
contents: data,
usage: wgpu::BufferUsages::STORAGE,
})
})
.collect();
let align = u64::from(limits.min_storage_buffer_offset_alignment);
let mut offsets = Vec::with_capacity(counts.len());
let mut total = 0;
for &count in &counts {
offsets.push(total);
total = (total + (count * JOB_BYTES) as u64).next_multiple_of(align);
}
let jobs = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Animated sprite jobs"),
size: total.max(align),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Animated sprites"),
source: wgpu::ShaderSource::Wgsl(include_str!("animate.wgsl").into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Animated sprites"),
layout: None,
module: &module,
entry_point: Some("animate"),
compilation_options: Default::default(),
cache: None,
});
let layout = pipeline.get_bind_group_layout(0);
let groups = keys
.iter()
.zip(&counts)
.zip(offsets)
.map(|((&(array, buffer), &count), offset)| {
let texture = &textures[array as usize];
let levels = (0..texture.mip_level_count())
.map(|level| {
let view = texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("Animated sprites"),
dimension: Some(wgpu::TextureViewDimension::D2Array),
base_mip_level: level,
mip_level_count: Some(1),
..Default::default()
});
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Animated sprites"),
layout: &layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: frames[buffer].as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &jobs,
offset,
size: wgpu::BufferSize::new((count * JOB_BYTES) as u64),
}),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&view),
},
],
})
})
.collect();
Group {
offset,
levels,
jobs: Vec::with_capacity(count * JOB_BYTES),
}
})
.collect();
Self {
sprites,
groups,
jobs,
pipeline,
size,
changed: Vec::new(),
}
}
/// Show every sprite's frame at `tick`, rewriting only the sprites whose
/// frame or mix changed (`SpriteContents.AnimationState.tick`).
pub fn animate(
&mut self,
encoder: &mut wgpu::CommandEncoder,
uploads: &mut Uploads,
tick: u64,
) {
self.changed.clear();
if self.collect(tick) == 0 {
return;
}
for group in &self.groups {
uploads.buffer(encoder, &self.jobs, group.offset, &group.jobs);
}
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Animated sprites"),
timestamp_writes: None,
});
pass.set_pipeline(&self.pipeline);
for group in &mut self.groups {
let count = (group.jobs.len() / JOB_BYTES) as u32;
if count == 0 {
continue;
}
for (level, bind) in group.levels.iter().enumerate() {
let groups = (self.size >> level).div_ceil(WORKGROUP);
pass.set_bind_group(0, bind, &[]);
pass.dispatch_workgroups(groups, groups, count);
}
group.jobs.clear();
}
}
/// Queue a job for every sprite whose blend at `tick` differs from what
/// its layer shows; the number of jobs.
fn collect(&mut self, tick: u64) -> usize {
let mut count = 0;
for sprite in &mut self.sprites {
let blend = sprite.animation.blend(tick);
if sprite.shown == Some(blend) {
continue;
}
sprite.shown = Some(blend);
self.changed.push(sprite.animation.layer);
let job = [
sprite.layer,
sprite.frames[blend.frame],
sprite.frames[blend.next],
blend.millis,
sprite.edge,
];
let jobs = &mut self.groups[sprite.group].jobs;
for word in job {
jobs.extend_from_slice(&word.to_le_bytes());
}
count += 1;
}
count
}
}
/// The mip chain a frame's layer is made of, and its first level's edge.
/// `mipmap::generate` makes a sprite scaled up by whole pixels to the
/// array's size from its own size's chain, its first level repeated into the
/// larger levels: that chain, which the shader repeats. Any other sprite: its
/// chain at the array's size.
fn source_chain(pixels: &[u8], size: u32, settings: &[Settings], layer: u32) -> (Vec<u8>, u32) {
let native = settings.get(layer as usize).map_or(0, |s| s.native_size);
let edge = if native.is_power_of_two() && native < size {
native
} else {
size
};
let frame = crate::sprites::resample(pixels, size, edge);
(super::mip_chain(&frame, edge, settings, layer, 1).0, edge)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mipmap::Strategy;
/// `animate.wgsl` on the CPU: `chain` (first level `edge` wide) as the
/// full chain of a `size` layer, mixed `millis` thousandths of the way
/// towards `next`.
fn reference(chain: &[u8], next: &[u8], millis: u32, edge: u32, size: u32) -> Vec<u8> {
let levels = size.trailing_zeros() + 1;
let mut out = Vec::new();
for level in 0..levels {
let width = size >> level;
for y in 0..width {
for x in 0..width {
let texel = if width >= edge {
let scale = width / edge;
y / scale * edge + x / scale
} else {
4 * (edge * edge - width * width) / 3 + y * width + x
} as usize;
for c in 0..4 {
let (a, b) = (
u32::from(chain[texel * 4 + c]),
u32::from(next[texel * 4 + c]),
);
out.push(((a * (1000 - millis) + b * millis + 500) / 1000) as u8);
}
}
}
}
out
}
fn frame(size: u32, seed: u32) -> Vec<u8> {
(0..size * size)
.flat_map(|i| {
let v = i
.wrapping_mul(2654435761)
.wrapping_add(seed.wrapping_mul(40503));
let alpha = match v >> 29 {
0 => 0,
1 => 77,
_ => 255,
};
[(v >> 3) as u8, (v >> 11) as u8, (v >> 19) as u8, alpha]
})
.collect()
}
fn settings(native: u32, strategy: Strategy) -> Settings {
Settings {
native_size: native,
strategy,
alpha_cutoff_bias: -0.1,
..Default::default()
}
}
#[test]
fn source_chains_repeat_into_the_array_chain() {
// Sprites scaled up by whole pixels, at the array's size, and of a
// size that is not a power of two (scaled up to the next one).
for (native, size) in [(16, 16), (16, 64), (8, 32), (32, 64), (1, 16), (24, 32)] {
for strategy in [
Strategy::Auto,
Strategy::Mean,
Strategy::Cutout,
Strategy::StrictCutout,
Strategy::DarkCutout,
] {
for item in [false, true] {
let settings = [
Settings::default(),
Settings {
item,
..settings(native, strategy)
},
];
let pixels = crate::sprites::resample(&frame(native, 3), native, size);
let (expected, _) = super::super::mip_chain(&pixels, size, &settings, 1, 1);
let (chain, edge) = source_chain(&pixels, size, &settings, 1);
let fits = native.is_power_of_two() && native < size;
assert_eq!(edge, if fits { native } else { size });
assert_eq!(
reference(&chain, &chain, 0, edge, size),
expected,
"{native} in {size}, {strategy:?}, item {item}"
);
}
}
}
}
#[test]
fn real_animation_chains_repeat_into_the_array_chain() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
if !root
.join("assets/minecraft/textures/block/water_still.png")
.exists()
{
return;
}
let mut sprites = crate::sprites::Sprites::default();
for name in [
"water_still",
"water_flow",
"lava_still",
"fire_0",
"nether_portal",
"sea_lantern",
"prismarine",
"magma",
"kelp",
"straw_bed",
] {
sprites
.insert(&root, &format!("minecraft:block/{name}"))
.unwrap();
}
sprites.finish();
assert_eq!(sprites.size, 64);
assert_eq!(sprites.animations.len(), 9);
for animation in &sprites.animations {
for frame in 0..animation.frame_count() {
let pixels = animation.pixels(frame);
let (expected, _) =
super::super::mip_chain(pixels, 64, &sprites.mips, animation.layer, 1);
let (chain, edge) = source_chain(pixels, 64, &sprites.mips, animation.layer);
assert!(edge < 64, "layer {}", animation.layer);
assert_eq!(reference(&chain, &chain, 0, edge, 64), expected);
}
}
}
#[test]
fn rounding_matches_f32_mix_but_for_exact_halves() {
// The CPU blend this replaced: f32 mix, then rounded. They differ
// only where the exact mix is a half, which f32 rounded either way.
for millis in 1..1000u32 {
let t = millis as f32 / 1000.0;
for a in 0..=255u32 {
for b in (0..=255u32).step_by(3) {
let f = ((a as f32 / 255.0) * (1.0 - t) + (b as f32 / 255.0) * t) * 255.0;
let exact = a * (1000 - millis) + b * millis;
let ours = (exact + 500) / 1000;
if exact % 1000 != 500 {
assert_eq!(ours, f.round() as u32, "{a} {b} {millis}");
}
}
}
}
}
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
pollster::block_on(adapter.request_device(&Default::default())).ok()
}
/// Every layer's full mip chain, layer major.
fn read_back(
device: &wgpu::Device,
queue: &wgpu::Queue,
texture: &wgpu::Texture,
) -> Vec<Vec<u8>> {
let layers = texture.depth_or_array_layers();
let mut out = vec![Vec::new(); layers as usize];
for level in 0..texture.mip_level_count() {
let edge = texture.width() >> level;
let padded = (edge * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(padded * edge * layers),
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: level,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded),
rows_per_image: Some(edge),
},
},
wgpu::Extent3d {
width: edge,
height: edge,
depth_or_array_layers: layers,
},
);
queue.submit([encoder.finish()]);
buffer
.slice(..)
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let data = buffer.slice(..).get_mapped_range().unwrap();
for (layer, image) in data.chunks((padded * edge) as usize).enumerate() {
for row in image.chunks(padded as usize) {
out[layer].extend_from_slice(&row[..edge as usize * 4]);
}
}
}
out
}
#[test]
fn gpu_layers_match_the_cpu_chains_every_tick() {
let Some((device, queue)) = device() else {
return;
};
let size = 32;
// Layers 1 and 3: 8-pixel sprites with and without interpolation;
// layer 4: one at the array's size. Two layers per array.
let clips = [
(
1,
8,
r#"{"frametime":3,"interpolate":true,"frames":[0,2,1]}"#,
),
(3, 8, r#"{"frametime":2}"#),
(4, 32, r#"{"frametime":5,"interpolate":true}"#),
];
let mut mips = vec![Settings::default(); 6];
let animations: Vec<_> = clips
.iter()
.map(|&(layer, native, metadata)| {
mips[layer as usize] = settings(native, Strategy::Cutout);
let frames = (0..3)
.map(|f| crate::sprites::resample(&frame(native, layer * 7 + f), native, size))
.collect();
crate::sprites::test_frames(layer, frames, metadata)
})
.collect();
let split = 2;
let textures: Vec<_> = (0..3)
.map(|_| {
device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: size,
height: size,
depth_or_array_layers: split,
},
mip_level_count: size.trailing_zeros() + 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
})
})
.collect();
let mut animator = SpriteAnimator::new(&device, &animations, size, &mips, &textures, split);
let mut uploads = Uploads::new(&device);
let mut writes = Vec::new();
for tick in [0, 0, 1, 2, 3, 4, 7, 7, 12, 30] {
let mut encoder = device.create_command_encoder(&Default::default());
let shown: Vec<_> = animator.sprites.iter().map(|s| s.shown).collect();
animator.animate(&mut encoder, &mut uploads, tick);
writes.push(
animator
.sprites
.iter()
.zip(shown)
.filter(|(s, shown)| s.shown != *shown)
.count(),
);
uploads.finish(&encoder);
queue.submit([encoder.finish()]);
for animation in &animations {
let blend = animation.blend(tick);
let chain = |f| source_chain(animation.pixels(f), size, &mips, animation.layer);
let ((current, edge), (next, _)) = (chain(blend.frame), chain(blend.next));
let layers = read_back(
&device,
&queue,
&textures[(animation.layer / split) as usize],
);
assert_eq!(
layers[(animation.layer % split) as usize],
reference(&current, &next, blend.millis, edge, size),
"layer {} at tick {tick}",
animation.layer
);
}
}
// Every sprite on the first tick, then only those whose frame or mix
// changed since they were written: the interpolated ones every tick
// but layer 1 at tick 30 (two 9-tick loops after 12), layer 3 when
// its frame turns over (every 2 ticks, but 12 shows 7's frame).
assert_eq!(writes, [3, 0, 2, 3, 2, 3, 3, 0, 2, 1]);
}
}
@@ -0,0 +1,48 @@
// Animated block sprites (gfx/animate.rs), as vanilla's animate_sprite_blit
// and animate_sprite_interpolate shaders draw them: each job writes its
// frame, or the frame mixed with the next one, into one mip level of its
// sprite array layer. One invocation per texel; the job is the z coordinate.
struct Job {
layer: u32,
// Word offsets of the two frames' mip chains in `frames`.
current: u32,
next: u32,
// Thousandths of the way from `current` to `next` (0: `current` alone).
millis: u32,
// Edge of the chains' first level.
edge: u32,
}
@group(0) @binding(0) var<storage, read> frames: array<u32>;
@group(0) @binding(1) var<storage, read> jobs: array<Job>;
@group(0) @binding(2) var level: texture_storage_2d_array<rgba8unorm, write>;
fn channels(rgba: u32) -> vec4<u32> {
return vec4(rgba & 0xffu, (rgba >> 8u) & 0xffu, (rgba >> 16u) & 0xffu, rgba >> 24u);
}
@compute @workgroup_size(8, 8)
fn animate(@builtin(global_invocation_id) id: vec3<u32>) {
let size = textureDimensions(level).x;
if id.x >= size || id.y >= size {
return;
}
let job = jobs[id.z];
// mipmap::generate: the levels at least as large as the chain's first
// repeat it by whole pixels, the smaller ones are the chain's own.
var texel: u32;
if size >= job.edge {
let scale = size / job.edge;
texel = id.y / scale * job.edge + id.x / scale;
} else {
// Every level above this one, each a quarter of the one before.
texel = 4u * (job.edge * job.edge - size * size) / 3u + id.y * size + id.x;
}
var color = channels(frames[job.current + texel]);
if job.millis > 0u {
// mix(current, next, millis / 1000), rounded to the nearest 8-bit
// value (halves up) in integers: the same on every GPU.
let next = channels(frames[job.next + texel]);
color = (color * (1000u - job.millis) + next * job.millis + 500u) / 1000u;
}
textureStore(level, id.xy, job.layer, vec4<f32>(color) / 255.0);
}
+190 -33
View File
@@ -22,8 +22,16 @@
//! Every solid draw is an entry of one of the two lists, so the CPU records
//! as many draws as without culling: drivers that unroll an indirect
//! multi-draw on the CPU (Mesa's on Intel Gen9) pay per entry. Phase 2's
//! counts come from the GPU, which needs a native multi-draw and forced
//! early depth tests: Vulkan. Translucent draws are not culled.
//! counts come from the GPU, which reads them from the draws themselves:
//! Vulkan's native multi-draw, and Metal's, which wgpu replays as one
//! indirect draw per entry. Translucent draws are not culled.
//!
//! Metal cannot force the depth test before a fragment shader that writes
//! storage (naga writes no `[[early_fragment_tests]]`), so there the boxes
//! are drawn in a pass of their own between the phases, which reads phase
//! 1's depth as a texture and makes the same comparison in the shader: the
//! fragment's depth against the stored one, greater or equal passing. The
//! same fragments pass, so the same sections are seen.
use std::num::NonZeroU64;
use std::sync::{
Arc,
@@ -38,6 +46,13 @@ const RETEST: u32 = 8;
/// more than they save. Else one frame in `PROBE` tests every section.
const MIN_SHARE: f32 = 0.1;
const PROBE: u32 = 64;
/// On Metal, section draws from which a frame culls. Apple's GPUs store and
/// reload the whole frame at each of the passes the test adds, a fixed cost
/// that the sections it hides repay only at high render distances: on an M4
/// Pro at 1080p and render distance 12 (1,000–1,600 draws) culling added
/// about 0.05 ms of GPU time while hiding 15–30% of the solid indices; at
/// 32 (drawn flat, over this many draws) it saved 0.25–1.6 ms.
pub const TILED_MIN_DRAWS: usize = 4096;
/// Boxes over more than this share of the screen count as seen untested.
const BIG: f32 = 0.25;
/// Results read back at once, some frames late so the CPU never waits.
@@ -74,10 +89,40 @@ struct Group {
group: wgpu::BindGroup,
}
/// Where the boxes' depth test runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DepthTest {
/// Forced before the fragment shader, in phase 1's pass (Vulkan).
Early,
/// In the fragment shader, against phase 1's depth read as a texture,
/// in a pass of its own (Metal).
InShader,
}
/// The Vulkan entry point: the depth test forced early, which naga cannot
/// write for Metal (so it is not in `cull.wgsl`, which every backend takes).
const EARLY_TEST: &str = "
@fragment
@early_depth_test(force)
fn fs_box_early(in: Box) -> @location(0) vec4<f32> {
see(in.test);
return vec4(0.0);
}
";
/// The test's depth texture binding (`InShader`), for the view it was made with.
struct DepthGroup {
view: wgpu::TextureView,
group: wgpu::BindGroup,
}
pub struct Cull {
pipeline: wgpu::RenderPipeline,
layout: wgpu::BindGroupLayout,
group: Option<Group>,
depth_test: DepthTest,
depth_layout: Option<wgpu::BindGroupLayout>,
depth_group: Option<DepthGroup>,
params: wgpu::Buffer,
/// Phase 2's draws: the solid draws after phase 1's in the frame's list.
pub phase2: wgpu::Buffer,
@@ -103,6 +148,8 @@ pub struct Cull {
pub hidden: ([usize; 2], f32),
/// Cull every frame, whatever the hidden share (A/B checks).
pub always: bool,
/// Frames with fewer section draws than this do not cull.
pub min_draws: usize,
}
fn buffer(
@@ -134,20 +181,33 @@ impl Cull {
pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features {
adapter.features() & wgpu::Features::SHADER_EARLY_DEPTH_TEST
}
/// Whether the device draws an indirect multi-draw natively and runs
/// fragment shaders that write storage only past an early depth test.
pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool {
adapter.get_info().backend == wgpu::Backend::Vulkan
&& device.features().contains(
wgpu::Features::SHADER_EARLY_DEPTH_TEST | wgpu::Features::INDIRECT_FIRST_INSTANCE,
)
/// Where the device can run the test, if it can: Vulkan with early
/// depth tests, or Metal, both drawing an indirect multi-draw's entries
/// with the instance counts the GPU wrote, with fragment shaders that
/// write storage.
pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Option<DepthTest> {
let depth_test = match adapter.get_info().backend {
wgpu::Backend::Vulkan
if device
.features()
.contains(wgpu::Features::SHADER_EARLY_DEPTH_TEST) =>
{
DepthTest::Early
}
wgpu::Backend::Metal => DepthTest::InShader,
_ => return None,
};
(device
.features()
.contains(wgpu::Features::INDIRECT_FIRST_INSTANCE)
&& adapter.get_downlevel_capabilities().flags.contains(
wgpu::DownlevelFlags::VERTEX_STORAGE
| wgpu::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE,
)
))
.then_some(depth_test)
}
/// `color` is the world pass's colour format.
pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat) -> Self {
pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat, depth_test: DepthTest) -> Self {
let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry {
binding,
visibility,
@@ -180,13 +240,41 @@ impl Cull {
});
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Section culling"),
source: wgpu::ShaderSource::Wgsl(include_str!("cull.wgsl").into()),
source: wgpu::ShaderSource::Wgsl(source(depth_test).into()),
});
let depth_layout = (depth_test == DepthTest::InShader).then(|| {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Section culling depth"),
entries: &[entry(
0,
fragment,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
)],
})
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Section culling"),
bind_group_layouts: &[Some(&layout)],
bind_group_layouts: &[Some(&layout), depth_layout.as_ref()],
..Default::default()
});
// In the shader: no colour target, and phase 1's depth attached read
// only (a pass needs an attachment), its test left to the shader.
let (fragment_entry, targets, depth_compare) = match depth_test {
DepthTest::Early => (
"fs_box_early",
&[Some(wgpu::ColorTargetState {
format: color,
blend: None,
write_mask: wgpu::ColorWrites::empty(),
})][..],
wgpu::CompareFunction::GreaterEqual,
),
DepthTest::InShader => ("fs_box", &[][..], wgpu::CompareFunction::Always),
};
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Section culling"),
layout: Some(&pipeline_layout),
@@ -204,20 +292,16 @@ impl Cull {
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(false),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
depth_compare: Some(depth_compare),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_box"),
entry_point: Some(fragment_entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: color,
blend: None,
write_mask: wgpu::ColorWrites::empty(),
})],
targets,
}),
multiview_mask: None,
cache: None,
@@ -226,6 +310,9 @@ impl Cull {
pipeline,
layout,
group: None,
depth_test,
depth_layout,
depth_group: None,
params: buffer(
device,
"Section culling parameters",
@@ -259,6 +346,7 @@ impl Cull {
stamp: 0,
hidden: ([0; 2], 1.0),
always: false,
min_draws: 0,
}
}
@@ -399,17 +487,69 @@ impl Cull {
}
}
/// In the world pass after phase 1: draw the tested boxes against its
/// depth. Leaves the pass's pipeline and group 0 changed.
pub fn depth_test(&self) -> DepthTest {
self.depth_test
}
/// In the world pass after phase 1 (`Early`): draw the tested boxes
/// against its depth. Leaves the pass's pipeline and group 0 changed.
pub fn test(&self, pass: &mut wgpu::RenderPass<'_>) {
let Some(Group { group, .. }) = &self.group else {
return;
};
if self.depth_test != DepthTest::Early || self.test_data.is_empty() {
return;
}
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, group, &[]);
pass.draw(0..36, 0..self.test_data.len() as u32);
}
/// Before the world pass (`InShader`): the binding of the depth the
/// world is drawn with this frame.
pub fn bind_depth(&mut self, device: &wgpu::Device, depth: &wgpu::TextureView) {
let Some(layout) = &self.depth_layout else {
return;
};
if self.depth_group.as_ref().is_none_or(|g| g.view != *depth) {
self.depth_group = Some(DepthGroup {
view: depth.clone(),
group: device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Section culling depth"),
layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(depth),
}],
}),
});
}
}
/// Between the phases (`InShader`): draw the tested boxes in a pass of
/// their own that reads phase 1's depth, bound by `bind_depth`.
pub fn test_pass(&self, encoder: &mut wgpu::CommandEncoder) {
let (Some(Group { group, .. }), Some(DepthGroup { view, group: depth })) =
(&self.group, &self.depth_group)
else {
return;
};
if self.test_data.is_empty() {
return;
}
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Section culling"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view,
depth_ops: None,
stencil_ops: None,
}),
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, group, &[]);
pass.set_bind_group(1, depth, &[]);
pass.draw(0..36, 0..self.test_data.len() as u32);
}
@@ -498,16 +638,33 @@ impl Cull {
}
}
#[cfg(test)]
mod tests {
#[test]
fn shader_validates() {
let module = naga::front::wgsl::parse_str(include_str!("cull.wgsl")).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
/// The test's shader for `depth_test`.
fn source(depth_test: DepthTest) -> String {
let common = include_str!("cull.wgsl");
match depth_test {
DepthTest::Early => format!("{common}{EARLY_TEST}"),
DepthTest::InShader => common.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shaders_validate() {
for (depth_test, capabilities) in [
(DepthTest::Early, naga::valid::Capabilities::all()),
// What wgpu's Metal backend allows: no early depth test.
(
DepthTest::InShader,
naga::valid::Capabilities::all() - naga::valid::Capabilities::EARLY_DEPTH_TEST,
),
] {
let module = naga::front::wgsl::parse_str(&source(depth_test)).unwrap();
naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities)
.validate(&module)
.unwrap_or_else(|e| panic!("{depth_test:?}: {e:?}"));
}
}
}
+20 -8
View File
@@ -86,16 +86,28 @@ fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box
return out;
}
// Runs only for fragments that pass the depth test (forced early).
@fragment
@early_depth_test(force)
fn fs_box(in: Box) -> @location(0) vec4<f32> {
if results[in.test] != params.stamp {
results[in.test] = params.stamp;
let test = tests[in.test];
// The box is seen at this fragment: store the stamp, and give its phase 2
// draws their instance.
fn see(t: u32) {
if results[t] != params.stamp {
results[t] = params.stamp;
let test = tests[t];
for (var k = 0u; k < test.z; k++) {
phase2[(test.y + k) * 5u + 1u] = 1u;
}
}
return vec4(0.0);
}
// Phase 1's depth, where the test runs in the shader (gfx/cull.rs).
@group(1) @binding(0) var depth: texture_depth_2d;
// The world pass's reversed depth test, greater or equal passing, made here:
// where it cannot be forced before a shader that writes storage, a fragment
// that fails it would still write. Where it can, `fs_box_early` (cull.rs)
// runs only for the fragments that pass it.
@fragment
fn fs_box(in: Box) {
if in.position.z >= textureLoad(depth, vec2<u32>(in.position.xy), 0) {
see(in.test);
}
}
+84
View File
@@ -0,0 +1,84 @@
//! The End sky's six tiled faces, retained for the lifetime of the renderer's atlas.
use crate::mesher::Vertex;
use wgpu::util::DeviceExt;
const VERTICES: u32 = 6 * 16 * 16 * 4;
#[derive(Default)]
pub(super) struct EndSky {
mesh: Option<([f32; 4], wgpu::Buffer)>,
}
impl EndSky {
/// Called only when the End sky is enabled. Rebuild on atlas UV changes;
/// resource reload and device recreation also replace the owning renderer.
pub(super) fn prepare(&mut self, device: &wgpu::Device, uv: Option<[f32; 4]>) {
let Some(uv) = uv else {
self.mesh = None;
return;
};
if self.mesh.as_ref().is_some_and(|(old, _)| *old == uv) {
return;
}
let vertices = vertices(uv);
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("End sky vertices"),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
self.mesh = Some((uv, buffer));
}
/// The celestial pipeline, atlas bind group and quad indices are already bound.
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {
if let Some((_, buffer)) = &self.mesh {
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw_indexed(0..VERTICES / 4 * 6, 0, 0..1);
}
}
}
/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times,
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
fn vertices(uv: [f32; 4]) -> Vec<Vertex> {
let mut out = Vec::with_capacity(VERTICES as usize);
use std::f32::consts::FRAC_PI_2;
let faces = [
glam::Mat4::IDENTITY,
glam::Mat4::from_rotation_x(FRAC_PI_2),
glam::Mat4::from_rotation_x(-FRAC_PI_2),
glam::Mat4::from_rotation_x(std::f32::consts::PI),
glam::Mat4::from_rotation_z(FRAC_PI_2),
glam::Mat4::from_rotation_z(-FRAC_PI_2),
];
let step = 200.0 / 16.0;
for pose in faces {
for a in 0..16 {
for b in 0..16 {
let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32);
let (x1, z1) = (x0 + step, z0 + step);
let corners = [
(x0, z0, [uv[0], uv[1]]),
(x0, z1, [uv[0], uv[3]]),
(x1, z1, [uv[2], uv[3]]),
(x1, z0, [uv[2], uv[1]]),
];
for (x, z, uv) in corners {
let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z));
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 2,
color: 0xFF28_2828,
light: 0,
});
}
}
}
}
out
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,330 @@
use super::*;
use crate::gfx::{Globals, Renderer};
use bytemuck::Zeroable;
use glam::Mat4;
#[test]
fn geometry_matches_pre_residency_vertex_snapshots() {
use sha2::{Digest, Sha256};
// Captured from game/end.rs at 34c3c1cf for full, tiled and non-binary UVs.
// Quantize positions only, avoiding platform sin/cos rounding differences;
// quad order, UVs, tint, material and light retain their exact byte values.
for (uv, expected) in [
(
[0.0, 0.0, 1.0, 1.0],
"f7ee23457fc557b33ecf09c9afaf858f3d8907e108abf06055f627523f733536",
),
(
[0.125, 0.25, 0.375, 0.5],
"f74c4b8d23ec2b7c11b5752821d0733851bf11358f1b26f9448226ff62a6a318",
),
(
[0.13, 0.27, 0.41, 0.59],
"f0aaa39c5b22168bdc7c6c329acb4d3598a2feb61ff7b6f2850b644682749b39",
),
] {
let mut mesh = vertices(uv);
assert_eq!(mesh.len(), VERTICES as usize);
for vertex in &mut mesh {
vertex.pos = vertex.pos.map(|x| {
let n = (x * 1024.0).round() / 1024.0;
if n == 0.0 { 0.0 } else { n }
});
}
assert_eq!(
format!("{:x}", Sha256::digest(bytemuck::cast_slice(&mesh))),
expected
);
}
}
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
eprintln!("End sky test adapter: {:?}", adapter.get_info());
pollster::block_on(adapter.request_device(&Default::default())).ok()
}
#[test]
fn resident_buffer_survives_frames_and_refreshes_with_the_atlas() {
let Some((device, _)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
let mut sky = EndSky::default();
let uv = [0.125, 0.25, 0.375, 0.5];
sky.prepare(&device, Some(uv));
let first = sky.mesh.as_ref().unwrap().1.clone();
assert_eq!(
first.size(),
u64::from(VERTICES) * size_of::<Vertex>() as u64
);
// Immutable: steady-state frames cannot upload into this buffer.
assert_eq!(first.usage(), wgpu::BufferUsages::VERTEX);
for _ in 0..600 {
sky.prepare(&device, Some(uv));
assert_eq!(sky.mesh.as_ref().unwrap().1, first);
}
let moved = [0.5, 0.5, 0.75, 0.75];
sky.prepare(&device, Some(moved));
assert_ne!(sky.mesh.as_ref().unwrap().1, first);
assert_eq!(sky.mesh.as_ref().unwrap().0, moved);
sky.prepare(&device, None);
assert!(sky.mesh.is_none());
sky.prepare(&device, Some(uv));
assert_ne!(sky.mesh.as_ref().unwrap().1, first);
// A resource reload/device recreation starts a new renderer-owned cache,
// even if the replacement atlas happens to use exactly the same UVs.
let mut replacement = EndSky::default();
replacement.prepare(&device, Some(uv));
assert_ne!(
replacement.mesh.as_ref().unwrap().1,
sky.mesh.as_ref().unwrap().1
);
}
/// The actual entity shader and celestial blend, comparing the old combined
/// vertex stream with a resident sky draw followed by a separate flash draw.
#[test]
fn separate_draws_match_combined_celestial_pixels() {
let Some((device, queue)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("End sky differential shader"),
source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()),
});
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("End sky differential pipeline"),
layout: None,
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_entity"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_celestial"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba8Unorm,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::OVER,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let texture = |pixels: &[u8], width, height| {
device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
pixels,
)
};
// Asymmetric, translucent texels expose UV/winding and blend-order errors.
let pixels: Vec<u8> = (0..16 * 16)
.flat_map(|i| {
[
(i * 17) as u8,
(i * 31) as u8,
(i * 7) as u8,
(80 + i % 176) as u8,
]
})
.collect();
let atlas = texture(&pixels, 16, 16).create_view(&Default::default());
let lightmap = texture(&[255; 4], 1, 1).create_view(&Default::default());
let sampler = device.create_sampler(&Default::default());
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let indices = Renderer::quad_indices(&device, VERTICES / 4 + 1);
let mut resident = EndSky::default();
let uv = [0.125, 0.25, 0.375, 0.5];
resident.prepare(&device, Some(uv));
let first = resident.mesh.as_ref().unwrap().1.clone();
let render = |sky: &EndSky, flash: &[Vertex], combined: bool| {
let target = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 64,
height: 64,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&Default::default());
let mut vertices = if combined { vertices(uv) } else { Vec::new() };
vertices.extend_from_slice(flash);
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 64 * 64 * 4,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &group, &[]);
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
if !combined {
sky.draw(&mut pass);
}
if !vertices.is_empty() {
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw_indexed(0..vertices.len() as u32 / 4 * 6, 0, 0..1);
}
}
encoder.copy_texture_to_buffer(
target.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(256),
rows_per_image: Some(64),
},
},
target.size(),
);
queue.submit([encoder.finish()]);
readback
.slice(..)
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
readback.slice(..).get_mapped_range().unwrap().to_vec()
};
let mut cases = 0;
let mut visible_flash_cases = 0;
for yaw in [0.0_f32, 45.0, 90.0, 180.0, 270.0] {
for pitch in [-85.0_f32, -30.0, 0.0, 45.0, 85.0] {
let mut globals = Globals::zeroed();
globals.view_proj = (Mat4::perspective_rh(90_f32.to_radians(), 1.0, 0.05, 1024.0)
* Mat4::from_rotation_x(pitch.to_radians())
* Mat4::from_rotation_y(yaw.to_radians()))
.to_cols_array_2d();
queue.write_buffer(&uniform, 0, bytemuck::bytes_of(&globals));
let no_flash = render(&resident, &[], true);
for level in [0_u32, 1, 127, 255] {
let flash: Vec<_> = if level == 0 {
Vec::new()
} else {
// Same flash size/height, with an arbitrary EndFlashState pose.
let pose = Mat4::from_rotation_y(1.3) * Mat4::from_rotation_x(-1.6);
[(-60.0, -60.0), (60.0, -60.0), (60.0, 60.0), (-60.0, 60.0)]
.map(|(x, z)| Vertex {
pos: pose.transform_point3(glam::vec3(x, 100.0, z)).to_array(),
uv: [0.75 + x / 480.0, 0.75 + z / 480.0],
layer: 2,
color: level * 0x01010101,
light: 0,
normal: [0; 4],
})
.to_vec()
};
resident.prepare(&device, Some(uv));
let expected = render(&resident, &flash, true);
let actual = render(&resident, &flash, false);
visible_flash_cases += usize::from(expected != no_flash);
assert_eq!(actual, expected, "yaw={yaw} pitch={pitch} flash={level}");
assert!(
actual.as_chunks::<4>().0.iter().any(|p| p[..3] != [0; 3]),
"empty frame"
);
assert_eq!(resident.mesh.as_ref().unwrap().1, first);
cases += 1;
}
}
}
assert!(
visible_flash_cases > 0,
"the flash must affect the comparison"
);
eprintln!("{cases} combined/resident framebuffer cases matched exactly");
}
+458 -136
View File
@@ -11,11 +11,37 @@
//! so each block names one section: its id here, which indexes the frame's
//! camera-relative origins (computed on the CPU exactly as for the instance
//! attribute).
//!
//! With occlusion culling (`cull`), phase 1's draws and the translucent ones
//! are copied before the world pass, as without it. Phase 2's draws are
//! copied after the test, which tells which ones it saw: each run of a page
//! reserves room for all of its draws, the copy packs the seen ones at its
//! start, and the run is drawn indirectly with the count the copy reached.
use super::arena::GRAIN;
/// One section draw for `flatten.wgsl`: index count, first sorted index (or
/// `QUADS` for a solid draw), base vertex, first index in the list.
/// `QUADS` for a solid draw; phase 2: its entry in phase 2's draws), base
/// vertex, first index in the list (phase 2: its draw call in phase 2).
type Range = [u32; 4];
/// Where a group of ranges takes its indices.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Source {
/// Solid draws: quads.
Quads,
/// Occlusion culling's phase 2: quads, of the sections its test saw.
Seen,
/// Translucent draws: this sorted index page.
Sorted(u32),
}
/// The frame's draw calls, as `plan` lays them out.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Plan {
phase1_calls: usize,
solid_calls: usize,
total: u64,
}
const QUADS: u32 = u32::MAX;
const GROUP_LIMIT: u32 = 65535;
@@ -38,6 +64,15 @@ pub struct Flat {
pub translucent: wgpu::RenderPipeline,
flatten: wgpu::ComputePipeline,
compute_layout: wgpu::BindGroupLayout,
flatten_seen: wgpu::ComputePipeline,
seen_layout: wgpu::BindGroupLayout,
/// Phase 2's draw calls (`DrawIndexedIndirectArgs`), whose index counts
/// `flatten_seen` makes.
phase2_calls: wgpu::Buffer,
phase2_call_capacity: u64,
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,
blocks_per_page: u64,
pages: Vec<Option<PageTable>>,
@@ -52,12 +87,14 @@ pub struct Flat {
ranges: wgpu::Buffer,
range_capacity: u64,
range_data: Vec<Range>,
/// Segments of `range_data` by index source: (sorted index page or
/// `None` for solid draws, first range, ranges).
segments: Vec<(Option<u32>, u64, u64)>,
/// Segments of `range_data` by index source: (source, first range,
/// ranges).
segments: Vec<(Source, u64, u64)>,
empty: wgpu::Buffer,
/// This frame's draw calls: solid ones, then translucent ones.
/// This frame's draw calls: solid ones (phase 1's, then phase 2's when
/// culling), then translucent ones.
pub calls: Vec<Call>,
pub phase1_calls: usize,
pub solid_calls: usize,
/// Frames with fewer section draws keep the per-section draws.
pub min_draws: usize,
@@ -121,42 +158,60 @@ fn buffer(
/// Lays out the frame's index list: each draw's range (destinations in draw
/// order) grouped by index source into `ranges`, every group padded to
/// `align` entries for binding, with `segments` naming each group; and the
/// draw calls, one per run of draws in the same vertex page, solid and
/// translucent apart. Returns the first translucent call and the list's
/// length.
/// 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.
fn plan(
draws: &[[u32; 5]],
pages: &[(u32, Option<u32>)],
phase1_draws: usize,
solid_draws: usize,
align: u64,
calls: &mut Vec<Call>,
ranges: &mut Vec<Range>,
segments: &mut Vec<(Option<u32>, u64, u64)>,
) -> (usize, u64) {
segments: &mut Vec<(Source, u64, u64)>,
) -> Plan {
calls.clear();
ranges.clear();
segments.clear();
let mut solid_calls = None;
let (mut phase1_calls, mut solid_calls) = (None, None);
let mut total = 0u64;
let mut by_source: Vec<(Option<u32>, Vec<Range>)> = Vec::new();
let mut by_source: Vec<(Source, Vec<Range>)> = Vec::new();
for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() {
let first = if sorted.is_some() { d[2] } else { QUADS };
let range = [d[0], first, d[3], total as u32];
match by_source.iter_mut().find(|(s, _)| *s == sorted) {
Some((_, list)) => list.push(range),
None => by_source.push((sorted, vec![range])),
if i == phase1_draws {
phase1_calls.get_or_insert(calls.len());
}
if i == solid_draws {
solid_calls = Some(calls.len());
}
match calls.last_mut() {
Some(last) if last.page == page && i != solid_draws => last.count += d[0],
Some(last) if last.page == page && i != phase1_draws && i != solid_draws => {
last.count += d[0]
}
_ => calls.push(Call {
page,
first: total as u32,
count: d[0],
}),
}
let (source, range) = match sorted {
Some(p) => (Source::Sorted(p), [d[0], d[2], d[3], total as u32]),
None if (phase1_draws..solid_draws).contains(&i) => (
Source::Seen,
[
d[0],
(i - phase1_draws) as u32,
d[3],
(calls.len() - 1 - phase1_calls.unwrap_or(0)) as u32,
],
),
None => (Source::Quads, [d[0], QUADS, d[3], total as u32]),
};
match by_source.iter_mut().find(|(s, _)| *s == source) {
Some((_, list)) => list.push(range),
None => by_source.push((source, vec![range])),
}
total += u64::from(d[0]);
}
for (source, list) in by_source {
@@ -165,7 +220,12 @@ fn plan(
let padded = (ranges.len() as u64).next_multiple_of(align);
ranges.resize(padded as usize, [0; 4]);
}
(solid_calls.unwrap_or(calls.len()), total)
let solid_calls = solid_calls.unwrap_or(calls.len());
Plan {
phase1_calls: phase1_calls.unwrap_or(calls.len()).min(solid_calls),
solid_calls,
total,
}
}
impl Flat {
@@ -201,24 +261,37 @@ impl Flat {
storage(2, compute, false),
],
});
let seen_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Flatten phase 2 section draws"),
entries: &[
storage(0, compute, true),
storage(2, compute, false),
storage(3, compute, true),
storage(4, compute, false),
],
});
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Flatten section draws"),
source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()),
});
let flatten = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Flatten section draws"),
layout: Some(
&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Flatten section draws"),
bind_group_layouts: &[Some(&compute_layout)],
..Default::default()
}),
),
module: &module,
entry_point: Some("flatten"),
compilation_options: Default::default(),
cache: None,
});
let compute_pipeline = |layout: &wgpu::BindGroupLayout, entry| {
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Flatten section draws"),
layout: Some(
&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Flatten section draws"),
bind_group_layouts: &[Some(layout)],
..Default::default()
}),
),
module: &module,
entry_point: Some(entry),
compilation_options: Default::default(),
cache: None,
})
};
let flatten = compute_pipeline(&compute_layout, "flatten");
let flatten_seen = compute_pipeline(&seen_layout, "flatten_seen");
let storage_usage = wgpu::BufferUsages::STORAGE;
Self {
solid: pipeline(&layout, "Terrain solid (flat)", "fs_solid", None),
@@ -230,6 +303,17 @@ impl Flat {
),
flatten,
compute_layout,
flatten_seen,
seen_layout,
phase2_calls: buffer(
device,
"Flat section draw calls, phase 2",
20,
wgpu::BufferUsages::INDIRECT | storage_usage,
),
phase2_call_capacity: 1,
phase2_call_data: Vec::new(),
phase2_group: None,
draw_layout,
blocks_per_page: page_vertices.div_ceil(GRAIN),
pages: Vec::new(),
@@ -251,6 +335,7 @@ impl Flat {
segments: Vec::new(),
empty: buffer(device, "No sorted indices", 16, storage_usage),
calls: Vec::new(),
phase1_calls: 0,
solid_calls: 0,
min_draws: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") {
0
@@ -321,6 +406,9 @@ impl Flat {
/// the origins of the sections they draw by id. Records the copy into
/// `encoder`; `calls` then lists the frame's draw calls. False when the
/// frame cannot be drawn flat (the per-section draws then apply).
///
/// When culling, the solid draws from `phase1_draws` are phase 2's, which
/// `phase2` holds as the test leaves them: `flatten_phase2` copies them.
#[allow(clippy::too_many_arguments)]
pub fn prepare(
&mut self,
@@ -329,10 +417,18 @@ impl Flat {
uploads: &mut super::upload::Uploads,
draws: &[[u32; 5]],
pages: &[(u32, Option<u32>)],
phase1_draws: usize,
solid_draws: usize,
phase2: Option<&wgpu::Buffer>,
origins: impl Iterator<Item = (u32, [f32; 4])>,
sorted_page: impl Fn(u32) -> wgpu::Buffer,
) -> bool {
self.phase2_group = None;
let phase1_draws = if phase2.is_some() {
phase1_draws
} else {
solid_draws
};
// Origins by section id.
self.origin_data.clear();
for (id, o) in origins {
@@ -362,18 +458,25 @@ impl Flat {
bytemuck::cast_slice(&self.origin_data),
);
}
let (solid_calls, total) = plan(
let Plan {
phase1_calls,
solid_calls,
total,
} = plan(
draws,
pages,
phase1_draws,
solid_draws,
self.range_align,
&mut self.calls,
&mut self.range_data,
&mut self.segments,
);
self.phase1_calls = phase1_calls;
self.solid_calls = solid_calls;
if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {
self.calls.clear();
self.phase1_calls = 0;
self.solid_calls = 0;
return false;
}
@@ -401,22 +504,82 @@ impl Flat {
0,
bytemuck::cast_slice(&self.range_data),
);
// Phase 2's calls start empty, each at the start of its room.
self.phase2_call_data.clear();
self.phase2_call_data.extend(
self.calls[phase1_calls..solid_calls]
.iter()
.map(|c| [0, 1, c.first, 0, 0]),
);
let phase2_calls = self.phase2_call_data.len() as u64;
if phase2_calls > self.phase2_call_capacity {
self.phase2_call_capacity = phase2_calls.next_power_of_two();
self.phase2_calls = buffer(
device,
"Flat section draw calls, phase 2",
self.phase2_call_capacity * 20,
wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::STORAGE,
);
}
if phase2_calls > 0 {
uploads.buffer(
encoder,
&self.phase2_calls,
0,
bytemuck::cast_slice(&self.phase2_call_data),
);
}
let ranges_at = |first: u64, count: u64| {
wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &self.ranges,
offset: first * 16,
size: wgpu::BufferSize::new(count * 16),
})
};
if let (Some(phase2), Some(&(_, first, count))) = (
phase2,
self.segments.iter().find(|(s, ..)| *s == Source::Seen),
) {
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Flatten phase 2 section draws"),
layout: &self.seen_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: ranges_at(first, count),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: phase2.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.phase2_calls.as_entire_binding(),
},
],
});
self.phase2_group = Some((group, count as u32));
}
let groups: Vec<(wgpu::BindGroup, u32)> = self
.segments
.iter()
.map(|&(source, first, count)| {
let sorted = source.map(&sorted_page);
.filter_map(|&(source, first, count)| {
let sorted = match source {
Source::Quads => None,
Source::Seen => return None,
Source::Sorted(page) => Some(sorted_page(page)),
};
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Flatten section draws"),
layout: &self.compute_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &self.ranges,
offset: first * 16,
size: wgpu::BufferSize::new(count * 16),
}),
resource: ranges_at(first, count),
},
wgpu::BindGroupEntry {
binding: 1,
@@ -428,7 +591,7 @@ impl Flat {
},
],
});
(group, count as u32)
Some((group, count as u32))
})
.collect();
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
@@ -464,16 +627,28 @@ impl Flat {
}
true
}
/// Draws `calls` with a flat pipeline set and `vertices` giving each
/// page's vertex buffer.
/// After occlusion culling's test: copies the phase 2 draws it saw.
pub fn flatten_phase2(&self, encoder: &mut wgpu::CommandEncoder) {
let Some((group, count)) = &self.phase2_group else {
return;
};
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Flatten phase 2 section draws"),
timestamp_writes: None,
});
pass.set_pipeline(&self.flatten_seen);
pass.set_bind_group(0, group, &[]);
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
}
/// The bind group layout of the draws' group 1 (block slots, slot
/// origins).
pub fn draw_layout(&self) -> &wgpu::BindGroupLayout {
&self.draw_layout
}
/// Draw `calls`; `page` binds what else a page's draws need (a Java
/// pack's terrain reads the page's vertices).
/// Draws `calls` with a flat pipeline set and `vertices` giving each
/// page's vertex buffer; `page` binds what else a page's draws need (a
/// Java pack's terrain reads the page's vertices).
pub fn draw<'a>(
&self,
pass: &mut wgpu::RenderPass<'_>,
@@ -483,16 +658,39 @@ impl Flat {
) {
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
for call in calls {
let table = self.pages[call.page as usize]
.as_ref()
.and_then(|t| t.group.as_ref())
.expect("prepared page");
pass.set_vertex_buffer(0, vertices(call.page).slice(..));
pass.set_bind_group(1, table, &[]);
self.bind_page(pass, call.page, &vertices);
page(pass, call.page);
pass.draw_indexed(call.first..call.first + call.count, 0, 0..1);
}
}
/// Draws phase 2's calls, as `flatten_phase2` left them.
pub fn draw_phase2<'a>(
&self,
pass: &mut wgpu::RenderPass<'_>,
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
) {
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
for (k, call) in self.calls[self.phase1_calls..self.solid_calls]
.iter()
.enumerate()
{
self.bind_page(pass, call.page, &vertices);
pass.draw_indexed_indirect(&self.phase2_calls, k as u64 * 20);
}
}
fn bind_page<'a>(
&self,
pass: &mut wgpu::RenderPass<'_>,
page: u32,
vertices: &impl Fn(u32) -> &'a wgpu::Buffer,
) {
let table = self.pages[page as usize]
.as_ref()
.and_then(|t| t.group.as_ref())
.expect("prepared page");
pass.set_vertex_buffer(0, vertices(page).slice(..));
pass.set_bind_group(1, table, &[]);
}
}
#[cfg(test)]
@@ -526,16 +724,22 @@ mod tests {
fn plan_draws_runs_of_a_page_in_order() {
let (draws, pages, solid) = sample();
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
let (solid_calls, total) = plan(
let Plan {
phase1_calls,
solid_calls,
total,
} = plan(
&draws,
&pages,
solid,
solid,
4,
&mut calls,
&mut ranges,
&mut segments,
);
assert_eq!(total, 6 * 13);
assert_eq!(phase1_calls, solid_calls);
let call = |page, first, count| Call { page, first, count };
// Pages 0, 0 | 1 | 0, then translucent 0, 0 (never merged with solid).
assert_eq!(
@@ -549,16 +753,65 @@ mod tests {
);
assert_eq!(solid_calls, 3);
// Solid ranges, then each sorted page's, every group padded to 4.
assert_eq!(segments, [(None, 0, 4), (Some(0), 4, 1), (Some(1), 8, 1)]);
assert_eq!(
segments,
[
(Source::Quads, 0, 4),
(Source::Sorted(0), 4, 1),
(Source::Sorted(1), 8, 1)
]
);
assert_eq!(ranges[3], [24, QUADS, 1024, 36]);
assert_eq!(ranges[4], [12, 6, 768, 60]);
assert_eq!(ranges[8], [6, 0, 40, 72]);
assert_eq!(ranges.len(), 12);
}
/// 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.
#[test]
fn plan_gives_phase_2_calls_of_its_own() {
let (draws, pages, solid) = sample();
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
let plan = plan(
&draws,
&pages,
2,
solid,
4,
&mut calls,
&mut ranges,
&mut segments,
);
assert_eq!(
plan,
Plan {
phase1_calls: 1,
solid_calls: 3,
total: 6 * 13
}
);
let call = |page, first, count| Call { page, first, count };
// Phase 1: page 0 | phase 2: page 1, page 0 | translucent: page 0.
assert_eq!(
calls,
[
call(0, 0, 30),
call(1, 30, 6),
call(0, 36, 24),
call(0, 60, 18)
]
);
assert_eq!(segments[1], (Source::Seen, 4, 2));
assert_eq!(ranges[4], [6, 0, 256, 0]);
assert_eq!(ranges[5], [24, 1, 1024, 1]);
}
/// The compute pass writes exactly the indices the per-section draws
/// read: quads 0 1 2 0 2 3 for solid draws, sorted indices otherwise,
/// plus the base vertex.
/// plus the base vertex. With culling, phase 2's runs hold the indices
/// of the draws the test saw, in order, and their calls count them.
#[test]
fn flatten_writes_the_indices_of_the_per_section_draws() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
@@ -574,101 +827,170 @@ mod tests {
use wgpu::util::DeviceExt;
let (draws, pages, solid) = sample();
let align = (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16).max(1);
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
let (_, total) = plan(
&draws,
&pages,
solid,
align,
&mut calls,
&mut ranges,
&mut segments,
);
let sorted: [Vec<u32>; 2] = [
(0..32).map(|i| (i * 7) % 32).collect(),
(0..8).rev().collect(),
];
let mut expected = Vec::new();
for (d, (_, page)) in draws.iter().zip(&pages) {
for k in 0..d[0] {
let i = match page {
None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize],
Some(p) => sorted[*p as usize][(d[2] + k) as usize],
};
expected.push(d[3] + i);
}
}
let storage = |entries: &[u32]| {
let indices = |d: &[u32; 5], sorted_page: Option<u32>| -> Vec<u32> {
(0..d[0])
.map(|k| {
d[3] + match sorted_page {
None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize],
Some(p) => sorted[p as usize][(d[2] + k) as usize],
}
})
.collect()
};
let storage = |entries: &[u32], usage| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(entries),
usage: wgpu::BufferUsages::STORAGE,
usage: wgpu::BufferUsages::STORAGE | usage,
})
};
let range_buffer = storage(bytemuck::cast_slice(&ranges));
let sorted_buffers = [storage(&sorted[0]), storage(&sorted[1]), storage(&[0; 4])];
let out = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: total * 4,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: total * 4,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let none = wgpu::BufferUsages::empty();
let sorted_buffers = [
storage(&sorted[0], none),
storage(&sorted[1], none),
storage(&[0; 4], none),
];
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: None,
module: &module,
entry_point: Some("flatten"),
compilation_options: Default::default(),
cache: None,
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
for &(source, first, count) in &segments {
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &range_buffer,
offset: first * 16,
size: wgpu::BufferSize::new(count * 16),
}),
},
wgpu::BindGroupEntry {
binding: 1,
resource: sorted_buffers[source.map_or(2, |p| p as usize)]
.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: out.as_entire_binding(),
},
],
});
pass.set_bind_group(0, &group, &[]);
pass.dispatch_workgroups(count as u32, 1, 1);
let pipeline = |entry| {
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: None,
module: &module,
entry_point: Some(entry),
compilation_options: Default::default(),
cache: None,
})
};
let (flatten, flatten_seen) = (pipeline("flatten"), pipeline("flatten_seen"));
let read_back = |buffer: &wgpu::Buffer, words: u64| -> Vec<u32> {
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: words * 4,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(buffer, 0, &read, 0, words * 4);
queue.submit([encoder.finish()]);
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec()
};
// Without culling, then with the third and fourth draws in phase 2,
// of which the test saw only the fourth.
for phase1 in [solid, 2] {
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
let plan = plan(
&draws,
&pages,
phase1,
solid,
align,
&mut calls,
&mut ranges,
&mut segments,
);
// Phase 2's draws as the test leaves them: instance counts of 0,
// 1 where it saw the section.
let mut phase2: Vec<[u32; 5]> = draws[phase1..solid]
.iter()
.map(|&[count, _, first, base, instance]| [count, 0, first, base, instance])
.collect();
if let Some(last) = phase2.last_mut() {
last[1] = 1;
}
let phase2_calls: Vec<[u32; 5]> = calls[plan.phase1_calls..plan.solid_calls]
.iter()
.map(|c| [0, 1, c.first, 0, 0])
.collect();
let range_buffer = storage(bytemuck::cast_slice(&ranges), none);
let phase2_buffer = storage(
bytemuck::cast_slice(&[phase2.as_slice(), &[[0; 5]]].concat()),
none,
);
let calls_buffer = storage(
bytemuck::cast_slice(&[phase2_calls.as_slice(), &[[0; 5]]].concat()),
wgpu::BufferUsages::COPY_SRC,
);
let out = storage(&vec![0; plan.total as usize], wgpu::BufferUsages::COPY_SRC);
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
for &(source, first, count) in &segments {
let ranges = wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &range_buffer,
offset: first * 16,
size: wgpu::BufferSize::new(count * 16),
});
let entry = |binding, resource| wgpu::BindGroupEntry { binding, resource };
let (pipeline, entries) = match source {
Source::Seen => (
&flatten_seen,
vec![
entry(0, ranges),
entry(2, out.as_entire_binding()),
entry(3, phase2_buffer.as_entire_binding()),
entry(4, calls_buffer.as_entire_binding()),
],
),
Source::Quads | Source::Sorted(_) => {
let page = match source {
Source::Sorted(p) => p as usize,
_ => 2,
};
(
&flatten,
vec![
entry(0, ranges),
entry(1, sorted_buffers[page].as_entire_binding()),
entry(2, out.as_entire_binding()),
],
)
}
};
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &entries,
});
pass.set_pipeline(pipeline);
pass.set_bind_group(0, &group, &[]);
pass.dispatch_workgroups(count as u32, 1, 1);
}
}
queue.submit([encoder.finish()]);
let got = read_back(&out, plan.total);
// Phase 1's and the translucent calls: each of their draws, in order.
let expected: Vec<u32> = (0..draws.len())
.filter(|i| !(phase1..solid).contains(i))
.flat_map(|i| indices(&draws[i], pages[i].1))
.collect();
let drawn: Vec<u32> = calls
.iter()
.enumerate()
.filter(|(c, _)| !(plan.phase1_calls..plan.solid_calls).contains(c))
.flat_map(|(_, c)| got[c.first as usize..(c.first + c.count) as usize].to_vec())
.collect();
assert_eq!(drawn, expected);
// Phase 2: page 1's run drew nothing; page 0's holds the fourth
// draw's indices.
if phase1 < solid {
let counts = read_back(&calls_buffer, phase2_calls.len() as u64 * 5);
assert_eq!(counts[0], 0);
assert_eq!(counts[5], draws[3][0]);
let run = &calls[plan.phase1_calls + 1];
assert_eq!(
got[run.first as usize..(run.first + draws[3][0]) as usize],
indices(&draws[3], None)
);
}
}
encoder.copy_buffer_to_buffer(&out, 0, &read, 0, total * 4);
queue.submit([encoder.finish()]);
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let got: Vec<u32> =
bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec();
assert_eq!(got, expected);
}
}
+44 -3
View File
@@ -4,9 +4,11 @@
// translucent ones read their sorted indices.
struct Range {
count: u32,
// First sorted index, or QUADS for a solid draw.
// First sorted index, or QUADS for a solid draw (`flatten_seen`: its
// entry in occlusion culling's phase 2 draws).
first: u32,
base: u32,
// First index in the list (`flatten_seen`: its draw call).
dst: u32,
}
const QUADS: u32 = 0xffffffffu;
@@ -14,6 +16,13 @@ const GROUP: u32 = 64u;
@group(0) @binding(0) var<storage, read> ranges: array<Range>;
@group(0) @binding(1) var<storage, read> sorted: array<u32>;
@group(0) @binding(2) var<storage, read_write> out: array<u32>;
// Index `k` of a solid draw: quad k / 6's vertices 0 1 2 0 2 3.
fn quad(k: u32) -> u32 {
let c = k % 6u;
return (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u);
}
@compute @workgroup_size(64)
fn flatten(@builtin(workgroup_id) group: vec3<u32>,
@builtin(local_invocation_index) lane: u32) {
@@ -25,11 +34,43 @@ fn flatten(@builtin(workgroup_id) group: vec3<u32>,
for (var k = lane; k < d.count; k += GROUP) {
var i: u32;
if d.first == QUADS {
let c = k % 6u;
i = (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u);
i = quad(k);
} else {
i = sorted[d.first + k];
}
out[d.dst + k] = d.base + i;
}
}
// Occlusion culling's phase 2 (gfx/cull.rs), after its test: the draws as
// the test left them (`DrawIndexedIndirectArgs`, the instance count 1 where
// it saw the section), and phase 2's draw calls, whose index counts start
// at 0. A draw the test saw takes the next indices of its call's run.
@group(0) @binding(3) var<storage, read> draws: array<u32>;
@group(0) @binding(4) var<storage, read_write> calls: array<atomic<u32>>;
const UNSEEN: u32 = 0xffffffffu;
var<workgroup> start: u32;
@compute @workgroup_size(64)
fn flatten_seen(@builtin(workgroup_id) group: vec3<u32>,
@builtin(local_invocation_index) lane: u32) {
let r = group.y * 65535u + group.x;
if r >= arrayLength(&ranges) {
return;
}
let d = ranges[r];
if lane == 0u {
var s = UNSEEN;
if draws[d.first * 5u + 1u] != 0u {
s = atomicLoad(&calls[d.dst * 5u + 2u]) + atomicAdd(&calls[d.dst * 5u], d.count);
}
start = s;
}
let s = workgroupUniformLoad(&start);
if s == UNSEEN {
return;
}
for (var k = lane; k < d.count; k += GROUP) {
out[s + k] = d.base + quad(k);
}
}
+168 -115
View File
@@ -2,11 +2,13 @@
//! Iris's colour targets (`colortex0..`, each with a main and an alternate
//! side) and the pack's `begin`, `prepare`, `deferred`, `composite` and
//! `final` programs as full-screen passes over them, as Iris's
//! `CompositeRenderer` runs them. Horizon's world enters `colortex0` and
//! `depthtex0..2` after `prepare`, where Iris's gbuffers programs would have
//! drawn, and the last picture goes to `world_post`. The targets keep GL's
//! layout (row 0 at the bottom, which the translated vertex programs
//! produce), so the world is flipped going in and the picture coming out.
//! `CompositeRenderer` runs them. Horizon's world enters the target the
//! pack's terrain program draws to (`colortex0` for most packs) and
//! `depthtex0` after `prepare`, where Iris's gbuffers programs would have
//! drawn (`depthtex1`/`depthtex2`: its depth before translucent geometry),
//! and the last picture goes to `world_post`. The targets keep GL's layout
//! (row 0 at the bottom, which the translated vertex programs produce), so
//! the world is flipped going in and the picture coming out.
//!
//! When the pack has terrain programs (`gfx/java_terrain.rs`), Horizon's
//! world comes without its terrain: the pack's `gbuffers_terrain` draws it
@@ -14,8 +16,9 @@
//! `gbuffers_water` draws the translucent terrain after `deferred`, as in
//! Iris. `depthtex1` and `depthtex2` then hold the depth before it.
use super::java_terrain::{Atlas, JavaWorld, TerrainPipelines};
use super::pack_stages::FrameUniform;
use crate::java_pack::{JavaFolder, JavaPasses};
use super::pack_stages::{FrameUniform, noise, rgba_view};
use crate::java_pack::{JavaFolder, JavaPasses, NOISE_KEY, blend_state, pass_blends, texture_key};
use crate::shader_pack::Rgba;
use glam::{Mat3, Mat4, Vec3, Vec4};
use horizon_shaderpack::pipeline::GeometryProgram;
use horizon_shaderpack::pipeline::TargetSettings;
@@ -35,14 +38,13 @@ pub struct JavaFrame {
pub moon_angle: f32,
}
/// Iris's `noisetex` size (`noiseTextureResolution`'s default).
const NOISE_SIZE: u32 = 256;
/// The vertex buffers a pass may read (wgpu's default limit).
const MAX_ATTRIBUTES: usize = 8;
pub(super) const BLIT: &str = r#"
@group(0) @binding(0) var color: texture_2d<f32>;
@group(0) @binding(1) var depth: texture_depth_2d;
@group(0) @binding(2) var opaque_depth: texture_depth_2d;
@vertex
fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
@@ -53,14 +55,19 @@ fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
struct World {
@location(0) color: vec4f,
@location(1) depth: vec4f,
@location(2) opaque_depth: vec4f,
}
// The world's colour and depth, upside down into GL's layout; Horizon's
// reversed depth (near 1) as GL's (near 0).
// The world's colour, depth and pre-translucent depth, upside down into GL's
// layout; Horizon's reversed depth (near 1) as GL's (near 0).
fn world_texel(p: vec4f) -> World {
let size = textureDimensions(depth);
let xy = vec2u(u32(p.x), size.y - 1u - u32(p.y));
return World(textureLoad(color, xy, 0), vec4f(1.0 - textureLoad(depth, xy, 0)));
return World(
textureLoad(color, xy, 0),
vec4f(1.0 - textureLoad(depth, xy, 0)),
vec4f(1.0 - textureLoad(opaque_depth, xy, 0)),
);
}
@fragment
@@ -71,6 +78,7 @@ fn world_in(@builtin(position) p: vec4f) -> World {
struct WorldDepth {
@location(0) color: vec4f,
@location(1) depth: vec4f,
@location(2) opaque_depth: vec4f,
@builtin(frag_depth) test: f32,
}
@@ -79,7 +87,7 @@ struct WorldDepth {
@fragment
fn world_in_depth(@builtin(position) p: vec4f) -> WorldDepth {
let world = world_texel(p);
return WorldDepth(world.color, world.depth, world.depth.x);
return WorldDepth(world.color, world.depth, world.opaque_depth, world.depth.x);
}
struct Depths {
@@ -184,10 +192,11 @@ struct Target {
#[derive(Clone, Copy, Debug, PartialEq)]
enum Source {
Target(u32),
/// `depthtex0`: the world's depth.
/// `depthtex0` / `gdepthtex`: the world's depth (including translucent water).
Depth,
/// `depthtex1` and `depthtex2`: the depth before translucent terrain
/// (the world's depth when the pack doesn't draw the terrain).
/// `depthtex1` / `depthtex2`: the depth before translucent terrain: after
/// the pack's own solid terrain when it draws it, else Horizon's world's
/// before translucent water.
DepthSolid,
Noise,
/// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow);
@@ -221,6 +230,7 @@ fn source(name: &str, geometry: bool) -> Source {
/// A sampler of a pass: its texture and sampler bindings.
struct SamplerBinding {
name: String,
source: Source,
dimension: wgpu::TextureViewDimension,
/// `isampler` (true) or `usampler` (false).
@@ -295,6 +305,7 @@ struct Common {
repeat: wgpu::Sampler,
compare: wgpu::Sampler,
noise: wgpu::TextureView,
custom_textures: BTreeMap<String, wgpu::TextureView>,
/// Full-screen triangle data per attribute kind (see `PassGpu::attributes`).
vertices: [wgpu::Buffer; 4],
world_layout: wgpu::BindGroupLayout,
@@ -308,6 +319,8 @@ struct Common {
struct Bound {
folder: usize,
size: [u32; 2],
/// `world_post`'s targets it binds (`Post::generation`).
post_generation: u64,
targets: BTreeMap<u32, Target>,
depth: wgpu::TextureView,
/// `depthtex1`: `depth` before translucent terrain, or `depth` itself.
@@ -316,7 +329,8 @@ struct Bound {
groups: Vec<wgpu::BindGroup>,
geometry: Option<BoundGeometry>,
world_in: (wgpu::RenderPipeline, wgpu::BindGroup),
/// The world goes to colortex0's alternate side.
/// The world's target, and whether the world goes to its alternate side.
world_target: u32,
world_alt: bool,
final_target: Option<wgpu::TextureView>,
present: (wgpu::RenderPipeline, wgpu::BindGroup),
@@ -344,6 +358,7 @@ struct BoundGeometry {
struct Folder {
targets: Vec<TargetSettings>,
world_at: usize,
world_target: u32,
flipped_after_prepare: BTreeSet<u32>,
flipped_at_end: BTreeSet<u32>,
passes: Vec<PassGpu>,
@@ -354,6 +369,9 @@ struct Folder {
pub struct JavaStages {
pub id: String,
/// A pass samples `depthtex1`/`depthtex2`: the world's depth is kept
/// before translucent geometry draws.
pub reads_opaque_depth: bool,
format: wgpu::TextureFormat,
common: Common,
folders: Vec<Folder>,
@@ -371,6 +389,9 @@ pub struct JavaStages {
atlas: Option<Atlas>,
/// The device has 16-bit normalized formats ([`target_format`]).
norm16: bool,
/// `wetness`: `rainStrength` smoothed with `wetnessHalflife` going up
/// and `drynessHalflife` going down.
wetness_smooth: SmoothFloat,
}
impl JavaStages {
@@ -386,7 +407,7 @@ impl JavaStages {
layouts: &GeometryLayouts,
norm16: bool,
) -> Result<Self, String> {
let common = Common::new(device, queue);
let common = Common::new(device, queue, &pack.custom_textures);
let folder_for = [-1, 0, 1].map(|d| pack.folder_for(d));
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let folders = pack
@@ -411,6 +432,7 @@ impl JavaStages {
Ok::<_, String>(Folder {
targets: plan.targets.clone(),
world_at: plan.world_at,
world_target: plan.world_target,
flipped_after_prepare: plan.flipped_after_prepare.clone(),
flipped_at_end: plan.flipped_at_end.clone(),
passes,
@@ -423,8 +445,14 @@ impl JavaStages {
if let Some(error) = pollster::block_on(scope.pop()) {
return Err(error.to_string());
}
let reads_opaque_depth = folders
.iter()
.flat_map(|f| f.passes.iter().chain(&f.final_pass))
.flat_map(|p| &p.samplers)
.any(|s| s.source == Source::DepthSolid);
Ok(Self {
id: id.to_owned(),
reads_opaque_depth,
format,
common,
folders,
@@ -439,6 +467,7 @@ impl JavaStages {
eye_smooth: [SmoothFloat::default(); 2],
atlas: None,
norm16,
wetness_smooth: SmoothFloat::default(),
})
}
@@ -481,7 +510,10 @@ impl JavaStages {
self.bound = None;
}
if self.bound.as_ref().is_none_or(|b| {
b.folder != folder || b.size != size || b.geometry.is_some() != terrain.is_some()
b.folder != folder
|| b.size != size
|| b.post_generation != post.generation()
|| b.geometry.is_some() != terrain.is_some()
}) {
self.bound = Some(self.bind(device, queue, folder, color, depth, size, post, terrain));
}
@@ -505,6 +537,12 @@ impl JavaStages {
for (i, smooth) in self.eye_smooth.iter_mut().enumerate() {
inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time);
}
inputs.wetness = self.wetness_smooth.update(
frame.weather[0],
directives.wetness_half_life,
directives.dryness_half_life,
frame_time,
);
self.uniforms
.update(&mut self.uniform_state, frame_time, &|name| {
inputs.builtin(name)
@@ -613,8 +651,9 @@ impl JavaStages {
let geometry_passes = geometry
.into_iter()
.flat_map(|g| std::iter::once(&g.terrain).chain(&g.water));
// Every target a pass reads or writes, and colortex0 (the world).
let mut used: BTreeSet<u32> = [0].into();
// Every target a pass reads or writes, colortex0 (shown without
// `final`) and the world's.
let mut used: BTreeSet<u32> = [0, folder.world_target].into();
for pass in all.clone().chain(geometry_passes) {
used.extend(pass.draw_buffers.iter().copied());
used.extend(pass.samplers.iter().filter_map(|s| match s.source {
@@ -692,16 +731,15 @@ impl JavaStages {
size,
)
.create_view(&Default::default());
let depth_solid = match geometry {
Some(_) => texture(
"Java shader pack depth before translucent terrain",
wgpu::TextureFormat::R32Float,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
size,
)
.create_view(&Default::default()),
None => depth.clone(),
};
// Written by `world_in` (Horizon's depth before translucent water),
// then by the pack's solid terrain when it draws it.
let depth_solid = texture(
"Java shader pack depth before translucent terrain",
wgpu::TextureFormat::R32Float,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
size,
)
.create_view(&Default::default());
let views = Views {
depth: &depth,
depth_solid: &depth_solid,
@@ -741,7 +779,7 @@ impl JavaStages {
&self.common,
&self.common.world_layout,
"world_in_depth",
&[targets[&0].format, r32],
&[targets[&folder.world_target].format, r32, r32],
true,
),
out_both: blit_pipeline(
@@ -765,14 +803,18 @@ impl JavaStages {
}
});
// The world goes into colortex0's side the gbuffers would write.
let colortex0 = &targets[&0];
// The world goes into its target's side the gbuffers would write.
let world_target = &targets[&folder.world_target];
let world_pipeline = blit_pipeline(
device,
&self.common,
&self.common.world_layout,
"world_in",
&[colortex0.format, wgpu::TextureFormat::R32Float],
&[
world_target.format,
wgpu::TextureFormat::R32Float,
wgpu::TextureFormat::R32Float,
],
false,
);
let world_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
@@ -787,6 +829,10 @@ impl JavaStages {
binding: 1,
resource: wgpu::BindingResource::TextureView(world_depth),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(post.opaque_depth()),
},
],
});
@@ -800,6 +846,7 @@ impl JavaStages {
.create_view(&Default::default())
});
// Without `final`, Iris shows colortex0 as the last pass left it.
let colortex0 = &targets[&0];
let shown = final_target.clone().unwrap_or_else(|| {
if plan.flipped_at_end.contains(&0) {
colortex0.alt_view.clone()
@@ -834,13 +881,15 @@ impl JavaStages {
Bound {
folder: folder_index,
size,
post_generation: post.generation(),
targets,
depth,
depth_solid,
groups,
geometry,
world_in: (world_pipeline, world_group),
world_alt: plan.flipped_after_prepare.contains(&0),
world_target: folder.world_target,
world_alt: plan.flipped_after_prepare.contains(&folder.world_target),
final_target,
present: (present_pipeline, present_group),
output_view,
@@ -899,15 +948,16 @@ fn folder_geometry(
}
fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) {
let colortex0 = &bound.targets[&0];
let target = &bound.targets[&bound.world_target];
let side = if bound.world_alt {
&colortex0.alt_view
&target.alt_view
} else {
&colortex0.main_view
&target.main_view
};
let attachments = [
Some(color_attachment(side, None)),
Some(color_attachment(&bound.depth, None)),
Some(color_attachment(&bound.depth_solid, None)),
];
let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Java shader pack world"),
@@ -1023,7 +1073,8 @@ fn blit_pipeline(
}
impl Common {
fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
/// `custom` holds the pack's `texture.*` images (`JavaPasses::custom_textures`).
fn new(device: &wgpu::Device, queue: &wgpu::Queue, custom: &BTreeMap<String, Rgba>) -> Self {
let sampler = |filter, address, compare| {
device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Java shader pack"),
@@ -1037,40 +1088,15 @@ impl Common {
})
};
use wgpu::{AddressMode::*, FilterMode::*};
// Iris's noise: random RGB, opaque.
let mut seed = 0x2545_f491_u32;
let noise_bytes: Vec<u8> = (0..NOISE_SIZE * NOISE_SIZE * 4)
.map(|i| {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
if i % 4 == 3 { 255 } else { (seed >> 24) as u8 }
})
let noise = match custom.get(NOISE_KEY) {
Some(image) => rgba_view(device, queue, "noisetex", image),
None => rgba_view(device, queue, "noisetex", &noise()),
};
let custom_textures = custom
.iter()
.filter(|(key, _)| *key != NOISE_KEY)
.map(|(key, image)| (key.clone(), rgba_view(device, queue, key, image)))
.collect();
let noise = device.create_texture(&wgpu::TextureDescriptor {
label: Some("noisetex"),
size: wgpu::Extent3d {
width: NOISE_SIZE,
height: NOISE_SIZE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
noise.as_image_copy(),
&noise_bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(NOISE_SIZE * 4),
rows_per_image: None,
},
noise.size(),
);
// The full-screen triangle (0, 0), (2, 0), (0, 2): the pack's
// projection maps 0..1 to the screen. Texture coordinates are the
// position; colours white; normals up.
@@ -1117,13 +1143,15 @@ impl Common {
nearest: sampler(Nearest, ClampToEdge, None),
repeat: sampler(Linear, Repeat, None),
compare: sampler(Linear, ClampToEdge, Some(wgpu::CompareFunction::LessEqual)),
noise: noise.create_view(&Default::default()),
noise,
custom_textures,
vertices,
world_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Java shader pack world"),
entries: &[
texture_entry(0, unfilterable),
texture_entry(1, wgpu::TextureSampleType::Depth),
texture_entry(2, wgpu::TextureSampleType::Depth),
],
}),
present_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -1213,6 +1241,7 @@ impl PassGpu {
.cloned()
.unwrap_or_else(|| format!("{sampler}_s"));
samplers.push(SamplerBinding {
name: sampler.clone(),
source: source(sampler, setup.is_some()),
dimension,
signed,
@@ -1354,10 +1383,11 @@ impl PassGpu {
// Output location `l` writes target `draw_buffers[l]` (or the screen).
let outputs = &program.fragment.interface.outputs;
let blends = pass_blends(&program.pass, &program.draw_buffers, None);
let target_states: Vec<Option<wgpu::ColorTargetState>> = match screen {
Some(format) => vec![Some(wgpu::ColorTargetState {
format,
blend: None,
blend: program.pass.blend.as_ref().and_then(blend_state),
write_mask: if outputs.contains_key(&0) {
wgpu::ColorWrites::ALL
} else {
@@ -1369,12 +1399,18 @@ impl PassGpu {
.iter()
.enumerate()
.map(|(l, &i)| {
let format = formats
.get(i as usize)
.copied()
.unwrap_or(wgpu::TextureFormat::Rgba8Unorm);
// Only filterable float/unorm formats support blending.
let can_blend = matches!(
sample_type(format),
wgpu::TextureSampleType::Float { filterable: true }
);
Some(wgpu::ColorTargetState {
format: formats
.get(i as usize)
.copied()
.unwrap_or(wgpu::TextureFormat::Rgba8Unorm),
blend: None,
format,
blend: blends[l].filter(|_| can_blend),
write_mask: if outputs.contains_key(&(l as u32)) {
wgpu::ColorWrites::ALL
} else {
@@ -1599,44 +1635,57 @@ impl PassGpu {
let depth = textures.depth;
let mut views = Vec::new();
for s in &self.samplers {
let view = match (s.compare, s.source) {
(true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth),
(false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => {
match targets.get(&i) {
Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(),
Some(t) => t.main_view.clone(),
None => blank_view(device, queue, blank, s, BlankKind::Color(false)),
let custom = (!s.compare && s.dimension == wgpu::TextureViewDimension::D2)
.then(|| {
common
.custom_textures
.get(&texture_key(&self.program, &s.name))
})
.flatten();
let view = if let Some(custom) = custom {
custom.clone()
} else {
match (s.compare, s.source) {
(true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth),
(false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => {
match targets.get(&i) {
Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(),
Some(t) => t.main_view.clone(),
None => blank_view(device, queue, blank, s, BlankKind::Color(false)),
}
}
}
(false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => {
depth.clone()
}
(false, Source::DepthSolid) if s.dimension == wgpu::TextureViewDimension::D2 => {
textures.depth_solid.clone()
}
(false, Source::Atlas) if s.dimension == wgpu::TextureViewDimension::D2 => {
match textures.atlas {
Some(v) => v.clone(),
None => blank_view(device, queue, blank, s, BlankKind::Color(true)),
(false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => {
depth.clone()
}
}
(false, Source::Lightmap) if s.dimension == wgpu::TextureViewDimension::D2 => {
match textures.lightmap {
Some(v) => v.clone(),
None => blank_view(device, queue, blank, s, BlankKind::Color(true)),
(false, Source::DepthSolid)
if s.dimension == wgpu::TextureViewDimension::D2 =>
{
textures.depth_solid.clone()
}
(false, Source::Atlas) if s.dimension == wgpu::TextureViewDimension::D2 => {
match textures.atlas {
Some(v) => v.clone(),
None => blank_view(device, queue, blank, s, BlankKind::Color(true)),
}
}
(false, Source::Lightmap) if s.dimension == wgpu::TextureViewDimension::D2 => {
match textures.lightmap {
Some(v) => v.clone(),
None => blank_view(device, queue, blank, s, BlankKind::Color(true)),
}
}
(false, Source::FlatNormal) => {
blank_view(device, queue, blank, s, BlankKind::FlatNormal)
}
(false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far),
(false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => {
common.noise.clone()
}
(false, Source::Blank(white)) => {
blank_view(device, queue, blank, s, BlankKind::Color(white))
}
_ => blank_view(device, queue, blank, s, BlankKind::Color(false)),
}
(false, Source::FlatNormal) => {
blank_view(device, queue, blank, s, BlankKind::FlatNormal)
}
(false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far),
(false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => {
common.noise.clone()
}
(false, Source::Blank(white)) => {
blank_view(device, queue, blank, s, BlankKind::Color(white))
}
_ => blank_view(device, queue, blank, s, BlankKind::Color(false)),
};
let sampler = match (s.compare, s.source) {
_ if s.shared.is_some() => match s.shared.as_deref() {
@@ -2051,6 +2100,8 @@ struct Inputs {
/// `eyeBrightness` and `eyeBrightnessSmooth`: block, sky light × 16.
eye: [f32; 2],
eye_smooth: [f32; 2],
/// `wetness` (`JavaStages::wetness_smooth`).
wetness: f32,
/// `CelestialUniforms`, in view space.
sun_position: Vec3,
moon_position: Vec3,
@@ -2110,6 +2161,7 @@ impl Inputs {
frame: *frame,
eye: [0.0; 2],
eye_smooth: [0.0; 2],
wetness: frame.weather[0],
sun_position: Vec3::ZERO,
moon_position: Vec3::ZERO,
up_position: Vec3::ZERO,
@@ -2242,7 +2294,8 @@ impl Inputs {
}),
"upPosition" => vec3(self.up_position),
"moonPhase" => vec![f.moon[3]],
"rainStrength" | "wetness" => vec![f.weather[0]],
"rainStrength" => vec![f.weather[0]],
"wetness" => vec![self.wetness],
"thunderStrength" => vec![f.weather[1]],
"fogColor" => f.fog_color[..3].to_vec(),
"skyColor" => f.sky_color[..3].to_vec(),
+211
View File
@@ -0,0 +1,211 @@
//! Seeded, bolt-local lightning meshes retained until their last active bolt disappears.
use crate::{gfx::upload::Uploads, mesher::Vertex};
use glam::DVec3;
use horizon_core::random::{LegacyRandom, RandomSource};
use std::collections::HashMap;
use wgpu::util::DeviceExt;
/// A bolt's render state. Simulation lifetime and flashes stay in the game.
#[derive(Clone, Copy)]
pub struct Bolt {
pub at: [f64; 3],
pub seed: i64,
}
#[derive(Default)]
pub struct Input<'a> {
pub bolts: &'a [Bolt],
/// Current atlas white texel; a changed rect invalidates retained vertices.
pub uv: [f32; 2],
}
// Four layers, fourteen segments (eight trunk, two branches of three), four quads.
pub(super) const QUADS: u32 = 4 * 14 * 4;
/// `LightningBoltRenderer.submit`: keep random draws, layers and quad order unchanged.
fn geometry(seed: i64, uv: [f32; 2]) -> Vec<Vertex> {
let mut out = Vec::with_capacity(QUADS as usize * 4);
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
let mut random = LegacyRandom::new(seed);
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
let (mut x_off, mut z_off) = (0f32, 0f32);
for i in (0..8).rev() {
xs[i] = x_off;
zs[i] = z_off;
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
}
for layer in 0..4 {
let mut random = LegacyRandom::new(seed);
for branch in 0..3 {
let trunk = branch == 0;
let start = 7 - branch;
let end = if trunk { 0 } else { start - 3 + 1 };
let mut sx = xs[start] - x_off;
let mut sz = zs[start] - z_off;
for segment in (end..=start).rev() {
let (ex, ez) = (sx, sz);
let spread = if trunk { 11 } else { 31 };
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
let mut top = 0.1 + layer as f32 * 0.2;
let mut bottom = top;
if trunk {
top *= segment as f32 * 0.1 + 1.0;
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
}
for (rx, rz, lx, lz) in [
(false, false, true, false),
(true, false, true, true),
(true, true, false, true),
(false, true, false, false),
] {
let s = |p: bool, r: f32| if p { r } else { -r };
let y0 = segment as f32 * 16.0;
let corners = [
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
];
for c in corners {
out.push(Vertex {
normal: [0; 4],
pos: c,
uv,
layer: 2,
color,
light: 240 | 240 << 8,
});
}
}
}
}
}
out
}
struct Cached<T> {
mesh: T,
used: bool,
}
/// Shared seeds use the same mesh; storage is bounded by active unique seeds,
/// including after seed changes, removals, dimension switches and disconnects.
struct Cache<T> {
uv: Option<[f32; 2]>,
meshes: HashMap<i64, Cached<T>>,
}
impl<T> Cache<T> {
fn new() -> Self {
Self {
uv: None,
meshes: HashMap::new(),
}
}
fn prepare(&mut self, input: &Input<'_>, mut build: impl FnMut(i64, [f32; 2]) -> T) {
if self.uv != Some(input.uv) {
self.meshes.clear();
self.uv = Some(input.uv);
}
for cached in self.meshes.values_mut() {
cached.used = false;
}
for bolt in input.bolts {
self.meshes
.entry(bolt.seed)
.or_insert_with(|| Cached {
mesh: build(bolt.seed, input.uv),
used: true,
})
.used = true;
}
self.meshes.retain(|_, cached| cached.used);
// HashMap::retain keeps its allocation. Release historical peak capacity
// as well as meshes once the storm (or connection) is gone.
if self.meshes.is_empty() {
self.meshes = HashMap::new();
} else if self.meshes.capacity() > self.meshes.len() * 4 {
self.meshes.shrink_to_fit();
}
}
}
fn offset(bolt: &Bolt, camera: DVec3) -> [f32; 3] {
(DVec3::from_array(bolt.at) - camera).as_vec3().to_array()
}
pub(super) struct Renderer {
cache: Cache<wgpu::Buffer>,
instances: Option<wgpu::Buffer>,
capacity: usize,
}
impl Renderer {
pub(super) fn new() -> Self {
Self {
cache: Cache::new(),
instances: None,
capacity: 0,
}
}
pub(super) fn prepare(
&mut self,
device: &wgpu::Device,
uploads: &mut Uploads,
encoder: &mut wgpu::CommandEncoder,
input: &Input<'_>,
camera: DVec3,
) {
self.cache.prepare(input, |seed, uv| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Lightning vertices"),
contents: bytemuck::cast_slice(&geometry(seed, uv)),
usage: wgpu::BufferUsages::VERTEX,
})
});
if input.bolts.is_empty() {
self.instances = None;
self.capacity = 0;
return;
}
if input.bolts.len() > self.capacity || input.bolts.len() < self.capacity / 4 {
self.capacity = input.bolts.len().next_power_of_two();
self.instances = Some(device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Lightning offsets"),
size: (self.capacity * std::mem::size_of::<[f32; 3]>()) as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}));
}
let offsets: Vec<_> = input
.bolts
.iter()
.map(|bolt| offset(bolt, camera))
.collect();
uploads.buffer(
encoder,
self.instances.as_ref().unwrap(),
0,
bytemuck::cast_slice(&offsets),
);
}
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, input: &Input<'_>) {
let Some(instances) = &self.instances else {
return;
};
pass.set_vertex_buffer(1, instances.slice(..));
// Follow simulation order, including repeated seeds; HashMap order must
// never change additive accumulation or the order before dragon rays.
for (i, bolt) in input.bolts.iter().enumerate() {
pass.set_vertex_buffer(0, self.cache.meshes[&bolt.seed].mesh.slice(..));
pass.draw_indexed(0..QUADS * 6, 0, i as u32..i as u32 + 1);
}
}
}
#[cfg(test)]
mod tests;

Some files were not shown because too many files have changed in this diff Show More