Merge main and preserve tick chunk membership invalidation

This commit is contained in:
rdbtCVS
2026-10-15 11:29:05 +01:00
221 changed files with 30674 additions and 1464 deletions
+8
View File
@@ -0,0 +1,8 @@
# Docker builds (the relay) need the Rust sources only.
target/
.local/
**/node_modules/
website/
benchmarks/
packs/
mods/
+1 -1
View File
@@ -54,7 +54,7 @@ jobs:
(github.event.pull_request.head.repo.full_name == github.repository && github.event.action != 'labeled') ||
(github.event.action == 'labeled' && github.event.label.name == 'run-parity'))
runs-on: [self-hosted, horizon-game]
timeout-minutes: 45
timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini
steps:
- uses: actions/checkout@v4
with:
+34
View File
@@ -0,0 +1,34 @@
name: telemetry-server
# The ingest server is its own workspace (crates/horizon-telemetry-server), so the checks job doesn't build
# it: this one does, when it or the crate it shares with the launcher and the game changes.
on:
push:
branches: [main]
paths:
- 'crates/horizon-telemetry/**'
- 'crates/horizon-telemetry-server/**'
- '.github/workflows/telemetry-server.yml'
pull_request:
paths:
- 'crates/horizon-telemetry/**'
- 'crates/horizon-telemetry-server/**'
- '.github/workflows/telemetry-server.yml'
permissions:
contents: read
jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 20
defaults:
run:
working-directory: crates/horizon-telemetry-server
steps:
- uses: actions/checkout@v4
- run: rustup toolchain install stable --profile minimal --component rustfmt --component clippy
- uses: Swatinem/rust-cache@v2
with:
workspaces: crates/horizon-telemetry-server
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo +stable fmt --check
- run: cargo +stable clippy --all-targets --locked -- -D warnings
- run: cargo +stable test --locked
Generated
+238
View File
@@ -24,6 +24,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aead"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
dependencies = [
"crypto-common",
"generic-array",
]
[[package]]
name = "ahash"
version = "0.8.12"
@@ -322,6 +332,30 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
]
[[package]]
name = "chacha20poly1305"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
dependencies = [
"aead",
"chacha20",
"cipher",
"poly1305",
"zeroize",
]
[[package]]
name = "chrono"
version = "0.4.45"
@@ -333,6 +367,17 @@ dependencies = [
"windows-link",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -493,6 +538,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"rand_core",
"typenum",
]
@@ -502,6 +548,32 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"fiat-crypto",
"rand_core",
"rustc_version",
"subtle",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "dasp_sample"
version = "0.11.0"
@@ -527,6 +599,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -631,6 +704,12 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "fiat-crypto"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
@@ -886,6 +965,24 @@ version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
[[package]]
name = "hkdf"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "horizon-assets"
version = "0.1.0"
@@ -896,6 +993,14 @@ dependencies = [
"serde_json",
]
[[package]]
name = "horizon-bench"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "horizon-client"
version = "0.1.0"
@@ -909,8 +1014,11 @@ dependencies = [
"gilrs",
"glam",
"horizon-assets",
"horizon-bench",
"horizon-core",
"horizon-friends",
"horizon-protocol",
"horizon-telemetry",
"horizon-theme",
"horizon-world",
"log",
@@ -918,7 +1026,9 @@ dependencies = [
"naga",
"png",
"pollster",
"serde",
"serde_json",
"sha2",
"symphonia",
"ureq",
"wgpu",
@@ -934,6 +1044,21 @@ dependencies = [
"libm",
]
[[package]]
name = "horizon-friends"
version = "0.1.0"
dependencies = [
"chacha20poly1305",
"getrandom 0.3.4",
"hkdf",
"if-addrs",
"serde",
"serde_json",
"sha2",
"socket2",
"spake2",
]
[[package]]
name = "horizon-prepare"
version = "0.1.0"
@@ -955,6 +1080,26 @@ dependencies = [
"sha1",
]
[[package]]
name = "horizon-relay"
version = "0.1.0"
dependencies = [
"getrandom 0.3.4",
"horizon-friends",
"serde_json",
]
[[package]]
name = "horizon-telemetry"
version = "0.1.0"
dependencies = [
"getrandom 0.3.4",
"ruzstd",
"serde",
"serde_json",
"ureq",
]
[[package]]
name = "horizon-theme"
version = "0.1.0"
@@ -1099,6 +1244,16 @@ dependencies = [
"icu_properties",
]
[[package]]
name = "if-addrs"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
dependencies = [
"libc",
"windows-sys 0.59.0",
]
[[package]]
name = "indexmap"
version = "2.14.2"
@@ -1129,6 +1284,15 @@ dependencies = [
"libc",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -1857,6 +2021,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "opaque-debug"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "orbclient"
version = "0.3.55"
@@ -2006,6 +2176,17 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
[[package]]
name = "poly1305"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
dependencies = [
"cpufeatures",
"opaque-debug",
"universal-hash",
]
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -2090,6 +2271,15 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -2266,6 +2456,15 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ruzstd"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5"
dependencies = [
"twox-hash",
]
[[package]]
name = "same-file"
version = "1.0.6"
@@ -2313,6 +2512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
@@ -2453,6 +2653,28 @@ dependencies = [
"serde",
]
[[package]]
name = "socket2"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
dependencies = [
"libc",
"windows-sys 0.52.0",
]
[[package]]
name = "spake2"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5482afe85a0b6ce956c945401598dbc527593c77ba51d0a87a586938b1b893a"
dependencies = [
"curve25519-dalek",
"hkdf",
"rand_core",
"sha2",
]
[[package]]
name = "spirv"
version = "0.4.0+sdk-1.4.341.0"
@@ -2758,6 +2980,12 @@ version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
[[package]]
name = "twox-hash"
version = "2.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
[[package]]
name = "typenum"
version = "1.20.1"
@@ -2782,6 +3010,16 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "universal-hash"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
dependencies = [
"crypto-common",
"subtle",
]
[[package]]
name = "untrusted"
version = "0.9.0"
+2 -2
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher"]
members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "xtask"]
exclude = ["launcher", "crates/horizon-telemetry-server"]
members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "xtask"]
resolver = "2"
[workspace.package]
@@ -0,0 +1,78 @@
# Entity model document loading
The three startup batches (boats/chest boats, minecarts, armor stands/player armor)
now share one parsed document. For this fixture, that replaces 43 full document
reads/parses (boat discovery plus 42 selected layers) with one. Selected models
still produce independent `Part` trees; the document is dropped after the batches
are built. Other entity loaders retain their existing behavior.
## Reproduce
From the repository root:
```sh
python3 benchmarks/entity-model-document-2026-10-14/generate_fixture.py /tmp/horizon-entity-model-document-fixture.json
ENTITY_MODEL_BENCH_DOCUMENT=/tmp/horizon-entity-model-document-fixture.json \
CARGO_TARGET_DIR=/home/bob/Documents/horizon/target \
cargo test -p horizon-client --profile fast --bin horizon-client \
entity_model_document_benchmark -- --ignored --nocapture
```
`CARGO_TARGET_DIR` is optional and can be changed for another machine. Supply a
prepared `entity-models.json` through `ENTITY_MODEL_BENCH_DOCUMENT` to benchmark
that document instead; the harness copies only that file to a temporary root.
`ENTITY_MODEL_BENCH_REPETITIONS` controls repetitions (default 15).
The opt-in Rust test calls the actual three optimized production loaders and
compares every selected part name, pose, polygon normal/vertex and child against
the previous algorithm using the compatible per-model `load_model` API. Timings
include reading, parsing, constructing, normalizing into a common result map, and
dropping the result. Each variant gets three warmups and 15 measured calls, with
order alternating. `black_box` consumes inputs/results. No other builds or
optimization benchmarks ran during the measured calls.
## Input and limitations
Prepared resources were unavailable in the repository and local Horizon asset
directories. This is a **synthetic** 2,473,695-byte document with 458 model layers,
each containing 12 posed parts with six exported quads and normals. It selects 22
boat/chest-boat layers, six minecart layers and 14 armor/player layers (42 total).
One wood name is synthetic (`test_wood`); boat discovery accepts arbitrary wood
names. The extra layers model the cost of parsing a full production-size document
for each selected model.
File data is warm in the OS page cache. Equipment files are absent, so equipment
texture loading is excluded. This measures the entity-model batch only and does
not establish overall startup, frame time or FPS improvement. Shapes/layer counts
in real prepared documents can produce different absolute timings.
Machine: AMD Ryzen 5 5600X (6 cores / 12 threads), Linux x86_64,
Rust 1.99.0 (b940084d7, LLVM 23.1.1), Cargo `fast` profile (opt-level 3,
16 codegen units, no LTO). Baseline algorithm corresponds to main
`73a019967e9665c6b96332988c13cb66679d8477`.
## Results
| Variant | Median batch time | Full document reads/parses |
| --- | ---: | ---: |
| Previous per-model algorithm | 1,434.974 ms | 43 |
| Shared document | 33.420 ms | 1 |
The measured batch is **42.94× faster** on this synthetic input. All 15 samples
for both variants, warmup count, document size and selected model count are in
[`results.json`](results.json).
## Validation
```sh
cargo fmt --all -- --check
CARGO_TARGET_DIR=/home/bob/Documents/horizon/target \
cargo test -p horizon-client --profile fast --bin horizon-client \
entity_model_loading_tests -- --nocapture
CARGO_TARGET_DIR=/home/bob/Documents/horizon/target \
cargo clippy -p horizon-client --profile fast --lib --bin horizon-client --tests -- -D warnings
```
The regular tests cover full/sparse documents, unrelated layers, a missing file,
invalid JSON, non-object JSON, missing model keys, independent model trees, and
equipment loading when the document is unavailable.
@@ -0,0 +1,31 @@
"""Generate a production-size synthetic document; no prepared assets required."""
import json
import pathlib
import sys
woods = "oak spruce birch jungle acacia dark_oak mangrove cherry bamboo pale_oak test_wood".split()
carts = "minecart chest_minecart hopper_minecart furnace_minecart tnt_minecart command_block_minecart".split()
keys = [f"minecraft:{prefix}/{wood}#main" for prefix in ("boat", "chest_boat") for wood in woods]
keys += [f"minecraft:{cart}#main" for cart in carts]
keys += [f"minecraft:{model}#{slot}" for model in ("player", "armor_stand", "armor_stand_small")
for slot in ("helmet", "chestplate", "leggings", "boots")]
keys += [f"minecraft:{model}#main" for model in ("armor_stand", "armor_stand_small")]
face = [[0, 0, 0, 0, 0], [16, 0, 0, 1, 0], [16, 16, 0, 1, 1], [0, 16, 0, 0, 1]]
part = {"pose": [1, 2, 3, 0.25, -0.5, 0.75, 1, 1, 1], "polygons": [face] * 6,
"normals": [[0, 0, 1]] * 6}
model = {"pose": [0, 0, 0, 0, 0, 0, 1, 1, 1],
"children": {f"part_{i}": part for i in range(12)}}
encoded = json.dumps(model, separators=(",", ":"))
entries = [json.dumps(key) + ":" + encoded for key in keys]
size = 2 + sum(map(len, entries)) + len(entries) - 1
index = 0
while size < 2_470_000:
entry = json.dumps(f"minecraft:fixture_{index}#main") + ":" + encoded
entries.append(entry)
size += 1 + len(entry)
index += 1
output = pathlib.Path(sys.argv[1])
output.write_text("{" + ",".join(entries) + "}")
print(json.dumps({"path": str(output), "bytes": output.stat().st_size,
"layers": len(entries), "selected_layers": len(keys)}))
@@ -0,0 +1,43 @@
{
"baseline_median_ms": 1434.973835,
"baseline_ms": [
1400.008286,
1406.761694,
1408.9131360000001,
1418.6680549999999,
1419.149658,
1427.082872,
1433.088092,
1434.973835,
1449.7688150000001,
1452.143883,
1453.987998,
1455.518231,
1457.0334540000001,
1458.588552,
1485.34133
],
"document_bytes": 2473695,
"optimized_median_ms": 33.419768000000005,
"optimized_ms": [
32.64795,
32.812732,
33.054488,
33.056914,
33.102999000000004,
33.23532,
33.28287,
33.419768000000005,
33.610569,
33.874749,
33.915657,
33.93877,
34.009893999999996,
34.550526,
36.096408000000004
],
"repetitions": 15,
"selected_models": 42,
"speedup": 42.937875421516985,
"warmup_pairs": 3
}
@@ -0,0 +1,69 @@
# Reuse parsed model states
`models::prepare` parsed `model-states.json` to select blocks, then
`StateModels::load` reopened and parsed the same document for binding and baking.
`StateModels::from_facts` now borrows the first parsed map. The public `load`
entry point still reads, parses and validates its own document. Both paths retain
the `fs::read` + `serde_json::from_slice` strategy merged in PR #205.
The shared map uses `BTreeMap`, preserving the original catalog loader's JSON
validation, including rejection of top-level `null`. The old selection map was
`serde_json::Map`, also backed by a BTreeMap with the project's current features.
Catalog binding, model selection and baking are unchanged. Preparation no longer
holds a second complete JSON tree while constructing the catalog; no persistent
cache or extra clones were added.
## Measurement
The committed `model_states_bench` example runs main's two-parse sequence after PR #205
(first a serde JSON map, then `StateModels::load`) and the new one-parse sequence
(first a BTreeMap, then `StateModels::from_facts`). Both select blocks from the
same generated document with slice parsing and call the actual catalog binding/baking code. Timing
includes file reads, parsing, filtering, binding, baking and result destruction.
Fixture generation and equality checks run outside the timed region.
Prepared Minecraft resources were unavailable locally, so this is a synthetic
2,836,696-byte document containing 843 block schemas and 53,952 states. Schemas
combine integer and named properties. Blockstate resources use weighted and
conditional multipart choices with rotations and UV locking, sharing one model
with a baked face. Its absent texture uses the normal missing-sprite fallback.
Both paths read identical files with a warm OS cache. The workload does not
represent the full diversity of production model and texture assets.
On AMD Ryzen 5 5600X, Linux 7.2.8-zen1-2-zen x86_64, rustc 1.99.0
(b940084d7 2026-09-28), Cargo `fast` profile, serial execution:
| Path | Median (15 samples) |
| --- | ---: |
| Before: parse twice, with #205 slice readers | 96.080 ms |
| After: reuse first parse, with #205 slice readers | 73.585 ms |
**1.306x speedup; 23.41% less elapsed time** for this loading segment after PR #205. Each path
has two warmups, sample order alternates, and inputs/results use `black_box`.
This excludes gallery placements, GPU work and overall application startup.
These measurements supersede the original unbuffered-reader timings
(2732.004 ms → 1386.060 ms, 1.971x) after rebasing onto main at
`e96e1571`. The reviewer measured approximately 1.05x with real prepared resources;
the generated fixture's balance of parsing and binding differs from production.
The change still removes one complete document read, parse and JSON tree.
Equality validation compares every state's selected variants and baked geometry
at three positions, plus sprite layers and opacity/translucency flags. The
focused test also checks matching schema/registry errors, malformed/missing
source files, rejection of `null`, and successful shared-facts loading after the
source file has been deleted.
## Reproduce
```sh
export CARGO_TARGET_DIR=/home/bob/Documents/horizon/target
export CARGO_INCREMENTAL=0
cargo run -p horizon-client --profile fast --example model_states_bench -- 15
cargo test -p horizon-client --profile fast --example model_states_bench
cargo clippy -p horizon-client --all-targets --profile fast -- -D warnings
cargo fmt --all -- --check
```
The target directory can be changed for another machine. The example creates and
removes its fixtures in the system temporary directory.
@@ -0,0 +1,54 @@
{
"date": "2026-10-15",
"environment": "Linux x86_64/ext4/NVMe, Ryzen5 5600X, Rust1.99.0, Cargo fast",
"scope": "actual resource_root vs original wrapper/builder; warmed storage; output equivalence outside timing",
"warmups": 2,
"median_samples": 11,
"prepared_minecraft": "26.3",
"prepared_schema": 7,
"prepared_manifest_sha256": "fd03c686302748748e132ef3978b7b0bcf42024257e802985a5cc7175cc74298",
"packs": [
{
"project": "faithful-32x",
"version": "lDYpMiqk",
"version_name": "[26.3] Faithful 32x \u2013 September 2026 Release",
"publisher_page": "https://modrinth.com/resourcepack/faithful-32x/version/lDYpMiqk",
"download_url": "https://cdn.modrinth.com/data/w0TnApzs/versions/lDYpMiqk/Faithful%2032x%20-%2026.3.zip",
"zip_bytes": 13116019,
"zip_sha512": "e90ec63af7f239dbb99aa20c98b23d830e76898f65d3e31b7f0b53bb36db12dcd8c38d6930c743237c9c3db7bf708423fa1d1b2fd497dd6c281dbe216b779db9",
"asset_files": 5063,
"assets_uncompressed_bytes": 12524266,
"original_ms": 159.827,
"cold_ms": 162.711,
"hit_ms": 0.707
},
{
"project": "default-hd-128x",
"version": "rErHu3BE",
"version_name": "Default HD 128x Demo/Alpha 1.8.2.7",
"publisher_page": "https://modrinth.com/resourcepack/default-hd-128x/version/rErHu3BE",
"download_url": "https://cdn.modrinth.com/data/orfTV6nk/versions/rErHu3BE/Default%20HD%20128x%20Demo%201.8.2.7.zip",
"zip_bytes": 16876419,
"zip_sha512": "f5f9606e92b986cd9c8b8e5ff2bb52db720cc7b38e013355bdc90089e01975a08d09750ef2fd727f753d88ec3fbcd067355179b490587f667b2995f8be81640f",
"asset_files": 2318,
"assets_uncompressed_bytes": 17315416,
"original_ms": 111.501,
"cold_ms": 114.386,
"hit_ms": 0.31
},
{
"project": "fpbr",
"version": "dynf82xk",
"version_name": "support 1.21.9 and newer",
"publisher_page": "https://modrinth.com/resourcepack/fpbr/version/dynf82xk",
"download_url": "https://cdn.modrinth.com/data/nvEpbd8t/versions/dynf82xk/FPBR-Main-1.21.9-R1.3.zip",
"zip_bytes": 46737770,
"zip_sha512": "64f1bbd036e205118f1d9c49a79558db2c1356ee988fb939c0023db1967d78e1bd05047f341ce6d65355717ba7ddb1330af57edbb4d5b8713c96ae62987274c5",
"asset_files": 7001,
"assets_uncompressed_bytes": 56356903,
"original_ms": 347.639,
"cold_ms": 348.012,
"hit_ms": 0.448
}
]
}
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "horizon-bench"
version = "0.1.0"
edition = "2021"
license = "MIT"
description = "The benchmark report format (docs/benchmark-report.md), shared by the game, the launcher and the upload"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+259
View File
@@ -0,0 +1,259 @@
//! The machine a report was measured on. CPU, RAM and OS are detected here; the GPU and the display
//! come from the program that rendered (the game knows its adapter, the launcher its window).
use std::process::Command;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Hardware {
/// `macos`, `linux`, `windows`.
pub os: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub os_version: Option<String>,
pub arch: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu_threads: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ram_mb: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gpu: Option<Gpu>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<Display>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Gpu {
pub name: String,
pub vendor: String,
pub driver: String,
/// `metal`, `vulkan`, `dx12`, `gl`.
pub backend: String,
/// `integrated`, `discrete`, `virtual`, `cpu`, `other`.
pub kind: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Display {
/// Physical pixels.
pub width: u32,
pub height: u32,
pub scale: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_hz: Option<u32>,
}
impl Hardware {
pub fn detect() -> Hardware {
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()),
ram_mb: ram_bytes().map(|b| b >> 20),
gpu: None,
display: None,
}
}
}
/// The one-minute load average: above about the number of threads the machine was busy.
pub fn load_average() -> Option<f64> {
if cfg!(target_os = "macos") {
// "{ 1.23 1.10 1.00 }"
output("sysctl", &["-n", "vm.loadavg"])?
.trim_start_matches('{')
.split_whitespace()
.next()?
.parse()
.ok()
} else {
std::fs::read_to_string("/proc/loadavg")
.ok()?
.split_whitespace()
.next()?
.parse()
.ok()
}
}
/// `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
}
/// Resident memory of a process, in bytes (macOS, Linux).
pub fn rss_bytes(pid: u32) -> Option<u64> {
if cfg!(target_os = "macos") {
return output("ps", &["-o", "rss=", "-p", &pid.to_string()])?
.parse::<u64>()
.ok()
.map(|kb| kb * 1024);
}
let status = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
let line = status.lines().find(|l| l.starts_with("VmRSS:"))?;
line.split_whitespace()
.nth(1)?
.parse::<u64>()
.ok()
.map(|kb| kb * 1024)
}
/// CPU time a process has used, user and system, in seconds (macOS, Linux).
pub fn cpu_seconds(pid: u32) -> Option<f64> {
if cfg!(target_os = "macos") {
// "[[dd-]hh:]mm:ss.cc"
let time = output("ps", &["-o", "time=", "-p", &pid.to_string()])?;
let (rest, days) = match time.split_once('-') {
Some((d, rest)) => (rest.to_owned(), d.parse::<f64>().ok()?),
None => (time, 0.0),
};
let seconds = rest.split(':').try_fold(0.0, |acc, part| {
part.parse::<f64>().ok().map(|v| acc * 60.0 + v)
})?;
return Some(days * 86_400.0 + seconds);
}
// utime and stime, fields 14 and 15, in clock ticks (100 per second on Linux).
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let fields: Vec<&str> = stat.rsplit_once(')')?.1.split_whitespace().collect();
let ticks: f64 = fields.get(11)?.parse::<f64>().ok()? + fields.get(12)?.parse::<f64>().ok()?;
Some(ticks / 100.0)
}
fn output(program: &str, args: &[&str]) -> Option<String> {
let out = Command::new(program).args(args).output().ok()?;
let text = String::from_utf8(out.stdout).ok()?.trim().to_owned();
(out.status.success() && !text.is_empty()).then_some(text)
}
#[cfg(target_os = "macos")]
fn os_version() -> Option<String> {
output("sw_vers", &["-productVersion"])
}
#[cfg(target_os = "macos")]
fn cpu() -> Option<String> {
output("sysctl", &["-n", "machdep.cpu.brand_string"])
}
#[cfg(target_os = "macos")]
fn ram_bytes() -> Option<u64> {
output("sysctl", &["-n", "hw.memsize"])?.parse().ok()
}
#[cfg(target_os = "linux")]
fn os_version() -> Option<String> {
let release = std::fs::read_to_string("/etc/os-release").ok()?;
let name = key_value(&release, "PRETTY_NAME", '=')?
.trim_matches('"')
.to_owned();
Some(match output("uname", &["-r"]) {
Some(kernel) => format!("{name} (kernel {kernel})"),
None => name,
})
}
#[cfg(target_os = "linux")]
fn cpu() -> Option<String> {
let info = std::fs::read_to_string("/proc/cpuinfo").ok()?;
// x86 names the CPU per core; ARM boards name the machine once.
key_value(&info, "model name", ':')
.or_else(|| key_value(&info, "Model", ':'))
.map(str::to_owned)
}
#[cfg(target_os = "linux")]
fn ram_bytes() -> Option<u64> {
let info = std::fs::read_to_string("/proc/meminfo").ok()?;
let kb = key_value(&info, "MemTotal", ':')?
.trim_end_matches("kB")
.trim();
kb.parse::<u64>().ok().map(|kb| kb * 1024)
}
#[cfg(target_os = "linux")]
fn key_value<'a>(text: &'a str, key: &str, sep: char) -> Option<&'a str> {
text.lines().find_map(|line| {
let (k, v) = line.split_once(sep)?;
(k.trim() == key).then(|| v.trim())
})
}
#[cfg(target_os = "windows")]
fn os_version() -> Option<String> {
output("cmd", &["/C", "ver"])
}
#[cfg(target_os = "windows")]
fn cpu() -> Option<String> {
std::env::var("PROCESSOR_IDENTIFIER").ok()
}
#[cfg(target_os = "windows")]
fn ram_bytes() -> Option<u64> {
let out = output(
"powershell",
&[
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory",
],
)?;
out.parse().ok()
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn os_version() -> Option<String> {
None
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn cpu() -> Option<String> {
None
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn ram_bytes() -> Option<u64> {
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_this_machine() {
let hw = Hardware::detect();
assert_eq!(hw.os, std::env::consts::OS);
assert!(hw.cpu_threads.unwrap() >= 1);
if cfg!(any(target_os = "macos", target_os = "linux")) {
assert!(hw.cpu.is_some(), "{hw:?}");
assert!(hw.ram_mb.unwrap() > 256, "{hw:?}");
assert!(hw.os_version.is_some(), "{hw:?}");
assert!(load_average().is_some());
assert!(rss_bytes(std::process::id()).unwrap() > 1 << 20);
assert!(cpu_seconds(std::process::id()).unwrap() >= 0.0);
}
}
}
+457
View File
@@ -0,0 +1,457 @@
//! The benchmark report format, version 1 (docs/benchmark-report.md).
//!
//! One JSON file per run, the same for the game, the launcher and `tools/perf_bench.py`: the local log
//! a player can attach, and, with consent, what the telemetry upload sends ([`Report::for_upload`]).
//! It holds summaries and fixed-edge histogram counts, never raw frame streams.
use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
mod hardware;
pub use hardware::{cpu_seconds, load_average, power_source, rss_bytes, Display, Gpu, Hardware};
pub const FORMAT: &str = "horizon-benchmark-report";
pub const VERSION: u32 = 1;
/// Lower edges of the frame-time histogram buckets, in milliseconds; the last bucket is 1000 ms and
/// over. Fixed by the format version so histograms from any number of reports add up.
pub const HISTOGRAM_EDGES_MS: [f64; 24] = [
0.0, 1.0, 2.0, 3.0, 4.17, 5.0, 6.0, 7.0, 8.33, 10.0, 12.0, 14.0, 16.67, 20.0, 25.0, 33.33,
40.0, 50.0, 66.67, 100.0, 150.0, 250.0, 500.0, 1000.0,
];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
Game,
Launcher,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct App {
pub name: String,
pub version: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub commit: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mods: Vec<Mod>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Mod {
pub name: String,
pub version: String,
}
/// What has to match for two reports to be compared. Every field is optional.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Conditions {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scenario: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seed: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub render_distance: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub simulation_distance: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub window: Option<[u32; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vsync: Option<bool>,
/// Absent: unlimited.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fps_cap: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub offscreen: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repeats: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub warmup_s: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub power: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub load_avg_1m: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<String>,
}
/// A measurement over a run's repeats.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Summary {
pub n: usize,
pub mean: f64,
/// Sample standard deviation; `None` for a single value.
pub stdev: Option<f64>,
pub min: f64,
pub max: f64,
/// Half-width of the 95% confidence interval of the mean (Student's t); `None` for a single value.
pub ci95: Option<f64>,
}
impl Summary {
/// `None` for no values.
pub fn of(values: &[f64]) -> Option<Summary> {
let n = values.len();
if n == 0 {
return None;
}
let mean = values.iter().sum::<f64>() / n as f64;
let (stdev, ci95) = if n > 1 {
let var = values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
let sd = var.sqrt();
(Some(sd), Some(t95(n - 1) * sd / (n as f64).sqrt()))
} else {
(None, None)
};
Some(Summary {
n,
mean: round(mean),
stdev: stdev.map(round),
min: round(values.iter().copied().fold(f64::INFINITY, f64::min)),
max: round(values.iter().copied().fold(f64::NEG_INFINITY, f64::max)),
ci95: ci95.map(round),
})
}
}
/// Two-sided 95% critical value of Student's t for `df` degrees of freedom.
fn t95(df: usize) -> f64 {
const TABLE: [f64; 30] = [
12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160,
2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056,
2.052, 2.048, 2.045, 2.042,
];
TABLE.get(df.wrapping_sub(1)).copied().unwrap_or(1.96)
}
/// One measured phase of one repeat.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Frames {
pub phase: String,
pub repeat: u32,
pub frames: usize,
pub seconds: f64,
pub avg_fps: f64,
pub low_1pct_fps: f64,
pub low_01pct_fps: f64,
pub p50_ms: f64,
pub p95_ms: f64,
pub p99_ms: f64,
pub p999_ms: f64,
pub max_ms: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu_p50_ms: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gpu_p50_ms: Option<f64>,
/// Frame counts per bucket of [`HISTOGRAM_EDGES_MS`].
pub histogram: Vec<u64>,
}
impl Frames {
/// The figures of a phase from its frame times in milliseconds (time between the starts of
/// consecutive frames); `None` for no frames. CPU and GPU times are per frame too, when measured.
pub fn of(
phase: &str,
repeat: u32,
frame_ms: &[f32],
cpu_ms: &[f32],
gpu_ms: &[f32],
) -> Option<Frames> {
let times = sorted(frame_ms);
let n = times.len();
if n == 0 {
return None;
}
let total: f64 = times.iter().sum();
// The average frame time of the slowest `share` of frames, as frames per second.
let low = |share: f64| {
let slowest = &times[n - ((n as f64 * share).ceil() as usize).max(1)..];
1000.0 * slowest.len() as f64 / slowest.iter().sum::<f64>()
};
let mut histogram = vec![0; HISTOGRAM_EDGES_MS.len()];
for &t in &times {
histogram[HISTOGRAM_EDGES_MS.partition_point(|&edge| edge <= t).max(1) - 1] += 1;
}
Some(Frames {
phase: phase.to_owned(),
repeat,
frames: n,
seconds: round(total / 1000.0),
avg_fps: round(n as f64 * 1000.0 / total),
low_1pct_fps: round(low(0.01)),
low_01pct_fps: round(low(0.001)),
p50_ms: round(percentile(&times, 0.5)),
p95_ms: round(percentile(&times, 0.95)),
p99_ms: round(percentile(&times, 0.99)),
p999_ms: round(percentile(&times, 0.999)),
max_ms: round(times[n - 1]),
cpu_p50_ms: (!cpu_ms.is_empty()).then(|| round(percentile(&sorted(cpu_ms), 0.5))),
gpu_p50_ms: (!gpu_ms.is_empty()).then(|| round(percentile(&sorted(gpu_ms), 0.5))),
histogram,
})
}
}
fn sorted(ms: &[f32]) -> Vec<f64> {
let mut v: Vec<f64> = ms
.iter()
.map(|&m| f64::from(m))
.filter(|m| m.is_finite())
.collect();
v.sort_by(f64::total_cmp);
v
}
/// Three decimals: plenty for milliseconds and FPS, short in JSON, and parsed back exactly.
fn round(v: f64) -> f64 {
(v * 1000.0).round() / 1000.0
}
/// Nearest-rank percentile of sorted, non-empty values.
fn percentile(sorted: &[f64], p: f64) -> f64 {
let n = sorted.len();
sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1]
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Report {
pub format: String,
pub version: u32,
pub kind: Kind,
/// When the run ended, UTC, `YYYY-MM-DDTHH:MM:SSZ`.
pub created: String,
pub app: App,
pub hardware: Hardware,
#[serde(default)]
pub conditions: Conditions,
/// Scalar measurements by name; the unit is the name's suffix (`_ms`, `_mb`...).
#[serde(default)]
pub metrics: BTreeMap<String, Summary>,
#[serde(default)]
pub frames: Vec<Frames>,
/// Local only: a name the person running it chose.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
/// Local only: logs the run wrote next to the report.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub local: Vec<PathBuf>,
}
impl Report {
/// An empty report for this machine, created now.
pub fn new(kind: Kind, app: App) -> Report {
Report {
format: FORMAT.to_owned(),
version: VERSION,
kind,
created: utc_now(),
app,
hardware: Hardware::detect(),
conditions: Conditions::default(),
metrics: BTreeMap::new(),
frames: Vec::new(),
label: None,
local: Vec::new(),
}
}
/// Records a measurement over the repeats; no values records nothing.
pub fn metric(&mut self, name: &str, values: &[f64]) {
if let Some(summary) = Summary::of(values) {
self.metrics.insert(name.to_owned(), summary);
}
}
/// Reads a report, rejecting other formats and newer versions.
pub fn parse(json: &str) -> Result<Report, String> {
let report: Report = serde_json::from_str(json).map_err(|e| e.to_string())?;
if report.format != FORMAT {
return Err(format!(
"not a benchmark report: format {:?}",
report.format
));
}
if report.version > VERSION {
return Err(format!(
"report version {} is newer than {VERSION}",
report.version
));
}
Ok(report)
}
/// The report without its local-only fields, dated to the day: what an upload sends.
pub fn for_upload(&self) -> Report {
let day = self.created.get(..10).unwrap_or_default();
Report {
label: None,
local: Vec::new(),
created: format!("{day}T00:00:00Z"),
..self.clone()
}
}
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).expect("a report always serializes")
}
/// Writes `<dir>/<kind>-<created>-<scenario>.json` and returns its path.
pub fn write_to(&self, dir: &Path) -> io::Result<PathBuf> {
std::fs::create_dir_all(dir)?;
let kind = match self.kind {
Kind::Game => "game",
Kind::Launcher => "launcher",
};
let stamp: String = self.created.chars().filter(char::is_ascii_digit).collect();
let scenario: String = self
.conditions
.scenario
.as_deref()
.unwrap_or("run")
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect();
let path = dir.join(format!("{kind}-{stamp}-{scenario}.json"));
std::fs::write(&path, self.to_json() + "\n")?;
Ok(path)
}
}
/// The current time, UTC, `YYYY-MM-DDTHH:MM:SSZ`.
pub fn utc_now() -> String {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
utc(secs)
}
fn utc(secs: u64) -> String {
let (days, rem) = (secs / 86_400, secs % 86_400);
// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
let z = days as i64 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
rem / 3600,
rem / 60 % 60,
rem % 60
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utc_dates() {
assert_eq!(utc(0), "1970-01-01T00:00:00Z");
assert_eq!(utc(951_782_400), "2000-02-29T00:00:00Z");
assert_eq!(utc(1_791_983_007), "2026-10-14T13:03:27Z");
}
#[test]
fn summary_of_repeats() {
assert_eq!(Summary::of(&[]), None);
let one = Summary::of(&[5.0]).unwrap();
assert_eq!((one.n, one.mean, one.stdev, one.ci95), (1, 5.0, None, None));
let s = Summary::of(&[2.0, 4.0, 6.0]).unwrap();
assert_eq!((s.mean, s.min, s.max), (4.0, 2.0, 6.0));
assert_eq!(s.stdev, Some(2.0));
assert_eq!(s.ci95, Some(4.969), "4.303 * 2 / sqrt(3)");
}
#[test]
fn frame_figures_and_histogram() {
// 998 frames of 2 ms, one of 20 ms, one of 1500 ms.
let mut ms = vec![2.0f32; 998];
ms.extend([20.0, 1500.0]);
let f = Frames::of("flight", 0, &ms, &[], &[]).unwrap();
assert_eq!(f.frames, 1000);
assert_eq!(f.seconds, 3.516);
assert_eq!((f.p50_ms, f.p999_ms, f.max_ms), (2.0, 20.0, 1500.0));
// Slowest 1% = 10 frames: 8 of 2 ms, 20 ms, 1500 ms.
assert_eq!(f.low_1pct_fps, 6.51, "1000 * 10 / 1536");
// Slowest 0.1% = the 1500 ms frame.
assert_eq!(f.low_01pct_fps, 0.667);
assert_eq!(f.histogram.len(), HISTOGRAM_EDGES_MS.len());
assert_eq!(f.histogram[2], 998, "2 ms falls in [2, 3)");
assert_eq!(f.histogram[13], 1, "20 ms falls in [20, 25)");
assert_eq!(f.histogram[23], 1, "1500 ms falls in [1000, inf)");
assert_eq!(f.histogram.iter().sum::<u64>(), 1000);
assert_eq!((f.cpu_p50_ms, f.gpu_p50_ms), (None, None));
assert_eq!(Frames::of("x", 0, &[], &[], &[]), None);
}
#[test]
fn round_trip_and_upload_strips_local_fields() {
let mut r = Report::new(
Kind::Game,
App {
name: "horizon-client".into(),
version: "0.1.0".into(),
..App::default()
},
);
r.conditions.scenario = Some("flight".into());
r.metric("startup.title_ms", &[800.0, 820.0]);
r.frames
.extend(Frames::of("village", 0, &[2.0, 3.0], &[1.0], &[]));
r.label = Some("my run".into());
r.local.push("/home/someone/logs/latest.log".into());
let back = Report::parse(&r.to_json()).unwrap();
assert_eq!(back, r);
r.created = "2026-10-15T14:03:27Z".into();
let upload = r.for_upload();
assert_eq!(upload.created, "2026-10-15T00:00:00Z", "the day only");
let upload = upload.to_json();
assert!(
!upload.contains("my run") && !upload.contains("someone"),
"{upload}"
);
}
#[test]
fn rejects_other_formats_and_newer_versions() {
let r = Report::new(Kind::Launcher, App::default());
let newer = r.to_json().replace("\"version\": 1", "\"version\": 2");
assert!(Report::parse(&newer).unwrap_err().contains("newer"));
let other = r.to_json().replace(FORMAT, "something-else");
assert!(Report::parse(&other).is_err());
}
#[test]
fn writes_into_a_folder() {
let dir = std::env::temp_dir().join(format!("horizon-bench-test-{}", std::process::id()));
let mut r = Report::new(Kind::Launcher, App::default());
r.created = "2026-10-15T14:03:27Z".into();
r.conditions.scenario = Some("cold start".into());
let path = r.write_to(&dir).unwrap();
assert_eq!(
path.file_name().unwrap(),
"launcher-20261015140327-cold_start.json"
);
assert_eq!(
Report::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(),
r
);
std::fs::remove_dir_all(dir).unwrap();
}
}
+6
View File
@@ -12,12 +12,15 @@ horizon-assets = { path = "../horizon-assets" }
horizon-core = { path = "../horizon-core" }
horizon-world = { path = "../horizon-world" }
horizon-protocol = { path = "../horizon-protocol" }
horizon-friends = { path = "../horizon-friends" }
wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] }
winit = "0.30.13"
pollster = "0.4"
bytemuck = { version = "1.24", features = ["derive"] }
glam = "0.30"
png = "0.18"
sha2 = "0.10.9"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1.0.151", features = ["raw_value"] }
cpal = "0.16"
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
@@ -27,6 +30,9 @@ log = "0.4"
chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] }
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
horizon-theme = { path = "../horizon-theme" }
# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
horizon-bench = { path = "../horizon-bench" }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
zip = { version = "2", default-features = false, features = ["deflate"] }
# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input).
@@ -262,7 +262,7 @@ fn main() -> Result<()> {
let a = arrow.arrow.as_ref().unwrap();
writeln!(
out,
"arrow {} {} {:08x} {:08x} {} {} {} {} {} {} {} {} {} {:016x} {:016x} {} {} {:016x}",
"arrow {} {} {:08x} {:08x} {} {} {} {} {} {} {} {} {} {:016x} {:016x} {} {} {:016x} {}",
bits(arrow.position),
bits(arrow.velocity),
arrow.pitch.to_bits(),
@@ -280,7 +280,8 @@ fn main() -> Result<()> {
a.fluids.fluid_height(&Tags, LAVA).to_bits(),
a.removed,
arrow.critical(),
a.fall_distance.to_bits()
a.fall_distance.to_bits(),
bits(arrow.previous)
)?;
writeln!(out, "events {}", events.join(" | "))?;
let a = arrow.arrow.as_ref().unwrap();
@@ -9,7 +9,7 @@ use horizon_client::{
biome::Biomes,
blocks::BlockFacts,
chunk::{Chunk, MIN_Y, SECTIONS},
light::{LightTables, light_chunk},
light::{LightTables, apply_lighting, light_chunk},
mesher::{MeshTables, Mesher},
models,
streaming::{ChunkGenerator, Proto},
@@ -105,7 +105,7 @@ fn main() -> Result<()> {
);
let mut chunks: Vec<Chunk> = chunks.iter().map(|c| (**c).clone()).collect();
for ((x, z), sections) in lit {
chunks[((z - 1) * inner + x - 1) as usize].sections = sections;
apply_lighting(&mut chunks[((z - 1) * inner + x - 1) as usize], sections);
}
let chunks: Vec<Arc<Chunk>> = chunks.into_iter().map(Arc::new).collect();
let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone();
@@ -9,7 +9,7 @@ use horizon_client::{
biome::Biomes,
blocks::BlockFacts,
chunk::{Chunk, MIN_Y, SECTIONS, index},
light::{LightTables, light_chunk},
light::{LightTables, apply_lighting, light_chunk},
save,
};
use horizon_core::position::ChunkPos;
@@ -101,7 +101,7 @@ fn main() -> horizon_client::Result<()> {
.unwrap_or((None, None));
let nib = |a: &Option<Vec<u8>>| a.as_ref().map(|a| (a[i >> 1] >> ((i & 1) * 4)) & 15);
let id = chunks[&(x, z)].get(wx & 15, wy, wz & 15);
let packed = lit[si].light(i);
let packed = lit[si].get(i);
println!(
"{wy}: {} horizon sky {} block {} vanilla sky {:?} block {:?}",
facts.states[id as usize].name,
@@ -157,7 +157,7 @@ fn main() -> horizon_client::Result<()> {
.map_or(15, |a| (a[(i & 255) >> 1] >> ((i & 1) * 4)) & 15),
};
let vb = nibble(&block, 0);
let packed = section.light(i);
let packed = section.get(i);
let (hs, hb) = (packed >> 4, packed & 15);
total += 1;
if hs != vs {
@@ -228,7 +228,7 @@ fn incremental(
std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1)))
});
let mut c = chunks[&(x, z)].clone();
c.sections = light_chunk(&region, tables, sky_light);
apply_lighting(&mut c, light_chunk(&region, tables, sky_light));
c.lit = true;
world.insert((x, z), Arc::new(c));
}
@@ -299,7 +299,7 @@ fn incremental(
let full = light_chunk(&region, tables, sky_light);
for (si, s) in full.iter().enumerate() {
for i in 0..4096 {
let (a, b) = (s.light(i), world[&(kx, kz)].sections[si].light(i));
let (a, b) = (s.get(i), world[&(kx, kz)].sections[si].light(i));
if a != b {
bad += 1;
if bad < 20 {
+218 -7
View File
@@ -5,13 +5,14 @@
//! usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT
use horizon_client::{
assets::Assets,
beehive::HiveHost,
biome::Biomes,
blocks::BlockFacts,
chunk::{Chunk, HEIGHT, MIN_Y},
collisions,
containers::{BlockEntity, CreakingHeart},
items::{ItemStack, Items},
light::{LightTables, light_chunk},
light::{LightTables, apply_lighting, light_chunk},
mobs::{
Damage, MobType, creaking,
creaking_heart::{self, HeartEvent, HeartHost},
@@ -27,7 +28,13 @@ use horizon_core::{
random::LegacyRandom,
};
use horizon_world::{chunk::BlockState, registry::BlockRegistry, registry::BlockStateId};
use std::{collections::BTreeMap, fmt::Write as _, fs, path::Path, sync::Arc};
use std::{
collections::{BTreeMap, HashMap},
fmt::Write as _,
fs,
path::Path,
sync::Arc,
};
struct MobSpec {
kind: String,
@@ -54,6 +61,8 @@ struct Scenario {
hearts: Vec<Vec<String>>,
/// `ServerLevel.isSpawningMonsters`.
spawning: bool,
/// The day time moves on with every tick.
daycycle: bool,
/// The player hits a mob for 1 at the start of a tick: (tick, mob index).
hurts: Vec<(i32, usize)>,
/// The player feeds an animal at the start of a tick (Animal.mobInteract):
@@ -85,6 +94,7 @@ fn parse(text: &str) -> Vec<Scenario> {
"thunder" => s.thunder = true,
"levelseed" => {}
"spawning" => s.spawning = true,
"daycycle" => s.daycycle = true,
_ => panic!("unknown scenario option {kv}"),
}
}
@@ -407,6 +417,65 @@ impl HeartHost for Host<'_> {
self.spawning
}
}
/// A scenario's beehives as `BeehiveBlockEntity.serverTick` sees the level:
/// the bees let out are newcomers seeded as the oracle seeds them.
struct ProbeHive<'a, 'w> {
w: &'a MobWorld<'w>,
random: &'a mut LegacyRandom,
types: &'a HashMap<String, Arc<MobType>>,
/// The index of the first newcomer of this tick.
first: usize,
added: &'a mut Vec<Mob>,
honey: &'a mut Vec<([i32; 3], i32)>,
events: &'a mut Vec<MobEvent>,
}
impl HiveHost for ProbeHive<'_, '_> {
fn random(&mut self) -> &mut LegacyRandom {
self.random
}
fn bees_stay_in_hive(&self, _at: [i32; 3]) -> bool {
horizon_client::mobs::bee::bees_stay_in_hive(self.w)
}
fn blocked(&self, at: [i32; 3]) -> bool {
!self.w.block_collision_boxes(at[0], at[1], at[2]).is_empty()
}
fn set_honey_level(&mut self, at: [i32; 3], level: i32) {
self.honey.push((at, level));
}
fn load(&mut self, tag: &horizon_world::nbt::Tag) -> Option<Mob> {
let index = self.first + self.added.len();
let mut m =
horizon_client::entity_nbt::mob_from_nbt(tag, self.types, 100_000 + index as u32)?;
if m.species() != Species::Bee {
return None;
}
m.random = LegacyRandom::new(spawn_seed(index));
horizon_client::mobs::bee::draw_cooldowns(&mut m);
Some(m)
}
fn add(&mut self, m: Mob) -> bool {
self.added.push(m);
true
}
fn sound(&mut self, name: &'static str, at: [f64; 3]) {
self.events.push(MobEvent::Sound(name, at, 1.0, 1.0));
}
}
/// The hive's honey level and front from its block state.
fn hive_state(registry: &BlockRegistry, world: &World, at: [i32; 3]) -> (Option<i32>, [i32; 2]) {
let props = registry
.state(world.block(at[0], at[1], at[2]))
.map(|s| s.properties.clone())
.unwrap_or_default();
let honey = props.get("honey_level").and_then(|v| v.parse().ok());
let facing = horizon_client::beehive::facing_step(props.get("facing").map(String::as_str));
(honey, facing)
}
fn is_hive(b: &[String]) -> bool {
b[0] == "block"
&& (b[4].starts_with("minecraft:beehive") || b[4].starts_with("minecraft:bee_nest"))
}
/// The heart's state, block entity and the level random, as the oracle
/// prints them.
fn print_heart(
@@ -470,7 +539,7 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool {
/// `player_down`: the scenario's player is no valid target (creative, or
/// killed this tick).
fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool) {
fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool, now: i64) {
let _ = write!(out, "{t} {i}");
if m.removed {
// Entity.RemovalReason: the end of the death animation, else a discard.
@@ -589,6 +658,21 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool) {
.map_or("-".into(), |p| format!("{},{},{}", p[0], p[1], p[2]));
let _ = write!(out, "\tcg {} {held} {opened}", m.extra.variant3);
}
if let Some(b) = horizon_client::mobs::bee::get(m) {
let anger = if b.anger_end > 0 {
b.anger_end - now
} else {
-1
};
let flower = b
.flower
.map_or("-".into(), |p| format!("{},{},{}", p[0], p[1], p[2]));
let _ = write!(
out,
"\tbee {} {anger} {} {} {flower}",
b.flags, b.ticks_without_nectar, b.flower_cooldown
);
}
out.push('\n');
}
@@ -687,6 +771,12 @@ fn main() -> horizon_client::Result<()> {
let motion = horizon_client::motion::MotionResources::load(root, &assets)?;
let data = MobData::load(root, &facts);
let types = MobTypes::load(root)?;
// The types a bee leaving its hive is loaded with (EntityType.loadEntityRecursive).
let arc_types: HashMap<String, Arc<MobType>> = types
.types
.iter()
.map(|(k, v)| (k.clone(), Arc::new(v.clone())))
.collect();
let biomes = Biomes::load(root)?;
let items = Items::load(root, registry, &facts)?;
let tables = LightTables::load(root, registry, &facts)?;
@@ -729,6 +819,11 @@ fn main() -> horizon_client::Result<()> {
let n = |i: usize| b[i].parse::<i32>().unwrap();
if b[0] == "block" || b[0] == "chest" {
world.set(n(1), n(2), n(3), state(registry, &b[4]))?;
if is_hive(b) {
world
.block_entities
.insert((n(1), n(2), n(3)), BlockEntity::Beehive(Box::default()));
}
if b[0] == "chest" {
// chest X Y Z STATE SLOTS: item*count or - per slot.
let mut slots = vec![None; 27];
@@ -779,7 +874,7 @@ fn main() -> horizon_client::Result<()> {
})
});
let mut c = (*world.chunks[&(x, z)]).clone();
c.sections = light_chunk(&region, &tables, true);
apply_lighting(&mut c, light_chunk(&region, &tables, true));
c.lit = true;
((x, z), c)
})
@@ -815,6 +910,7 @@ fn main() -> horizon_client::Result<()> {
&mut Vec::new(),
),
"inlove" => m.extra.in_love = 600,
"nectar" => horizon_client::mobs::bee::set_has_nectar(&mut m, true),
"tame" => m.extra.tame = true,
x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(),
x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(),
@@ -835,6 +931,10 @@ fn main() -> horizon_client::Result<()> {
}
}
m.random = LegacyRandom::new(spec.seed);
if m.species() == Species::Bee {
// The oracle draws the constructor's cooldowns again once seeded.
horizon_client::mobs::bee::draw_cooldowns(&mut m);
}
if horizon_client::mobs::monster_brain::has_brain(m.species()) {
// The oracle delays the sensors again with the seeded random
// and seeds RunOne's shuffles with the mob's seed.
@@ -902,7 +1002,7 @@ fn main() -> horizon_client::Result<()> {
// from it, and the scenarios feed neither.
let mut level_random = LegacyRandom::new(0);
for (i, m) in mobs.iter().enumerate() {
print(&mut out, 0, i, m, s.creative);
print(&mut out, 0, i, m, s.creative, world.game_time);
}
// The MobWorld every step sees, over a snapshot of the mobs.
macro_rules! mob_world {
@@ -917,7 +1017,7 @@ fn main() -> horizon_client::Result<()> {
data: &data,
player: player.clone(),
others: $snapshot,
daylight: (s.time.rem_euclid(24000)) < 12000,
daylight: (world.day_time.rem_euclid(24000)) < 12000,
game_time: world.game_time,
day_time: world.day_time,
raining: s.rain,
@@ -937,6 +1037,9 @@ fn main() -> horizon_client::Result<()> {
}
for t in 1..=s.ticks {
world.game_time += 1;
if s.daycycle {
world.day_time = s.time + i64::from(t);
}
let mut heart_events_later: Vec<HeartEvent> = Vec::new();
// Creaking.tick reads the heart's block entity.
for (at, h) in &hearts {
@@ -1102,6 +1205,41 @@ fn main() -> horizon_client::Result<()> {
_ => {}
}
}
// BeeEnterHiveGoal.start: BeehiveBlockEntity.addOccupant.
let entering: Vec<[i32; 3]> = events[from.min(events.len())..]
.iter()
.filter_map(|e| match e {
MobEvent::EnterHive { hive, .. } => Some(*hive),
_ => None,
})
.collect();
for at in entering {
let key = (at[0], at[1], at[2]);
let Some(BlockEntity::Beehive(mut hive)) = world.block_entities.remove(&key)
else {
continue;
};
let tag = horizon_client::entity_nbt::mob_to_nbt(&mobs[i], [0; 4], None);
let flower = horizon_client::mobs::bee::get(&mobs[i]).and_then(|b| b.flower);
let mut honey = Vec::new();
let stored = {
let w = mob_world!(&snapshot);
let mut host = ProbeHive {
w: &w,
random: &mut scratch,
types: &arc_types,
first: 0,
added: &mut Vec::new(),
honey: &mut honey,
events: &mut events,
};
hive.add_occupant(at, tag, flower, &mut host)
};
world.block_entities.insert(key, BlockEntity::Beehive(hive));
if stored {
mobs[i].removed = true;
}
}
// ServerLevel ticks entities one after another: the ones
// after this mob see it as it is now.
if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) {
@@ -1134,6 +1272,43 @@ fn main() -> horizon_client::Result<()> {
added.append(&mut host.added);
}
drop(w);
// Then the hives (BeehiveBlockEntity.serverTick).
let mut hive_keys: Vec<(i32, i32, i32)> = world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Beehive(_)))
.map(|(k, _)| *k)
.collect();
hive_keys.sort_unstable();
let mut honey = Vec::new();
for key in hive_keys {
let at = [key.0, key.1, key.2];
let (level, facing) = hive_state(registry, &world, at);
let Some(BlockEntity::Beehive(mut hive)) = world.block_entities.remove(&key) else {
continue;
};
{
let w = mob_world!(&snapshot);
let mut host = ProbeHive {
w: &w,
random: &mut scratch,
types: &arc_types,
first: mobs.len() + born.len(),
added: &mut added,
honey: &mut honey,
events: &mut events,
};
hive.server_tick(at, facing, level, &mut host);
}
world.block_entities.insert(key, BlockEntity::Beehive(hive));
}
for (at, level) in honey {
if let Some(mut st) = registry.state(world.block(at[0], at[1], at[2])).cloned() {
st.properties
.insert("honey_level".to_owned(), level.to_string());
world.set(at[0], at[1], at[2], registry.resolve(&st)?)?;
}
}
mobs.append(&mut born);
mobs.append(&mut added);
for e in &heart_events {
@@ -1152,7 +1327,14 @@ fn main() -> horizon_client::Result<()> {
.iter()
.any(|e| player_hurt(player.as_ref(), e) && player_damage(e) >= 20.0);
for (i, m) in mobs.iter().enumerate() {
print(&mut out, t, i, m, s.creative || player_killed);
print(
&mut out,
t,
i,
m,
s.creative || player_killed,
world.game_time,
);
}
for e in &events {
if let MobEvent::Sound(name, _, volume, pitch) = e {
@@ -1209,6 +1391,35 @@ fn main() -> horizon_client::Result<()> {
}
);
}
for b in s.blocks.iter().filter(|b| is_hive(b)) {
let n = |i: usize| b[i].parse::<i32>().unwrap();
let Some(BlockEntity::Beehive(hive)) =
world.block_entities.get(&(n(1), n(2), n(3)))
else {
continue;
};
let (level, _) = hive_state(registry, &world, [n(1), n(2), n(3)]);
let bees: Vec<String> = hive
.bees
.iter()
.map(|b| format!("{}/{}", b.ticks_in_hive, b.min_ticks_in_hive))
.collect();
let _ = writeln!(
out,
"{t} hive {},{},{} honey {} bees {} flower {}",
b[1],
b[2],
b[3],
level.unwrap_or(-1),
if bees.is_empty() {
"-".into()
} else {
bees.join(",")
},
hive.flower
.map_or("-".into(), |f| format!("{},{},{}", f[0], f[1], f[2]))
);
}
for line in traces {
let _ = writeln!(out, "{line}");
}
@@ -0,0 +1,291 @@
//! Compare the old two-parse loading path with catalog construction from shared facts.
//! Run: cargo run -p horizon-client --profile fast --example model_states_bench -- 15
use horizon_client::{Result, models::StateModels, sprites::Sprites};
use horizon_core::position::BlockPos;
use horizon_world::{
DATA_VERSION,
chunk::BlockState,
nbt::Tag,
registry::{BlockRegistry, BlockStateId},
};
use serde_json::{Value, json};
use std::{collections::BTreeMap, fs, hint::black_box, path::PathBuf, time::Instant};
struct Fixture {
root: PathBuf,
registry: BlockRegistry,
bytes: usize,
blocks: usize,
}
impl Fixture {
fn new(target_bytes: usize) -> Result<Self> {
let root =
std::env::temp_dir().join(format!("horizon-model-states-{}", std::process::id()));
fs::create_dir_all(root.join("assets/minecraft/blockstates"))?;
fs::create_dir_all(root.join("assets/minecraft/models/block"))?;
let mut possible = Vec::new();
for age in 0..8 {
for facing in ["north", "south", "east", "west"] {
for waterlogged in ["false", "true"] {
possible.push(
json!({"age":age.to_string(), "facing":facing, "waterlogged":waterlogged}),
);
}
}
}
let fact = json!({"schema":{
"age":{"integer":[0,7]},
"facing":{"named":["north","south","east","west"]},
"waterlogged":{"named":["false","true"]}
},"states":possible});
let blocks = (target_bytes / (serde_json::to_vec(&fact)?.len() + 26)).max(1);
let mut facts = BTreeMap::new();
let mut states = Vec::new();
let mut defaults = BTreeMap::new();
for i in 0..blocks {
let block = format!("fixture_{i:04}");
let name = format!("minecraft:{block}");
defaults.insert(name.as_str().into(), Tag::Int(states.len() as i32));
for properties in &possible {
let state = BlockState {
name: name.clone(),
properties: serde_json::from_value(properties.clone())?,
};
states.push(state.to_nbt());
}
facts.insert(name, fact.clone());
fs::write(
root.join(format!("assets/minecraft/blockstates/{block}.json")),
r#"{"multipart":[{"apply":[{"model":"minecraft:block/fixture","weight":2},{"model":"minecraft:block/fixture","y":90,"weight":1}]},{"when":{"waterlogged":"true"},"apply":{"model":"minecraft:block/fixture","y":180,"uvlock":true}}]}"#,
)?;
}
fs::write(
root.join("assets/minecraft/models/block/fixture.json"),
r##"{"textures":{"all":"minecraft:block/fixture"},"elements":[{"from":[0,0,0],"to":[16,16,16],"faces":{"north":{"texture":"#all","cullface":"north"}}}]}"##,
)?;
let document = serde_json::to_vec(&facts)?;
let bytes = document.len();
fs::write(root.join("model-states.json"), document)?;
let registry = BlockRegistry::from_nbt(&Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
("states", Tag::List(states)),
("defaults", Tag::Compound(defaults)),
]))?;
Ok(Self {
root,
registry,
bytes,
blocks,
})
}
fn facts(&self) -> Result<BTreeMap<String, Value>> {
Ok(serde_json::from_slice(&fs::read(
self.root.join("model-states.json"),
)?)?)
}
fn block_names<'a>(&self, names: impl Iterator<Item = &'a String>) -> Vec<&'a str> {
names
.filter(|name| self.registry.default_state(name).is_some())
.filter_map(|name| name.strip_prefix("minecraft:"))
.collect()
}
fn load(&self, reuse: bool) -> Result<(StateModels, Sprites)> {
// The first parse and block filtering match models::prepare in both paths.
let mut sprites = Sprites::default();
let catalog = if reuse {
let facts = self.facts()?;
let blocks = self.block_names(facts.keys());
StateModels::from_facts(&self.root, &self.registry, &blocks, &mut sprites, &facts)?
} else {
let facts: serde_json::Map<String, Value> =
serde_json::from_slice(&fs::read(self.root.join("model-states.json"))?)?;
let blocks = self.block_names(facts.keys());
StateModels::load(&self.root, &self.registry, &blocks, &mut sprites)?
};
Ok((catalog, sprites))
}
fn verify(&self) -> Result<()> {
let (before, before_sprites) = self.load(false)?;
let (after, after_sprites) = self.load(true)?;
assert_eq!(before_sprites.layers, after_sprites.layers);
assert_eq!(before_sprites.opaque, after_sprites.opaque);
assert_eq!(before_sprites.translucent, after_sprites.translucent);
for id in 0..self.registry.len() {
for position in [
BlockPos::new(0, 0, 0),
BlockPos::new(12, -4, 7),
BlockPos::new(42, 9, -19),
] {
let a = before.collect(BlockStateId(id as u32), position)?;
let b = after.collect(BlockStateId(id as u32), position)?;
assert_eq!(a.len(), b.len());
for ((av, am), (bv, bm)) in a.into_iter().zip(b) {
assert_eq!(av, bv);
assert_eq!(am.ambient_occlusion, bm.ambient_occlusion);
assert_eq!(am.cube, bm.cube);
assert_eq!(am.faces.len(), bm.faces.len());
for (af, bf) in am.faces.iter().zip(&bm.faces) {
assert_eq!(af.quad, bf.quad);
assert_eq!(
(af.layer, af.opaque, af.translucent),
(bf.layer, bf.opaque, bf.translucent)
);
}
}
}
}
Ok(())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.root);
}
}
fn median(values: &mut [f64]) -> f64 {
values.sort_by(f64::total_cmp);
values[values.len() / 2]
}
fn main() -> Result<()> {
let repetitions: usize = std::env::args()
.nth(1)
.map(|s| s.parse())
.transpose()?
.unwrap_or(15);
if repetitions == 0 {
return Err("repetitions must be positive".into());
}
let fixture = Fixture::new(2_840_000)?;
fixture.verify()?;
for _ in 0..2 {
for reuse in [false, true] {
drop(black_box(fixture.load(reuse)?));
}
}
let mut before = Vec::new();
let mut after = Vec::new();
for iteration in 0..repetitions {
// Alternate order to limit cache/order bias. Both paths use slice parsing.
for reuse in if iteration % 2 == 0 {
[false, true]
} else {
[true, false]
} {
let started = Instant::now();
drop(black_box(fixture.load(black_box(reuse))?));
let ms = started.elapsed().as_secs_f64() * 1000.0;
if reuse {
after.push(ms);
} else {
before.push(ms);
}
}
}
let before = median(&mut before);
let after = median(&mut after);
println!(
"fixture: {} bytes, {} blocks, {} states; equality: all states at 3 positions",
fixture.bytes,
fixture.blocks,
fixture.registry.len()
);
println!(
"2 warmups/path, {repetitions} samples/path; median before {before:.3} ms, after {after:.3} ms; {:.3}x speedup ({:.2}% less time)",
before / after,
(1.0 - after / before) * 100.0
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shared_facts_match_load_and_preserve_errors() -> Result<()> {
let fixture = Fixture::new(1)?;
fixture.verify()?;
let mut facts = fixture.facts()?;
let blocks = ["fixture_0000"];
let load_error = |facts: &BTreeMap<String, Value>| -> Result<String> {
fs::write(
fixture.root.join("model-states.json"),
serde_json::to_vec(facts)?,
)?;
let a = StateModels::load(
&fixture.root,
&fixture.registry,
&blocks,
&mut Sprites::default(),
)
.err()
.ok_or("expected load error")?
.to_string();
let b = StateModels::from_facts(
&fixture.root,
&fixture.registry,
&blocks,
&mut Sprites::default(),
facts,
)
.err()
.ok_or("expected shared facts error")?
.to_string();
assert_eq!(a, b);
Ok(a)
};
let good = facts.clone();
facts.clear();
assert_eq!(load_error(&facts)?, "missing block model state schema");
facts = good.clone();
facts.get_mut("minecraft:fixture_0000").unwrap()["schema"] = Value::Null;
assert_eq!(load_error(&facts)?, "invalid model schema");
facts = good.clone();
facts.get_mut("minecraft:fixture_0000").unwrap()["states"]
.as_array_mut()
.unwrap()
.reverse();
assert_eq!(
load_error(&facts)?,
"model state definitions disagree with the imported block registry"
);
fs::remove_file(fixture.root.join("model-states.json"))?;
// A parsed document remains usable without reopening its source file.
StateModels::from_facts(
&fixture.root,
&fixture.registry,
&blocks,
&mut Sprites::default(),
&good,
)?;
assert!(
StateModels::load(
&fixture.root,
&fixture.registry,
&blocks,
&mut Sprites::default()
)
.is_err()
);
fs::write(fixture.root.join("model-states.json"), b"null")?;
assert!(
StateModels::load(
&fixture.root,
&fixture.registry,
&blocks,
&mut Sprites::default()
)
.is_err()
);
fs::write(fixture.root.join("model-states.json"), b"{")?;
assert!(
StateModels::load(
&fixture.root,
&fixture.registry,
&blocks,
&mut Sprites::default()
)
.is_err()
);
Ok(())
}
}
@@ -10,7 +10,7 @@ use horizon_client::{
biome::Biomes,
blocks::BlockFacts,
chunk::{Chunk, MIN_Y, SECTIONS},
light::{LightTables, light_chunk},
light::{LightTables, apply_lighting, light_chunk},
save::{self, SaveTables},
};
use horizon_core::position::ChunkPos;
@@ -157,7 +157,7 @@ fn main() -> horizon_client::Result<()> {
std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1)))
});
let mut chunk = chunks[&(x, z)].clone();
chunk.sections = light_chunk(&region, &lights, sky_light);
apply_lighting(&mut chunk, light_chunk(&region, &lights, sky_light));
chunk.lit = true;
let ours = save::encode_with(&chunk, assets.registry, &biomes, Some(&tables), sky_light);
let theirs = &originals[&(x, z)];
@@ -199,6 +199,28 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
velocity.z.to_bits()
)),
MotionEvent::SplashEvent => Some("splash-event".into()),
MotionEvent::Swim { volume, pitch } => Some(format!(
"sound swim entity {:08x} {:08x}",
volume.to_bits(),
pitch.to_bits()
)),
MotionEvent::Emission {
state,
in_water: true,
..
} => Some(format!("muffled-step {}", state.0)),
MotionEvent::BubbleColumnParticle { bubble, position } => Some(format!(
"column-particle {} {:016x},{:016x},{:016x} 1 {:016x},{:016x},{:016x} {:016x}",
if *bubble { "bubble" } else { "splash" },
position.x.to_bits(),
position.y.to_bits(),
position.z.to_bits(),
0f64.to_bits(),
if *bubble { 0.01f64 } else { 0.0 }.to_bits(),
0f64.to_bits(),
if *bubble { 0.2f64 } else { 1.0 }.to_bits()
)),
MotionEvent::Drown => Some("broadcast 67".into()),
// The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so.
MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()),
MotionEvent::Waypoint { receiver, enabled } => Some(format!(
@@ -399,7 +421,8 @@ fn main() -> Result<()> {
Some(vector(&op["value"]))
},
),
"block" => {
// A block, or every block of the box from position to "to".
"block" | "fill" => {
let p = &op["position"];
let mut state = assets
.registry
@@ -417,12 +440,15 @@ fn main() -> Result<()> {
.id(&definition)
.ok_or("missing fixture state")?;
}
world.scene.set(
p[0].as_i64().unwrap() as i32,
p[1].as_i64().unwrap() as i32,
p[2].as_i64().unwrap() as i32,
state,
)?;
let at = |v: &Value, i: usize| v[i].as_i64().unwrap() as i32;
let to = if op["to"].is_array() { &op["to"] } else { p };
for x in at(p, 0)..=at(to, 0) {
for y in at(p, 1)..=at(to, 1) {
for z in at(p, 2)..=at(to, 2) {
world.scene.set(x, y, z, state)?;
}
}
}
}
"landing" => {
let p = &op["position"];
@@ -443,6 +469,23 @@ fn main() -> Result<()> {
// Entity.baseTick's fluid phase alone (wasEyeInWater,
// updateFluidInteraction, lava fall halving, firstTick).
"fluid_tick" => world.fluid_base_tick()?,
// LivingEntity.baseTick's air supply alone.
"air_tick" => world.tick_environment_damage()?,
"air" => world.player.air = op["value"].as_i64().unwrap() as i32,
"pitch" => world.player.pitch = single(&op["value"]),
"swimming" => world.player.swimming = op["value"].as_bool().unwrap(),
"effect" => {
let on = op["value"].as_bool().unwrap();
let status = &mut world.player.status;
match op["name"].as_str().unwrap() {
"minecraft:dolphins_grace" => status.dolphins_grace = on,
"minecraft:water_breathing" | "minecraft:conduit_power" => {
status.water_breathing = on
}
"minecraft:breath_of_the_nautilus" => status.breath_of_the_nautilus = on,
other => return Err(format!("unknown fixture effect {other}").into()),
}
}
"travel" => world.travel_in_air(vector(&op["value"]))?,
"tick" => {
let v = vector(&op["value"]);
@@ -569,7 +612,7 @@ fn main() -> Result<()> {
let stuck = player.stuck_multiplier;
writeln!(
out,
"block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x}",
"block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x} swim {} {} air {}",
check_block.0,
player.ticks_frozen,
player.in_powder_snow,
@@ -582,7 +625,10 @@ fn main() -> Result<()> {
player.is_eye_in_fluid(WATER),
player.fluids.first_tick,
player.fluid_height(WATER).to_bits(),
player.fluid_height(LAVA).to_bits()
player.fluid_height(LAVA).to_bits(),
player.swimming,
player.fluids.was_eye_in_water,
player.air
)?;
writeln!(
out,
@@ -0,0 +1,143 @@
//! Resident-key synchronization used by Game (registration callback work excluded).
//! Run: CARGO_INCREMENTAL=0 cargo run -p horizon-client --profile fast --example tick_chunk_membership_bench
use horizon_client::{
chunk::Chunk, chunk_map::ChunkMap, tick_chunk_membership::TickChunkMembership,
};
use std::{collections::HashSet, hint::black_box, sync::Arc, time::Instant};
type Key = (i32, i32);
#[derive(Default)]
struct Old {
keys: HashSet<Key>,
}
impl Old {
fn sync(&mut self, map: &ChunkMap) -> (usize, usize) {
let loaded: HashSet<_> = map.keys().copied().collect();
let mut counts = (0, 0);
for key in loaded.difference(&self.keys.clone()) {
black_box(key);
counts.0 += 1;
}
for key in self.keys.difference(&loaded) {
black_box(key);
counts.1 += 1;
}
self.keys = loaded;
counts
}
}
fn new_sync(cache: &mut TickChunkMembership, map: &ChunkMap) -> (usize, usize) {
if !cache.synchronize(map) {
return (0, 0);
}
let added = cache.take_added();
for key in &added {
black_box(key);
}
for key in cache.removed() {
black_box(key);
}
let counts = (added.len(), cache.removed().len());
cache.recycle_added(added);
counts
}
fn map(offset: i32) -> ChunkMap {
let mut map = ChunkMap::default();
// Share a payload: the synchronization path reads only keys, not block data.
let chunk = Arc::new(Chunk::empty(0, 0));
for x in -16..=16 {
for z in -16..=16 {
map.insert((x + offset, z), chunk.clone());
}
}
map
}
fn run(new: bool, scenario: usize, iterations: usize) -> (f64, (usize, usize)) {
let mut a = map(0);
let b = map(33);
let chunk = Arc::new(Chunk::empty(0, 0));
let mut old = Old::default();
let mut cache = TickChunkMembership::default();
for _ in 0..64 {
if new {
black_box(new_sync(&mut cache, &a));
} else {
black_box(old.sync(&a));
}
}
let mut total = (0, 0);
let start = Instant::now();
for i in 0..iterations {
let resident = match scenario {
0 => &a,
1 => {
let (previous, next) = if i % 2 == 0 {
((-16, -16), (-17, -16))
} else {
((-17, -16), (-16, -16))
};
a.remove(&previous);
a.insert(next, chunk.clone());
&a
}
2 => {
if i % 2 == 0 {
&b
} else {
&a
}
}
_ => unreachable!(),
};
let counts = if new {
new_sync(black_box(&mut cache), black_box(resident))
} else {
old.sync(black_box(resident))
};
total.0 += counts.0;
total.1 += counts.1;
}
(
start.elapsed().as_secs_f64() * 1e9 / iterations as f64,
black_box(total),
)
}
fn main() {
println!("1089 keys, 64 warmup calls, 9 samples; ns/sync, median");
for (scenario, name, iterations) in [
(0, "stable", 10_000),
(1, "one-key same-count replacement", 2_000),
(2, "whole-map replacement", 1_000),
] {
let mut before = Vec::new();
let mut after = Vec::new();
for sample in 0..9 {
let (old, new) = if sample % 2 == 0 {
(
run(false, scenario, iterations),
run(true, scenario, iterations),
)
} else {
let new = run(true, scenario, iterations);
(run(false, scenario, iterations), new)
};
assert_eq!(old.1, new.1);
let expected = match scenario {
0 => (0, 0),
1 => (iterations, iterations),
_ => (1089 * iterations, 1089 * iterations),
};
assert_eq!(new.1, expected);
before.push(old.0);
after.push(new.0);
}
before.sort_by(f64::total_cmp);
after.sort_by(f64::total_cmp);
println!(
"{name}: {:.1} -> {:.1} ns, {:.2}x; {iterations} iterations/sample",
before[4],
after[4],
before[4] / after[4]
);
}
}
+3
View File
@@ -387,6 +387,9 @@ pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) ->
let Some(mut st) = p.arrow.take() else {
return (false, Hit::None);
};
// Entity.setOldPosAndRot: the renderer interpolates from here, in flight
// and stuck alike.
p.previous = p.position;
let hit = Ticker {
p,
st: &mut st,
+438
View File
@@ -0,0 +1,438 @@
//! Beehives and bee nests (`BeehiveBlockEntity`): up to three bees stored as
//! entity tags, let out when their time inside is up (never at night or in
//! the rain, nor through a blocked front, unless the hive is emptied in an
//! emergency), honey for every bee coming home with nectar. The host (the game
//! or the mob AI probe) loads and adds the bees through [`HiveHost`].
use crate::mobs::{Mob, Species, bee};
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::nbt::{Compound, Tag};
pub const MAX_OCCUPANTS: usize = 3;
/// `BeehiveBlockEntity.IGNORED_BEE_TAGS`: dropped from a bee going in, and
/// again from the tag it comes out with.
const IGNORED_BEE_TAGS: [&str; 25] = [
"Air",
"drop_chances",
"equipment",
"Brain",
"CanPickUpLoot",
"DeathTime",
"fall_distance",
"FallFlying",
"Fire",
"HurtTime",
"LeftHanded",
"Motion",
"NoGravity",
"OnGround",
"PortalCooldown",
"Pos",
"Rotation",
"sleeping_pos",
"CannotEnterHiveTicks",
"TicksSincePollination",
"CropsGrownSincePollination",
"hive_pos",
"Passengers",
"leash",
"UUID",
];
/// `BeehiveBlockEntity`: the bees inside and the flower one of them knew.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Beehive {
pub bees: Vec<Occupant>,
pub flower: Option<[i32; 3]>,
}
/// `BeehiveBlockEntity.Occupant`: a bee's tag (with its `id`), its time in
/// the hive and the time it stays at least.
#[derive(Clone, Debug, PartialEq)]
pub struct Occupant {
pub entity_data: Tag,
pub ticks_in_hive: i32,
pub min_ticks_in_hive: i32,
}
/// `BeehiveBlockEntity.BeeReleaseStatus`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Release {
HoneyDelivered,
BeeReleased,
Emergency,
}
/// What a hive needs from the level it is in.
pub trait HiveHost {
/// `level.getRandom()`.
fn random(&mut self) -> &mut LegacyRandom;
/// `EnvironmentAttributes.BEES_STAY_IN_HIVE` at a position.
fn bees_stay_in_hive(&self, at: [i32; 3]) -> bool;
/// A non-empty collision shape at a block.
fn blocked(&self, at: [i32; 3]) -> bool;
/// `BlockState.setValue(HONEY_LEVEL, level)` on the hive.
fn set_honey_level(&mut self, at: [i32; 3], level: i32);
/// `EntityType.loadEntityRecursive` (the tag has its `id` and a `Pos`):
/// a new entity, or `None` for anything but a `#beehive_inhabitors`.
fn load(&mut self, tag: &Tag) -> Option<Mob>;
/// `Level.addFreshEntity`.
fn add(&mut self, m: Mob) -> bool;
fn sound(&mut self, name: &'static str, at: [f64; 3]);
}
fn strip_ignored(c: &mut Compound) {
for key in IGNORED_BEE_TAGS {
c.remove(&key.into());
}
}
fn int(tag: Option<&Tag>) -> Option<i32> {
match tag {
Some(Tag::Int(v)) => Some(*v),
_ => None,
}
}
fn pos(tag: Option<&Tag>) -> Option<[i32; 3]> {
match tag {
Some(Tag::IntArray(p)) if p.len() == 3 => Some([p[0], p[1], p[2]]),
_ => None,
}
}
impl Occupant {
/// `Occupant.of`: the bee's saved tag without the ignored tags, staying
/// 2400 ticks with nectar, else 600.
pub fn of(mut tag: Tag) -> Self {
if let Tag::Compound(c) = &mut tag {
strip_ignored(c);
}
let nectar = matches!(tag.get("HasNectar"), Some(Tag::Byte(v)) if *v != 0);
Self {
entity_data: tag,
ticks_in_hive: 0,
min_ticks_in_hive: if nectar { 2400 } else { 600 },
}
}
/// `Occupant.create`: a worldgen nest's bee, a bare bee tag.
pub fn create(ticks_in_hive: i32) -> Self {
Self {
entity_data: Tag::compound([("id", Tag::String("minecraft:bee".into()))]),
ticks_in_hive,
min_ticks_in_hive: 600,
}
}
fn has_nectar(&self) -> bool {
matches!(self.entity_data.get("HasNectar"), Some(Tag::Byte(v)) if *v != 0)
}
fn from_nbt(tag: &Tag) -> Option<Self> {
let data = tag.get("entity_data")?;
if !matches!(data, Tag::Compound(c) if c.contains_key(&"id".into())) {
return None;
}
Some(Self {
entity_data: data.clone(),
ticks_in_hive: int(tag.get("ticks_in_hive"))?,
min_ticks_in_hive: int(tag.get("min_ticks_in_hive"))?,
})
}
fn to_nbt(&self) -> Tag {
Tag::compound([
("entity_data", self.entity_data.clone()),
("ticks_in_hive", Tag::Int(self.ticks_in_hive)),
("min_ticks_in_hive", Tag::Int(self.min_ticks_in_hive)),
])
}
}
impl Beehive {
pub fn full(&self) -> bool {
self.bees.len() == MAX_OCCUPANTS
}
/// `loadAdditional`: `bees` (all or none, as the list codec reads them)
/// and `flower_pos`.
pub fn from_nbt(tag: &Tag) -> Self {
let bees = match tag.get("bees") {
Some(Tag::List(list)) => list
.iter()
.map(Occupant::from_nbt)
.collect::<Option<Vec<_>>>()
.unwrap_or_default(),
_ => Vec::new(),
};
Self {
bees,
flower: pos(tag.get("flower_pos")),
}
}
/// `saveAdditional`.
pub fn to_nbt(&self) -> Vec<(&'static str, Tag)> {
let mut out = vec![(
"bees",
Tag::List(self.bees.iter().map(Occupant::to_nbt).collect()),
)];
if let Some(f) = self.flower {
out.push(("flower_pos", Tag::IntArray(f.to_vec())));
}
out
}
/// `addOccupant` (the bee's own tag, saved by the host): the hive keeps
/// the bee's flower, or now and then swaps its own for it. The host then
/// discards the bee.
pub fn add_occupant(
&mut self,
at: [i32; 3],
tag: Tag,
bee_flower: Option<[i32; 3]>,
host: &mut impl HiveHost,
) -> bool {
if self.bees.len() >= MAX_OCCUPANTS {
return false;
}
self.bees.push(Occupant::of(tag));
if let Some(f) = bee_flower
&& (self.flower.is_none() || host.random().next_boolean())
{
self.flower = Some(f);
}
let corner = at.map(f64::from);
host.sound("block.beehive.enter", corner);
true
}
/// `serverTick`: the bees whose time is up come out, then the hive
/// hums now and then while it holds any. `honey` is the hive state's
/// honey level as the tick starts (`None` without the property);
/// `facing` its front.
pub fn server_tick(
&mut self,
at: [i32; 3],
facing: [i32; 2],
honey: Option<i32>,
host: &mut impl HiveHost,
) {
let flower = self.flower;
let mut i = 0;
while i < self.bees.len() {
// BeeData.tick: ticksInHive++ > minTicksInHive.
let b = &mut self.bees[i];
let up = b.ticks_in_hive > b.min_ticks_in_hive;
b.ticks_in_hive += 1;
if up {
let status = if b.has_nectar() {
Release::HoneyDelivered
} else {
Release::BeeReleased
};
let occupant = b.clone();
if release(host, at, facing, honey, &occupant, status, flower).is_some() {
self.bees.remove(i);
continue;
}
}
i += 1;
}
if !self.bees.is_empty() && host.random().next_double() < 0.005 {
let hum = [
f64::from(at[0]) + 0.5,
f64::from(at[1]),
f64::from(at[2]) + 0.5,
];
host.sound("block.beehive.work", hum);
}
}
/// `releaseAllOccupants`: the ids of the bees let out.
pub fn release_all(
&mut self,
at: [i32; 3],
facing: [i32; 2],
honey: Option<i32>,
status: Release,
host: &mut impl HiveHost,
) -> Vec<u32> {
let flower = self.flower;
let mut out = Vec::new();
self.bees.retain(
|b| match release(host, at, facing, honey, b, status, flower) {
Some(id) => {
out.extend(id);
false
}
None => true,
},
);
out
}
}
/// `releaseOccupant`: `None` while the bee stays in, else the id of the bee
/// let out (`Some(None)` when the level refused it).
fn release(
host: &mut impl HiveHost,
at: [i32; 3],
facing: [i32; 2],
honey: Option<i32>,
occupant: &Occupant,
status: Release,
flower: Option<[i32; 3]>,
) -> Option<Option<u32>> {
let emergency = status == Release::Emergency;
if host.bees_stay_in_hive(at) && !emergency {
return None;
}
let blocked = host.blocked([at[0] + facing[0], at[1], at[2] + facing[1]]);
if blocked && !emergency {
return None;
}
// Occupant.createEntity: the tag without the ignored tags.
let mut tag = occupant.entity_data.clone();
if let Tag::Compound(c) = &mut tag {
strip_ignored(c);
let center = [at[0], at[1], at[2]].map(|v| Tag::Double((f64::from(v) + 0.5).to_bits()));
c.insert("Pos".into(), Tag::List(center.to_vec()));
}
let mut m = host.load(&tag)?;
m.no_gravity = true;
if m.species() == Species::Bee {
bee::set_hive(&mut m, Some(at));
// setBeeReleaseData: the time inside counts towards growing up and
// away from love.
let ticks = occupant.ticks_in_hive;
if !m.extra.age_locked {
let age = m.extra.age;
m.extra.age = if age < 0 {
(age + ticks).min(0)
} else if age > 0 {
(age - ticks).max(0)
} else {
age
};
}
m.extra.in_love = (m.extra.in_love - ticks).max(0);
if let Some(f) = flower
&& bee::get(&m).is_none_or(|b| b.flower.is_none())
&& host.random().next_float() < 0.9
{
bee::set_flower(&mut m, Some(f));
}
if status == Release::HoneyDelivered {
bee::drop_off_nectar(&mut m);
if let Some(level) = honey.filter(|&l| l < 5) {
let mut increase = if host.random().next_int_bound(100).unwrap_or(1) == 0 {
2
} else {
1
};
if level + increase > 5 {
increase -= 1;
}
host.set_honey_level(at, level + increase);
}
}
let delta = if blocked {
0.0
} else {
0.55 + f64::from(m.width() / 2.0)
};
let p = horizon_core::geometry::Vec3::new(
f64::from(at[0]) + 0.5 + delta * f64::from(facing[0]),
f64::from(at[1]) + 0.5 - f64::from(m.height() / 2.0),
f64::from(at[2]) + 0.5 + delta * f64::from(facing[1]),
);
m.position = p;
m.previous = p;
}
host.sound(
"block.beehive.exit",
[
f64::from(at[0]) + 0.5,
f64::from(at[1]) + 0.5,
f64::from(at[2]) + 0.5,
],
);
let id = m.id;
Some(host.add(m).then_some(id))
}
/// `CampfireBlock.isSmokeyPos`: a lit campfire up to five blocks below,
/// unless a block whose collision crosses the smoke's centre post comes
/// first (a lit campfire right under that block still counts).
pub fn smokey(w: &crate::mobs::MobWorld, at: [i32; 3]) -> bool {
let lit = |y: i32| {
w.has_tag("minecraft:campfires", w.block_name(at[0], y, at[2]))
&& w.prop(at[0], y, at[2], "lit") == Some("true")
};
for i in 1..=5 {
let y = at[1] - i;
if lit(y) {
return true;
}
// SHAPE_VIRTUAL_POST: Block.column(4, 0, 16), the middle quarter.
let (x0, z0) = (f64::from(at[0]), f64::from(at[2]));
let blocked = w.block_collision_boxes(at[0], y, at[2]).iter().any(|b| {
let (min, max) = (b.min_position(), b.max_position());
min.x < x0 + 0.625 && max.x > x0 + 0.375 && min.z < z0 + 0.625 && max.z > z0 + 0.375
});
if blocked {
return lit(y - 1);
}
}
false
}
/// `HorizontalDirectionalBlock.FACING` as an x/z step.
pub fn facing_step(facing: Option<&str>) -> [i32; 2] {
match facing {
Some("south") => [0, 1],
Some("west") => [-1, 0],
Some("east") => [1, 0],
_ => [0, -1],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nbt_round_trips_in_vanilla_order() {
let tag = Tag::compound([
(
"bees",
Tag::List(vec![
Occupant::create(37).to_nbt(),
Occupant::create(0).to_nbt(),
]),
),
("flower_pos", Tag::IntArray(vec![1, -60, 3])),
]);
let hive = Beehive::from_nbt(&tag);
assert_eq!(hive.bees.len(), 2);
assert_eq!(hive.bees[0].ticks_in_hive, 37);
assert_eq!(hive.flower, Some([1, -60, 3]));
assert_eq!(Tag::compound(hive.to_nbt()), tag);
}
#[test]
fn a_bad_bee_drops_the_whole_list() {
let tag = Tag::compound([(
"bees",
Tag::List(vec![
Occupant::create(1).to_nbt(),
Tag::compound([("ticks_in_hive", Tag::Int(3))]),
]),
)]);
assert!(Beehive::from_nbt(&tag).bees.is_empty());
}
#[test]
fn going_in_strips_the_ignored_tags() {
let tag = Tag::compound([
("id", Tag::String("minecraft:bee".into())),
("UUID", Tag::IntArray(vec![1, 2, 3, 4])),
("Health", Tag::Float(10.0_f32.to_bits())),
("HasNectar", Tag::Byte(1)),
("hive_pos", Tag::IntArray(vec![0, 0, 0])),
]);
let o = Occupant::of(tag);
assert_eq!(o.min_ticks_in_hive, 2400);
assert!(o.entity_data.get("UUID").is_none());
assert!(o.entity_data.get("hive_pos").is_none());
assert!(o.entity_data.get("Health").is_some());
}
}
+427
View File
@@ -0,0 +1,427 @@
//! `horizon-client --benchmark SCENARIO`: the run `tools/perf_bench.py` drives from outside, driven
//! from inside, so anyone can measure their machine with nothing but the game. A thread sends the
//! same control commands `horizon-ctl` would, through the game's own command queue, and writes a
//! report (docs/benchmark-report.md) to `benchmarks/` in the game folder.
//!
//! The scenes, the world (seed 1234, creative) and every step and figure match `tools/perf_bench.py`,
//! so reports from the two can be compared.
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Sender};
use std::thread;
use std::time::{Duration, Instant};
use horizon_bench::{App, Frames, Kind, Report};
use serde_json::Value;
use crate::control::Request;
pub const SEED: i64 = 1234;
/// The world the benchmark creates under `saves/`, replaced on every run.
pub const WORLD: &str = "horizon-benchmark";
/// Written into the world so a later run only ever replaces its own world.
const MARKER: &str = "horizon-benchmark.txt";
/// A straight flight over terrain: name, start, end, pitch (`tools/graphics_bench.py`'s paths).
type Scene = (&'static str, [f64; 3], [f64; 3], f64);
pub const SCENES: [Scene; 4] = [
(
"village",
[-960.0, 125.0, 80.0],
[-960.0, 125.0, 272.0],
35.0,
),
(
"forest",
[-1100.0, 120.0, -560.0],
[-1100.0, 120.0, -368.0],
25.0,
),
(
"ocean",
[-300.0, 85.0, -420.0],
[-300.0, 85.0, -228.0],
10.0,
),
(
"mountain",
[560.0, 260.0, 860.0],
[752.0, 260.0, 860.0],
30.0,
),
];
const FLIGHT_SECONDS: f64 = 12.0;
const SETTLE: Duration = Duration::from_secs(2);
const LOAD_LIMIT: Duration = Duration::from_secs(600);
/// `standard` flies every scene; a scene's name flies only that one.
pub fn scenes(scenario: &str) -> Option<Vec<Scene>> {
match scenario {
"standard" => Some(SCENES.to_vec()),
name => SCENES.iter().find(|s| s.0 == name).map(|s| vec![*s]),
}
}
/// What the game knows about the run before it starts.
pub struct Setup {
pub scenario: String,
pub started: Instant,
pub app: App,
pub simulation_distance: u32,
pub vsync: bool,
/// `None`: unlimited.
pub fps_cap: Option<u32>,
pub offscreen: bool,
pub game_dir: PathBuf,
}
/// Starts the driver; the game quits when it is done, and the report's path is printed.
pub fn start(requests: Sender<Request>, setup: Setup) {
thread::Builder::new()
.name("horizon-benchmark".into())
.spawn(move || {
let control = Control(requests);
match run(&control, setup) {
Ok(path) => println!("Horizon: benchmark report {}", path.display()),
Err(e) => eprintln!("Horizon: benchmark failed: {e}"),
}
let _ = control.call("quit");
})
.expect("spawn the benchmark thread");
}
struct Control(Sender<Request>);
impl Control {
fn call(&self, line: &str) -> Result<Value, String> {
let (reply, response) = mpsc::channel();
self.0
.send(Request {
line: line.to_owned(),
reply,
})
.map_err(|_| "the game has exited".to_owned())?;
// Flights and loads reply when they finish.
let text = response
.recv_timeout(LOAD_LIMIT)
.map_err(|_| format!("{line}: no reply"))?;
let value: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
match value.get("error").and_then(Value::as_str) {
Some(e) => Err(format!("{line}: {e}")),
None => Ok(value),
}
}
fn status(&self) -> Value {
self.call("status").unwrap_or(Value::Null)
}
}
fn run(control: &Control, setup: Setup) -> Result<PathBuf, String> {
let scenes =
scenes(&setup.scenario).ok_or_else(|| format!("unknown scenario {}", setup.scenario))?;
let mut report = Report::new(Kind::Game, setup.app.clone());
let pid = std::process::id();
report.conditions.load_avg_1m = horizon_bench::load_average();
report.conditions.power = horizon_bench::power_source().map(str::to_owned);
let rss = RssSampler::start(pid);
let title = poll(control, LOAD_LIMIT, |s| {
s["screen"] == "title" && !s["renderer"].is_null()
})?;
report.metric("startup.title_ms", &[ms(setup.started.elapsed())]);
let renderer = &title["renderer"];
report.hardware.gpu = Some(horizon_bench::Gpu {
name: text(&renderer["gpu"]),
vendor: match text(&renderer["vendor"]) {
// Metal reports no vendor ID.
v if v.is_empty() && text(&renderer["gpu"]).starts_with("Apple") => "apple".into(),
v => v,
},
driver: text(&renderer["driver"]),
backend: text(&renderer["backend"]).to_lowercase(),
kind: text(&renderer["device_type"]),
});
report.hardware.display = serde_json::from_value(title["display"].clone()).ok();
replace_world(&setup.game_dir)?;
control.call(&format!("open {WORLD} {SEED} creative"))?;
std::fs::write(
setup.game_dir.join("saves").join(WORLD).join(MARKER),
"Created by horizon-client --benchmark; replaced by the next run.\n",
)
.map_err(|e| e.to_string())?;
let loaded = wait_loaded(control, |_| true)?;
report.metric("startup.world_ms", &[ms(loaded - setup.started)]);
let mut steady = Vec::new();
for (name, start, end, pitch) in scenes {
control.call("time 6000")?;
let meshed = control.status()["meshed_sections"].as_f64().unwrap_or(0.0);
let generated = control.status()["generated_chunks"].as_f64().unwrap_or(0.0);
let [x, y, z] = start;
control.call(&format!("tp {x} {y} {z}"))?;
let teleported = Instant::now();
// A zero-length flight holds the player at the start, flying.
control.call(&format!("fly {x} {y} {z} {x} {y} {z} 0.1 {pitch}"))?;
control.call(&format!("look {:.3} {pitch}", yaw(start, end)))?;
let near = |p: &Value| {
let p: Vec<f64> = p
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_f64)
.collect();
p.len() == 3 && (0..3).map(|i| (p[i] - start[i]).powi(2)).sum::<f64>() < 4.0
};
let loaded = wait_loaded(control, near)?;
let load = loaded - teleported;
report.metric(&format!("chunks.{name}.load_ms"), &[ms(load)]);
let status = control.status();
let meshes = status["meshed_sections"].as_f64().unwrap_or(0.0) - meshed;
let chunks = status["generated_chunks"].as_f64().unwrap_or(0.0) - generated;
report.metric(&format!("chunks.{name}.meshed_count"), &[meshes]);
report.metric(&format!("chunks.{name}.generated_count"), &[chunks]);
if load.as_secs_f64() > 0.0 {
report.metric(
&format!("chunks.{name}.generated_per_s"),
&[chunks / load.as_secs_f64()],
);
}
thread::sleep(SETTLE);
let [ex, ey, ez] = end;
let begin = Instant::now();
let flight = control.call(&format!(
"fly {x} {y} {z} {ex} {ey} {ez} {FLIGHT_SECONDS} {pitch} raw"
))?;
steady.push((begin, Instant::now()));
let series = |key: &str| -> Vec<f32> {
flight[key]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_f64)
.map(|v| v as f32)
.collect()
};
let frames = Frames::of(
name,
0,
&series("frame_ms"),
&series("cpu_ms"),
&series("gpu_ms"),
)
.ok_or("the flight drew no frames")?;
report.metric(&format!("fps.{name}.avg_fps"), &[frames.avg_fps]);
report.metric(&format!("fps.{name}.low_1pct_fps"), &[frames.low_1pct_fps]);
report.metric(
&format!("fps.{name}.low_01pct_fps"),
&[frames.low_01pct_fps],
);
report.frames.push(frames);
}
let status = control.status();
let renderer = &status["renderer"];
let c = &mut report.conditions;
c.scenario = Some(setup.scenario.clone());
c.seed = Some(SEED.to_string());
c.render_distance = status["render_distance"].as_u64().map(|d| d as u32);
c.simulation_distance = Some(setup.simulation_distance);
c.window = serde_json::from_value(renderer["size"].clone()).ok();
c.vsync = Some(setup.vsync);
c.fps_cap = setup.fps_cap;
c.offscreen = Some(setup.offscreen);
c.repeats = Some(1);
c.warmup_s = Some(SETTLE.as_secs_f64());
if let Some(bytes) = renderer["gpu_allocated_bytes"].as_f64() {
report.metric("memory.gpu_mb", &[bytes / f64::from(1 << 20)]);
}
let samples = rss.stop();
if let Some(peak) = samples.iter().map(|s| s.1).max() {
report.metric("memory.rss_peak_mb", &[peak as f64 / f64::from(1 << 20)]);
}
let mut during: Vec<u64> = samples
.iter()
.filter(|(t, _)| steady.iter().any(|(a, b)| a <= t && t <= b))
.map(|s| s.1)
.collect();
during.sort_unstable();
if let Some(&median) = during.get(during.len() / 2) {
report.metric(
"memory.rss_steady_mb",
&[median as f64 / f64::from(1 << 20)],
);
}
if let Ok(meta) = std::env::current_exe().and_then(std::fs::metadata) {
report.metric("game.binary_bytes", &[meta.len() as f64]);
}
crate::telemetry::keep_benchmark(&crate::logging::game_home(), &report);
report
.write_to(&setup.game_dir.join("benchmarks"))
.map_err(|e| e.to_string())
}
/// Removes the previous run's world, never one the benchmark didn't create.
fn replace_world(game_dir: &Path) -> Result<(), String> {
let world = game_dir.join("saves").join(WORLD);
if !world.exists() {
return Ok(());
}
if !world.join(MARKER).exists() {
return Err(format!(
"{} exists and was not created by the benchmark: rename it",
world.display()
));
}
std::fs::remove_dir_all(&world).map_err(|e| e.to_string())
}
fn poll(
control: &Control,
limit: Duration,
ready: impl Fn(&Value) -> bool,
) -> Result<Value, String> {
let deadline = Instant::now() + limit;
while Instant::now() < deadline {
let status = control.status();
if ready(&status) {
return Ok(status);
}
thread::sleep(Duration::from_millis(50));
}
Err(format!("not ready after {} s", limit.as_secs()))
}
/// Fewer section meshes than this in a second is the game remeshing blocks that change (random
/// ticks), not loading.
const QUIET_MESHES_PER_S: f64 = 100.0;
/// Waits until the player is spawned where `near` says, nothing is queued, the resident and
/// generated chunk counts have not changed for a second and the last sections are drawn (they wait
/// for their neighbours' light, so after the counts settle); returns when the last of these
/// happened (`tools/perf_bench.py`'s `wait_loaded`). With `status.streaming`, the sections are
/// drawn once no stage has held work for half a second: blocks changing after the load (fluids
/// settling, random ticks) only remesh in bursts. Without it, meshing has to go quiet.
fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result<Instant, String> {
let deadline = Instant::now() + LOAD_LIMIT;
let (mut last, mut changed, mut meshing) = (None, Instant::now(), Instant::now());
let mut previous: Option<(Instant, f64)> = None;
while Instant::now() < deadline {
let s = control.status();
let now = Instant::now();
let position = &s["player"]["position"];
if position.is_null()
|| !near(position)
|| s["pending_chunks"] != 0
|| s["screen"] == "title"
{
(last, changed, previous, meshing) = (None, now, None, now);
} else {
let counts = (s["chunks"].as_u64(), s["generated_chunks"].as_u64());
if last != Some(counts) {
(last, changed) = (Some(counts), now);
}
let meshed = s["meshed_sections"].as_f64().unwrap_or(0.0);
let quiet = if let Some(stages) = s["streaming"].as_object() {
// Protos outside the view distance wait for neighbours that are never generated.
if stages
.iter()
.any(|(k, v)| k != "protos" && v.as_u64().unwrap_or(0) > 0)
{
meshing = now;
}
Duration::from_millis(500)
} else {
if let Some((at, before)) = previous
&& meshed - before > QUIET_MESHES_PER_S * (now - at).as_secs_f64()
{
meshing = now;
}
Duration::from_secs(1)
};
previous = Some((now, meshed));
if now - changed >= Duration::from_secs(1) && now - meshing >= quiet {
return Ok(changed.max(meshing));
}
}
thread::sleep(Duration::from_millis(50));
}
Err(format!("not loaded after {} s", LOAD_LIMIT.as_secs()))
}
/// Vanilla's yaw facing from `start` to `end`.
fn yaw(start: [f64; 3], end: [f64; 3]) -> f64 {
(-(end[0] - start[0])).atan2(end[2] - start[2]).to_degrees()
}
fn ms(d: Duration) -> f64 {
d.as_secs_f64() * 1000.0
}
fn text(v: &Value) -> String {
v.as_str().unwrap_or_default().to_owned()
}
/// Samples the process's resident memory four times a second, as `tools/perf_bench.py` does.
struct RssSampler {
stop: Sender<()>,
thread: thread::JoinHandle<Vec<(Instant, u64)>>,
}
impl RssSampler {
fn start(pid: u32) -> Self {
let (stop, stopped) = mpsc::channel();
let thread = thread::spawn(move || {
let mut samples = Vec::new();
while let Err(mpsc::RecvTimeoutError::Timeout) =
stopped.recv_timeout(Duration::from_millis(250))
{
samples.extend(horizon_bench::rss_bytes(pid).map(|b| (Instant::now(), b)));
}
samples
});
Self { stop, thread }
}
fn stop(self) -> Vec<(Instant, u64)> {
let _ = self.stop.send(());
self.thread.join().unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scenarios() {
assert_eq!(scenes("standard").unwrap().len(), 4);
assert_eq!(scenes("ocean").unwrap()[0].0, "ocean");
assert!(scenes("nether").is_none());
}
#[test]
fn yaw_matches_vanilla() {
// South (+Z) is 0, west (-X) 90, east (+X) -90.
assert!((yaw([0.0; 3], [0.0, 0.0, 10.0])).abs() < 1e-9);
assert!((yaw([0.0; 3], [-10.0, 0.0, 0.0]) - 90.0).abs() < 1e-9);
assert!((yaw([0.0; 3], [10.0, 0.0, 0.0]) + 90.0).abs() < 1e-9);
}
#[test]
fn only_replaces_its_own_world() {
let dir =
std::env::temp_dir().join(format!("horizon-benchmark-test-{}", std::process::id()));
let world = dir.join("saves").join(WORLD);
std::fs::create_dir_all(&world).unwrap();
assert!(
replace_world(&dir).is_err(),
"a player's world of that name stays"
);
assert!(world.exists());
std::fs::write(world.join(MARKER), "").unwrap();
replace_world(&dir).unwrap();
assert!(!world.exists());
replace_world(&dir).unwrap();
std::fs::remove_dir_all(dir).unwrap();
}
}
@@ -305,7 +305,8 @@ pub const COMMANDS: &[Cmd] = &[
["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!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH]", "fly the camera along a line, then reply with the frame summary", "",
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",
"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),
];
+3 -3
View File
@@ -598,8 +598,8 @@ pub fn depth_far(render_distance_chunks: i32, cloud_range_chunks: i32) -> f32 {
/// `Projection.getMatrix` for a perspective set up by `setupPerspective`:
/// JOML's `Matrix4f.setPerspective(fov * DEG_TO_RAD, width / height, near,
/// far, zZeroToOne)`, column-major. Vanilla passes its planes reversed
/// (`near` is `zFar`); the hand pass here keeps them in order.
/// far, zZeroToOne)`, column-major. Vanilla's `Projection` passes its planes
/// reversed (`near` is `zFar`) for reversed depth.
pub fn perspective(
fov_degrees: f32,
width: f32,
@@ -632,7 +632,7 @@ pub fn perspective(
/// death and fluids), never the FOV option or the sprint, speed and bow
/// modifier.
pub fn hand_projection(hud_fov: f32, width: f32, height: f32, far: f32) -> [f32; 16] {
perspective(hud_fov, width, height, 0.05, far, true)
perspective(hud_fov, width, height, far, 0.05, true)
}
/// `Camera.modifyFovBasedOnDeathOrFluid`. `dead` is the camera entity's
/// `deathTime` while it is a living entity that is dead or dying.
+10 -4
View File
@@ -20,6 +20,15 @@ pub enum Light {
Uniform(u8),
Full(Box<[u8; 4096]>),
}
impl Light {
#[inline]
pub fn get(&self, i: usize) -> u8 {
match self {
Self::Uniform(v) => *v,
Self::Full(a) => a[i],
}
}
}
#[inline]
pub fn index(x: i32, y: i32, z: i32) -> usize {
((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize
@@ -59,10 +68,7 @@ impl Section {
}
#[inline]
pub fn light(&self, i: usize) -> u8 {
match &self.light {
Light::Uniform(v) => *v,
Light::Full(a) => a[i],
}
self.light.get(i)
}
pub fn is_uniform(&self, v: u16) -> bool {
self.blocks.is_uniform(u32::from(v))
+122
View File
@@ -0,0 +1,122 @@
//! Resident chunk membership, with a token for consumers that cache its keys.
use crate::{chunk::Chunk, fast_hash::FxHashMap};
use std::{
collections::hash_map::{Iter, ValuesMut},
ops::Deref,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
};
type Key = (i32, i32);
type Columns = FxHashMap<Key, Arc<Chunk>>;
static NEXT_REVISION: AtomicU64 = AtomicU64::new(1);
fn next_revision() -> u64 {
NEXT_REVISION.fetch_add(1, Ordering::Relaxed)
}
/// Read access behaves like a map. Structural writes are explicit so edits to
/// blocks or light don't invalidate consumers of the loaded chunk key set.
/// Tokens are process-wide: replacing the entire map also invalidates caches.
pub struct ChunkMap {
columns: Columns,
revision: u64,
}
impl Default for ChunkMap {
fn default() -> Self {
Self {
columns: Columns::default(),
revision: next_revision(),
}
}
}
impl ChunkMap {
pub fn membership_revision(&self) -> u64 {
self.revision
}
pub fn insert(&mut self, key: Key, chunk: Arc<Chunk>) -> Option<Arc<Chunk>> {
let previous = self.columns.insert(key, chunk);
if previous.is_none() {
self.revision = next_revision();
}
previous
}
pub fn remove(&mut self, key: &Key) -> Option<Arc<Chunk>> {
let previous = self.columns.remove(key);
if previous.is_some() {
self.revision = next_revision();
}
previous
}
pub fn clear(&mut self) {
if !self.columns.is_empty() {
self.columns.clear();
self.revision = next_revision();
}
}
pub fn get_mut(&mut self, key: &Key) -> Option<&mut Arc<Chunk>> {
self.columns.get_mut(key)
}
pub fn values_mut(&mut self) -> ValuesMut<'_, Key, Arc<Chunk>> {
self.columns.values_mut()
}
}
impl Deref for ChunkMap {
type Target = Columns;
fn deref(&self) -> &Columns {
&self.columns
}
}
impl<'a> IntoIterator for &'a ChunkMap {
type Item = (&'a Key, &'a Arc<Chunk>);
type IntoIter = Iter<'a, Key, Arc<Chunk>>;
fn into_iter(self) -> Self::IntoIter {
self.columns.iter()
}
}
impl crate::light::LightWorld for ChunkMap {
fn state(&self, x: i32, y: i32, z: i32) -> Option<u16> {
self.columns.state(x, y, z)
}
fn light(&self, x: i32, y: i32, z: i32) -> Option<u8> {
self.columns.light(x, y, z)
}
fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) {
self.columns.set_light(x, y, z, packed);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn membership_tokens_track_keys_and_map_replacement_only() {
let mut map = ChunkMap::default();
let empty = map.membership_revision();
map.clear();
map.remove(&(0, 0));
assert_eq!(empty, map.membership_revision());
let chunk = Arc::new(Chunk::empty(0, 0));
map.insert((0, 0), chunk.clone());
let inserted = map.membership_revision();
assert_ne!(empty, inserted);
map.insert((0, 0), chunk.clone());
Arc::make_mut(map.get_mut(&(0, 0)).unwrap()).lit = true;
for column in map.values_mut() {
Arc::make_mut(column).light_loaded = true;
}
crate::light::LightWorld::set_light(&mut map, 0, 0, 0, 0);
assert_eq!(inserted, map.membership_revision());
map.remove(&(0, 0));
map.insert((1, 0), chunk);
assert_eq!(map.len(), 1);
assert_ne!(inserted, map.membership_revision());
let replaced = map.membership_revision();
map.clear();
assert_ne!(replaced, map.membership_revision());
let cleared = map.membership_revision();
map = ChunkMap::default();
assert_ne!(cleared, map.membership_revision());
}
}
+48 -1
View File
@@ -1,4 +1,20 @@
//! Fancy cloud face selection (`CloudRenderer.buildExtrudedCell`).
//! Cloud visibility and flat/fancy cell geometry (`CloudRenderer`).
/// `LevelRenderer`: skip OFF clouds and colors with no packed alpha.
pub fn visible(mode: &str, alpha: f32) -> bool {
mode != "false" && (alpha.clamp(0.0, 1.0) * 255.0) as u8 > 0
}
/// `buildFlatCell`: bottom plane, in both windings for the culled cloud pipeline.
pub fn flat_cell(x: f32, z: f32, bottom: f32) -> [[[f32; 3]; 4]; 2] {
let p = [
[x + 12.0, bottom, z],
[x + 12.0, bottom, z + 12.0],
[x, bottom, z + 12.0],
[x, bottom, z],
];
[p, [p[3], p[2], p[1], p[0]]]
}
/// Direction order is DOWN, UP, NORTH, SOUTH, WEST, EAST; inward faces use bits 6..12.
pub fn face_mask(x: i32, z: i32, bottom: f32, empty: [bool; 4]) -> u16 {
let mut mask = 0;
@@ -55,6 +71,37 @@ pub fn cells(radius: i32) -> impl Iterator<Item = (i32, i32)> {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn settings_and_packed_alpha_gate_clouds() {
for mode in ["false", "fast", "true"] {
assert_eq!(visible(mode, 1.0), mode != "false");
assert!(!visible(mode, 0.0));
assert!(!visible(mode, 0.5 / 255.0));
}
assert!(visible("fast", 1.0 / 255.0));
}
#[test]
fn fast_cells_are_flat_at_the_bottom_and_visible_from_both_sides() {
for bottom in [-10.0, 0.0, 10.0] {
let [down, up] = flat_cell(-3.0, 7.0, bottom);
assert_eq!(
down,
[
[9.0, bottom, 7.0],
[9.0, bottom, 19.0],
[-3.0, bottom, 19.0],
[-3.0, bottom, 7.0],
]
);
assert_eq!(up, [down[3], down[2], down[1], down[0]]);
for (quad, sign) in [(down, -1.0), (up, 1.0)] {
let [a, b, c] = [quad[0], quad[1], quad[2]].map(glam::Vec3::from_array);
assert!((b - a).cross(c - a).y * sign > 0.0);
}
}
}
#[test]
fn cells_are_nearest_first_and_unique() {
let cells: Vec<_> = cells(2).collect();
+39 -10
View File
@@ -10,10 +10,10 @@ use horizon_world::{
block_collision::{BlockCollisionRegistry, DynamicCollisionWorld, ShulkerCollisionState},
block_collision_scan::{BlockCollisionWorld, CollisionBlock},
collision::CachedCollisionRegistry,
collision_context::CollisionContext,
collision_context::{CollisionContext, CollisionEntity, CollisionItem},
dynamic_support::DynamicSupportWorld,
entity_obstruction::EntityIdentity,
fluid::FluidState,
fluid::{FluidKind, FluidState},
liquid_collision::LiquidCollisionWorld,
nbt::{self, Limits},
powder_snow_collision::{PowderSnowEntity, PowderSnowWorld},
@@ -39,8 +39,8 @@ pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result<BlockCollisi
Ok(BlockCollisionRegistry::new(Arc::new(cached))?)
}
/// What powder snow's contextual collision asks of the colliding entity
/// (`PowderSnowBlock.getCollisionShape`).
/// What powder snow's and liquids' contextual collisions ask of the colliding
/// entity (`PowderSnowBlock` and `LiquidBlock.getCollisionShape`).
#[derive(Clone, Copy, Debug, Default)]
pub struct PowderSnowSubject {
pub fall_distance: f64,
@@ -50,6 +50,13 @@ pub struct PowderSnowSubject {
pub leather_boots: bool,
/// `EntityTypeTags.POWDER_SNOW_WALKABLE_MOBS`.
pub walkable_type: bool,
/// A strider: lava sources hold it up (`canStandOnFluid`), on its
/// `getLiquidCollisionShape`.
pub lava_walker: bool,
}
/// `Strider.getLiquidCollisionShape`: `Block.column(16.0, 0.0, 8.0)`.
fn strider_liquid_shape() -> VoxelShape {
VoxelShape::from_cube([1, 2, 1], &[true, false]).expect("a valid half-block column")
}
pub struct SceneCollisions<'w, 'r> {
@@ -60,7 +67,8 @@ pub struct SceneCollisions<'w, 'r> {
}
impl SceneCollisions<'_, '_> {
/// Position contexts permit geometric movement probes without inventing a
/// player, inventory, effects or fluid-standing behavior.
/// player, inventory, effects or fluid-standing behavior; a lava walker
/// collides as the living entity it is, empty-handed.
pub fn resolve(
&mut self,
bounds: Aabb,
@@ -72,7 +80,7 @@ impl SceneCollisions<'_, '_> {
self,
MovementRequest {
entity: EntityIdentity(0),
context: CollisionContext::position(bounds.min_position().y),
context: self.context(bounds),
bounds,
movement,
max_step,
@@ -81,6 +89,21 @@ impl SceneCollisions<'_, '_> {
},
)?)
}
fn context(&self, bounds: Aabb) -> CollisionContext<'static> {
let y = bounds.min_position().y;
if !self.subject.is_some_and(|s| s.lava_walker) {
return CollisionContext::position(y);
}
CollisionContext::for_entity(
CollisionEntity {
identity: EntityIdentity(0),
y,
descending: false,
main_hand: Some(CollisionItem::EMPTY),
},
false,
)
}
pub fn unobstructed(&mut self, bounds: Aabb) -> Result<bool> {
Ok(no_world_collision(
self,
@@ -180,9 +203,13 @@ impl DynamicCollisionWorld for SceneCollisions<'_, '_> {
}
impl LiquidCollisionWorld for SceneCollisions<'_, '_> {
type Error = io::Error;
/// Players and the supported mobs cannot stand on fluids (no striders).
/// Only striders stand on fluids.
fn entity_liquid_shape(&mut self, _: EntityIdentity) -> io::Result<VoxelShape> {
Ok(VoxelShape::empty())
Ok(if self.subject.is_some_and(|s| s.lava_walker) {
strider_liquid_shape()
} else {
VoxelShape::empty()
})
}
fn fluid(&mut self, p: BlockPos) -> io::Result<FluidState> {
FluidState::from_block(
@@ -192,8 +219,10 @@ impl LiquidCollisionWorld for SceneCollisions<'_, '_> {
.ok_or_else(|| io::Error::other("scene fluid state outside registry"))?,
)
}
fn entity_can_stand(&mut self, _: EntityIdentity, _: FluidState) -> io::Result<bool> {
Ok(false)
/// `Strider.canStandOnFluid`: lava.
fn entity_can_stand(&mut self, _: EntityIdentity, fluid: FluidState) -> io::Result<bool> {
Ok(self.subject.is_some_and(|s| s.lava_walker)
&& matches!(fluid.kind(), FluidKind::Lava | FluidKind::FlowingLava))
}
}
impl PowderSnowWorld for SceneCollisions<'_, '_> {
+11 -3
View File
@@ -68,6 +68,8 @@ pub enum BlockEntity {
Crafter(Crafter),
/// `SpawnerBlockEntity` (`crate::mobs::spawner`).
Spawner(Box<crate::mobs::spawner::Spawner>),
/// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`).
Beehive(Box<crate::beehive::Beehive>),
}
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
/// and the ticks left in the crafting animation.
@@ -185,6 +187,9 @@ impl BlockEntity {
if name == "minecraft:spawner" {
return Some(Self::Spawner(Box::default()));
}
if name == "minecraft:beehive" || name == "minecraft:bee_nest" {
return Some(Self::Beehive(Box::default()));
}
if name == "minecraft:lectern" {
return Some(Self::Lectern(Lectern::default()));
}
@@ -261,6 +266,7 @@ impl BlockEntity {
Self::Crafter(_) => "minecraft:crafter",
Self::CreakingHeart(_) => "minecraft:creaking_heart",
Self::Spawner(_) => "minecraft:mob_spawner",
Self::Beehive(_) => "minecraft:beehive",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -270,7 +276,9 @@ impl BlockEntity {
Self::Brewing(b) => b.items.iter().flatten().cloned().collect(),
Self::Sign(_) => Vec::new(),
Self::Jukebox(j) => j.record.iter().cloned().collect(),
Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) => Vec::new(),
Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => {
Vec::new()
}
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
@@ -289,7 +297,7 @@ impl BlockEntity {
| Self::Sculk(_)
| Self::Banner(_) => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_) | Self::Spawner(_) => &[],
Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -304,7 +312,7 @@ impl BlockEntity {
| Self::Sculk(_)
| Self::Banner(_) => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_) | Self::Spawner(_) => &mut [],
Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &mut [],
}
}
}
+28
View File
@@ -150,6 +150,7 @@ pub struct Request {
pub struct Server {
path: PathBuf,
requests: mpsc::Receiver<Request>,
sender: mpsc::Sender<Request>,
}
/// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime
@@ -172,6 +173,7 @@ impl Server {
std::fs::remove_file(path)?;
}
let (sender, requests) = mpsc::channel();
let local = sender.clone();
if uses_tcp(path) {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
let token = random_token();
@@ -204,8 +206,22 @@ impl Server {
Ok(Self {
path: path.to_owned(),
requests,
sender: local,
})
}
/// Commands from inside the process only (`--benchmark` without `--control`).
pub fn local() -> Self {
let (sender, requests) = mpsc::channel();
Self {
path: PathBuf::new(),
requests,
sender,
}
}
/// Sends commands as a socket client would, from another thread.
pub fn sender(&self) -> mpsc::Sender<Request> {
self.sender.clone()
}
pub fn path(&self) -> &Path {
&self.path
}
@@ -424,6 +440,18 @@ impl FrameStats {
self.gpu.extend_from_slice(millis);
}
}
/// Every recorded frame time, in milliseconds, in order.
pub fn frame_millis(&self) -> &[f32] {
&self.millis
}
/// CPU time of every recorded frame, in milliseconds.
pub fn cpu_millis(&self) -> &[f32] {
&self.cpu
}
/// GPU time of every frame the GPU timed, in milliseconds.
pub fn gpu_millis(&self) -> &[f32] {
&self.gpu
}
pub fn reset(&mut self) {
self.millis.clear();
self.cpu.clear();
+15 -7
View File
@@ -1,7 +1,8 @@
//! Crash reports, laid out like vanilla's CrashReport.getFriendlyReport: a comment, the time,
//! a description, the error with its stack, then the details of the game and the machine.
//! Written to `crash-reports/crash-<yyyy-MM-dd_HH.mm.ss>-client.txt` in the game folder when
//! the main thread panics or `main` gets an error back. Nothing is sent anywhere.
//! the main thread panics or `main` gets an error back. It leaves the machine only scrubbed, and
//! only if the player allows crash reports (`telemetry`).
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
@@ -104,8 +105,18 @@ impl Report {
}
}
/// The release tag (the launcher installs each build in a folder named after it) and the client's
/// own version, or just the latter.
pub fn version() -> String {
let version = env!("CARGO_PKG_VERSION");
match release_tag() {
Some(tag) => format!("{tag} (client {version})"),
None => version.to_owned(),
}
}
/// The release this binary came with: launcher installs live in a folder named after the tag.
fn release_tag() -> Option<String> {
pub fn release_tag() -> Option<String> {
let exe = std::env::current_exe().ok()?;
let folder = exe.parent()?.file_name()?.to_str()?;
(folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit()))
@@ -227,12 +238,8 @@ fn memory() -> String {
/// The report's details: Horizon's and the machine's, then what the game set as it ran.
pub fn system_details() -> Vec<(String, String)> {
let mut version = env!("CARGO_PKG_VERSION").to_owned();
if let Some(tag) = release_tag() {
version = format!("{tag} (client {version})");
}
let mut out = vec![
("Horizon Version".to_owned(), version),
("Horizon Version".to_owned(), version()),
("Minecraft Version".to_owned(), "26.3".to_owned()),
("Operating System".to_owned(), operating_system()),
("CPU".to_owned(), cpu()),
@@ -270,6 +277,7 @@ fn deliver(home: &Path, report: Report) -> Option<PathBuf> {
),
);
crate::logging::flush();
crate::telemetry::keep_crash(home, &report);
match report.save(home) {
Ok(path) => {
eprintln!("Horizon: crash report saved to {}", path.display());
+579
View File
@@ -0,0 +1,579 @@
//! The debug charts (26.3 `debugchart`): F3+2 shows the frame times and, in
//! single player, the integrated server's tick times; F3+3 the ping and, on a
//! remote server, the bandwidth. Each chart keeps the last 240 samples
//! (`LocalSampleLogger`) and draws one bar per sample over a 60 pixel high
//! box (`AbstractDebugChart`).
use crate::{
font::Font,
hud_layout::{GuiDraw, argb, fill},
text::Text,
};
use std::{
collections::VecDeque,
time::{Duration, Instant},
};
/// `LocalSampleLogger.CAPACITY`.
pub const CAPACITY: usize = 240;
/// `AbstractDebugChart.CHART_HEIGHT`.
pub const CHART_HEIGHT: i32 = 60;
/// `TpsDebugDimensions`: a tick sample's values.
pub const FULL_TICK: usize = 0;
pub const TICK_SERVER_METHOD: usize = 1;
pub const SCHEDULED_TASKS: usize = 2;
pub const IDLE: usize = 3;
/// `LocalSampleLogger`: the last [`CAPACITY`] samples, oldest first; a
/// sample has up to four values (`TpsDebugDimensions`), the first the main.
#[derive(Clone, Debug, Default)]
pub struct SampleLogger {
samples: VecDeque<[i64; 4]>,
}
impl SampleLogger {
/// `logSample`.
pub fn log(&mut self, value: i64) {
self.log_full([value, 0, 0, 0]);
}
/// `logFullSample`.
pub fn log_full(&mut self, sample: [i64; 4]) {
if self.samples.len() == CAPACITY {
self.samples.pop_front();
}
self.samples.push_back(sample);
}
pub fn len(&self) -> usize {
self.samples.len()
}
pub fn is_empty(&self) -> bool {
self.samples.is_empty()
}
pub fn reset(&mut self) {
self.samples.clear();
}
fn get(&self, index: usize, dimension: usize) -> i64 {
self.samples[index][dimension]
}
}
/// `DebugScreenOverlay`'s chart switches and the samples behind them.
#[derive(Clone, Debug, Default)]
pub struct DebugCharts {
/// `renderFpsCharts` (F3+2).
pub fps: bool,
/// `renderNetworkCharts` (F3+3).
pub network: bool,
/// `renderLightmapTexture` (F3+4).
pub lightmap: bool,
/// `frameTimeLogger`: nanoseconds between frames.
pub frame_times: SampleLogger,
/// `tickTimeLogger`: the integrated server's ticks.
pub tick_times: SampleLogger,
/// `pingLogger`: milliseconds.
pub ping: SampleLogger,
/// `bandwidthLogger`: bytes received per tick.
pub bandwidth: SampleLogger,
previous_tick: Option<Instant>,
bytes_seen: Option<i64>,
}
impl DebugCharts {
/// `toggleFpsCharts`; `overlay` is the debug overlay's visibility.
pub fn toggle_fps(&mut self, overlay: &mut bool) {
self.fps = !*overlay || !self.fps;
if self.fps {
*overlay = true;
self.network = false;
self.lightmap = false;
}
}
/// `toggleNetworkCharts`.
pub fn toggle_network(&mut self, overlay: &mut bool) {
self.network = !*overlay || !self.network;
if self.network {
*overlay = true;
self.fps = false;
self.lightmap = false;
}
}
/// `toggleLightmapTexture`.
pub fn toggle_lightmap(&mut self, overlay: &mut bool) {
self.lightmap = !*overlay || !self.lightmap;
if self.lightmap {
*overlay = true;
self.fps = false;
self.network = false;
}
}
/// `reset`: leaving a world.
pub fn reset(&mut self) {
self.tick_times.reset();
self.ping.reset();
self.bandwidth.reset();
self.previous_tick = None;
self.bytes_seen = None;
}
/// One integrated server tick that started at `started` and ran its
/// tick method for `method` (`MinecraftServer.logFullTickTime` and
/// `logTickMethodTime`): the full tick runs from one start to the next,
/// and what the tick method leaves of it is idle.
pub fn log_tick(&mut self, started: Instant, method: Duration) {
let method = method.as_nanos() as i64;
let full = self
.previous_tick
.map_or(method, |p| (started - p).as_nanos() as i64)
.max(method);
self.previous_tick = Some(started);
self.tick_times.log_full([full, method, 0, full - method]);
}
/// `BandwidthDebugMonitor.tick`: the bytes received since the last
/// tick, from the connection's running total.
pub fn log_bandwidth(&mut self, total: i64) {
if let Some(seen) = self.bytes_seen {
self.bandwidth.log(total - seen);
}
self.bytes_seen = Some(total);
}
/// The charts along the bottom of the screen (`extractRenderState`):
/// frame times left and tick times right, or bandwidth left (remote
/// servers only) and ping right. `mspt` is the level's milliseconds
/// per tick.
pub fn draw(
&self,
font: &Font,
width: i32,
height: i32,
framerate_limit: u32,
mspt: f32,
remote: bool,
) -> Vec<GuiDraw> {
let mut out = Vec::new();
let max_width = width / 2;
let chart_width = Chart::width(max_width);
if self.fps {
let fps = Chart::Fps { framerate_limit };
out.extend(fps.draw(font, &self.frame_times, 0, chart_width, height));
if !self.tick_times.is_empty() {
let tps = Chart::Tps { mspt };
out.extend(tps.draw(
font,
&self.tick_times,
width - chart_width,
chart_width,
height,
));
}
}
if self.network {
if remote {
out.extend(Chart::Bandwidth.draw(font, &self.bandwidth, 0, chart_width, height));
}
out.extend(Chart::Ping.draw(
font,
&self.ping,
width - chart_width,
chart_width,
height,
));
}
out
}
}
/// The lightmap view (`showLightmapTexture`): the 16 by 16 texture at 64
/// by 64 in the bottom right corner on a black border, sky light up and
/// block light right (the blit flips the texture's rows). `pixels` are RGBA
/// rows of sky level by block level.
pub fn lightmap(pixels: &[u8; 16 * 16 * 4], width: i32, height: i32) -> Vec<GuiDraw> {
let (x, y) = (width - 64 - 2, height - 64 - 2);
let mut out = vec![fill(x - 1, y - 1, x + 64 + 1, y + 64 + 1, 0xFF00_0000)];
for (i, p) in pixels.as_chunks::<4>().0.iter().enumerate() {
let (sky, block) = ((i / 16) as i32, (i % 16) as i32);
let color = argb(255, u32::from(p[0]), u32::from(p[1]), u32::from(p[2]));
let (cx, cy) = (x + block * 4, y + (15 - sky) * 4);
out.push(fill(cx, cy, cx + 4, cy + 4, color));
}
out
}
/// The four charts and what each needs to scale its bars.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Chart {
/// `FpsDebugChart`: frame durations in nanoseconds; the frame rate limit
/// option (`maxFps`).
Fps { framerate_limit: u32 },
/// `TpsDebugChart`: tick samples in nanoseconds; the level's
/// milliseconds per tick.
Tps { mspt: f32 },
/// `PingDebugChart`: round trips in milliseconds.
Ping,
/// `BandwidthDebugChart`: bytes received per tick.
Bandwidth,
}
/// The labels' colour and the backdrop of the box and shaded labels.
const LABEL: u32 = 0xFFE0_E0E0;
const BACKDROP: u32 = 0x9050_5050;
const WHITE: u32 = 0xFFFF_FFFF;
const GREEN: u32 = 0xFF00_FF00;
const YELLOW: u32 = 0xFFFF_FF00;
const RED: u32 = 0xFFFF_0000;
const CYAN: u32 = 0xFF00_FFFF;
/// `BandwidthDebugChart.MID_COLOR`.
const LAVENDER: u32 = 0xFFA0_A0FF;
/// `TpsDebugChart`'s bar parts.
const TICK_METHOD_COLOR: u32 = 0xFF99_1111;
const TASK_COLOR: u32 = 0xFFBA_995F;
const OTHER_COLOR: u32 = 0xFF5F_0E8C;
const MEGABYTE: f64 = 1_048_576.0;
impl Chart {
/// `AbstractDebugChart.getWidth`.
pub fn width(max_width: i32) -> i32 {
(CAPACITY as i32 + 2).min(max_width)
}
/// `getFullHeight`: the box and the min/avg/max line above it.
pub fn full_height() -> i32 {
CHART_HEIGHT + 9
}
/// `AbstractDebugChart.extractRenderState`.
pub fn draw(
self,
font: &Font,
samples: &SampleLogger,
left: i32,
width: i32,
bottom: i32,
) -> Vec<GuiDraw> {
let mut out = vec![fill(
left,
bottom - CHART_HEIGHT,
left + width,
bottom,
BACKDROP,
)];
let (mut sum, mut min, mut max) = (0i64, i64::from(i32::MAX), i64::from(i32::MIN));
let start = CAPACITY.saturating_sub((width - 2).max(0) as usize);
let count = samples.len().saturating_sub(start);
for i in 0..count {
let x = left + i as i32 + 1;
let index = start + i;
let value = self.aggregated(samples, index);
min = min.min(value);
max = max.max(value);
sum += value;
self.bars(&mut out, samples, bottom, x, index);
}
horizontal_line(
&mut out,
left,
left + width - 1,
bottom - CHART_HEIGHT,
WHITE,
);
horizontal_line(&mut out, left, left + width - 1, bottom - 1, WHITE);
vertical_line(&mut out, left, bottom - CHART_HEIGHT, bottom, WHITE);
vertical_line(
&mut out,
left + width - 1,
bottom - CHART_HEIGHT,
bottom,
WHITE,
);
if count > 0 {
let y = bottom - CHART_HEIGHT - 9;
let min_text = format!("{} min", self.display(min as f64));
let avg_text = format!("{} avg", self.display(sum as f64 / count as f64));
let max_text = format!("{} max", self.display(max as f64));
text(&mut out, min_text, left + 2, y, LABEL, true);
let avg_x = left + width / 2 - font.width(&avg_text) as i32 / 2;
text(&mut out, avg_text, avg_x, y, LABEL, true);
let max_x = left + width - font.width(&max_text) as i32 - 2;
text(&mut out, max_text, max_x, y, LABEL, true);
}
self.lines_and_labels(&mut out, font, left, width, bottom);
out
}
fn bars(
self,
out: &mut Vec<GuiDraw>,
samples: &SampleLogger,
bottom: i32,
x: i32,
index: usize,
) {
let value = samples.get(index, 0);
let height = self.height(value as f64);
out.push(fill(x, bottom - height, x + 1, bottom, self.color(value)));
if let Chart::Tps { .. } = self {
let method = samples.get(index, TICK_SERVER_METHOD);
let method_h = self.height(method as f64);
out.push(fill(x, bottom - method_h, x + 1, bottom, TICK_METHOD_COLOR));
let tasks = samples.get(index, SCHEDULED_TASKS);
let tasks_h = self.height(tasks as f64);
out.push(fill(
x,
bottom - method_h - tasks_h,
x + 1,
bottom - method_h,
TASK_COLOR,
));
let other = value - samples.get(index, IDLE) - method - tasks;
let other_h = self.height(other as f64);
out.push(fill(
x,
bottom - other_h - tasks_h - method_h,
x + 1,
bottom - tasks_h - method_h,
OTHER_COLOR,
));
}
}
/// `getValueForAggregation`: a tick's time without its idle part.
fn aggregated(self, samples: &SampleLogger, index: usize) -> i64 {
match self {
Chart::Tps { .. } => samples.get(index, 0) - samples.get(index, IDLE),
_ => samples.get(index, 0),
}
}
/// `extractAdditionalLinesAndLabels`.
fn lines_and_labels(
self,
out: &mut Vec<GuiDraw>,
font: &Font,
left: i32,
width: i32,
bottom: i32,
) {
match self {
Chart::Fps { framerate_limit } => {
shaded(out, font, "30 fps", left + 1, bottom - CHART_HEIGHT + 1);
shaded(out, font, "60 fps", left + 1, bottom - 30 + 1);
horizontal_line(out, left, left + width - 1, bottom - 30, WHITE);
if framerate_limit > 0 && framerate_limit <= 250 {
let y = bottom - self.height(1.0e9 / f64::from(framerate_limit)) - 1;
horizontal_line(out, left, left + width - 1, y, CYAN);
}
}
Chart::Tps { mspt } => {
let tps = 1000.0 / mspt;
shaded(
out,
font,
&format!("{tps:.1} tps"),
left + 1,
bottom - CHART_HEIGHT + 1,
);
}
Chart::Ping => shaded(out, font, "500 ms", left + 1, bottom - CHART_HEIGHT + 1),
Chart::Bandwidth => {
for bytes in [64.0, 1024.0, 16384.0] {
let y = bottom - bandwidth_height(bytes);
shaded(out, font, &bandwidth_display(bytes), left + 1, y + 1);
horizontal_line(out, left, left + width - 1, y, WHITE);
}
let y = bottom - bandwidth_height(MEGABYTE) + 1;
shaded(out, font, &bandwidth_display(MEGABYTE), left + 1, y);
}
}
}
/// `toDisplayString`.
fn display(self, sample: f64) -> String {
match self {
Chart::Fps { .. } | Chart::Tps { .. } => format!("{} ms", java_round(sample / 1.0e6)),
Chart::Ping => format!("{} ms", java_round(sample)),
Chart::Bandwidth => bandwidth_display(sample * 20.0),
}
}
/// `getSampleHeight`.
fn height(self, sample: f64) -> i32 {
match self {
Chart::Fps { .. } => java_round(sample / 1.0e6 * 60.0 / 33.333333333333336) as i32,
Chart::Tps { mspt } => java_round(sample / 1.0e6 * 60.0 / f64::from(mspt)) as i32,
Chart::Ping => java_round(sample * 60.0 / 500.0) as i32,
Chart::Bandwidth => bandwidth_height(sample * 20.0),
}
}
/// `getSampleColor`.
fn color(self, sample: i64) -> u32 {
let s = sample as f64;
match self {
Chart::Fps { .. } => gradient(s / 1.0e6, 0.0, GREEN, 28.0, YELLOW, 56.0, RED),
Chart::Tps { mspt } => {
let m = f64::from(mspt);
gradient(s / 1.0e6, m, GREEN, m * 1.125, YELLOW, m * 1.25, RED)
}
Chart::Ping => gradient(s, 0.0, GREEN, 250.0, YELLOW, 500.0, RED),
Chart::Bandwidth => gradient(s * 20.0, 0.0, CYAN, 8192.0, LAVENDER, 1.048576e7, RED),
}
}
}
/// `BandwidthDebugChart.toDisplayStringInternal`.
fn bandwidth_display(bytes_per_second: f64) -> String {
if bytes_per_second >= MEGABYTE {
format!("{:.1} MiB/s", bytes_per_second / MEGABYTE)
} else if bytes_per_second >= 1024.0 {
format!("{:.1} KiB/s", bytes_per_second / 1024.0)
} else {
format!("{} B/s", bytes_per_second.floor() as i64)
}
}
/// `BandwidthDebugChart.getSampleHeightInternal`: logarithmic, 1 MiB/s at
/// the top.
fn bandwidth_height(bytes_per_second: f64) -> i32 {
java_round((bytes_per_second + 1.0).ln() * 60.0 / MEGABYTE.ln()) as i32
}
/// `Math.round(double)`: halves round up.
fn java_round(v: f64) -> i64 {
(v + 0.5).floor() as i64
}
/// `AbstractDebugChart.getSampleColor(sample, min, minColor, mid, ...)`.
fn gradient(
sample: f64,
min: f64,
min_color: u32,
mid: f64,
mid_color: u32,
max: f64,
max_color: u32,
) -> u32 {
let sample = sample.clamp(min, max);
if sample < mid {
srgb_lerp(((sample - min) / (mid - min)) as f32, min_color, mid_color)
} else {
srgb_lerp(((sample - mid) / (max - mid)) as f32, mid_color, max_color)
}
}
/// `ARGB.srgbLerp`: each channel by `Mth.lerpInt`.
fn srgb_lerp(alpha: f32, p0: u32, p1: u32) -> u32 {
let channel = |shift: u32| {
let (a, b) = (((p0 >> shift) & 255) as i32, ((p1 >> shift) & 255) as i32);
(a + (alpha * (b - a) as f32).floor() as i32) as u32
};
argb(channel(24), channel(16), channel(8), channel(0))
}
/// `GuiGraphicsExtractor.horizontalLine`.
fn horizontal_line(out: &mut Vec<GuiDraw>, x0: i32, x1: i32, y: i32, color: u32) {
out.push(fill(x0.min(x1), y, x0.max(x1) + 1, y + 1, color));
}
/// `GuiGraphicsExtractor.verticalLine`.
fn vertical_line(out: &mut Vec<GuiDraw>, x: i32, y0: i32, y1: i32, color: u32) {
out.push(fill(x, y0.min(y1) + 1, x + 1, y0.max(y1), color));
}
fn text(out: &mut Vec<GuiDraw>, s: String, x: i32, y: i32, color: u32, shadow: bool) {
out.push(GuiDraw::Text {
text: Text::literal(s),
x,
y,
color,
shadow,
});
}
/// `extractStringWithShade`: a label on a dark backdrop, without shadow.
fn shaded(out: &mut Vec<GuiDraw>, font: &Font, s: &str, x: i32, y: i32) {
out.push(fill(x, y, x + font.width(s) as i32 + 1, y + 9, BACKDROP));
text(out, s.to_owned(), x + 1, y + 1, LABEL, false);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_logger_keeps_the_last_240_samples() {
let mut l = SampleLogger::default();
for i in 0..300 {
l.log(i);
}
assert_eq!(l.len(), CAPACITY);
assert_eq!(l.get(0, 0), 60);
assert_eq!(l.get(CAPACITY - 1, 0), 299);
}
#[test]
fn chart_toggles_show_the_overlay_and_exclude_each_other() {
let mut c = DebugCharts::default();
let mut overlay = false;
c.toggle_fps(&mut overlay);
assert!(overlay && c.fps);
c.toggle_network(&mut overlay);
assert!(c.network && !c.fps);
c.toggle_network(&mut overlay);
assert!(!c.network && overlay);
c.toggle_lightmap(&mut overlay);
c.toggle_fps(&mut overlay);
assert!(c.fps && !c.lightmap);
// With the overlay hidden, the key shows it again with the chart on.
c.toggle_fps(&mut overlay);
overlay = false;
c.toggle_fps(&mut overlay);
assert!(overlay && c.fps);
}
#[test]
fn the_lightmap_puts_full_sky_light_at_the_top_left() {
let mut pixels = [0u8; 16 * 16 * 4];
// Sky 15, block 0: the last row's first texel.
pixels[15 * 64..15 * 64 + 4].copy_from_slice(&[10, 20, 30, 255]);
let draws = lightmap(&pixels, 427, 240);
assert_eq!(draws[0], fill(360, 173, 426, 239, 0xFF00_0000));
assert_eq!(draws.len(), 257);
assert!(draws.contains(&fill(361, 174, 365, 178, 0xFF0A_141E)));
}
#[test]
fn ticks_and_bandwidth_log_their_differences() {
let mut c = DebugCharts::default();
let t0 = Instant::now();
c.log_tick(t0, Duration::from_millis(5));
c.log_tick(t0 + Duration::from_millis(50), Duration::from_millis(7));
assert_eq!(
c.tick_times.samples[1],
[50_000_000, 7_000_000, 0, 43_000_000]
);
c.log_bandwidth(1000);
c.log_bandwidth(1600);
assert_eq!(c.bandwidth.len(), 1);
assert_eq!(c.bandwidth.get(0, 0), 600);
}
#[test]
fn heights_match_vanilla_scales() {
let fps = Chart::Fps {
framerate_limit: 260,
};
// 33.3 ms (30 fps) fills the chart; 16.7 ms half of it.
assert_eq!(fps.height(33_333_333.0), 60);
assert_eq!(fps.height(16_666_667.0), 30);
let tps = Chart::Tps { mspt: 50.0 };
assert_eq!(tps.height(25e6), 30);
assert_eq!(Chart::Ping.height(250.0), 30);
// 1 MiB/s at the top; 52 bytes per tick is 1 KiB/s.
assert_eq!(bandwidth_height(MEGABYTE), 60);
assert_eq!(Chart::Bandwidth.height(51.2), 30);
}
#[test]
fn labels_match_vanilla_formats() {
assert_eq!(
Chart::Fps { framerate_limit: 0 }.display(16_500_000.0),
"17 ms"
);
assert_eq!(Chart::Ping.display(12.4), "12 ms");
assert_eq!(Chart::Bandwidth.display(3.0), "60 B/s");
assert_eq!(Chart::Bandwidth.display(100.0), "2.0 KiB/s");
assert_eq!(bandwidth_display(MEGABYTE), "1.0 MiB/s");
}
#[test]
fn colours_go_green_yellow_red() {
let fps = Chart::Fps { framerate_limit: 0 };
assert_eq!(fps.color(0), GREEN);
assert_eq!(fps.color(28_000_000), YELLOW);
assert_eq!(fps.color(100_000_000), RED);
// Halfway between green and yellow: Mth.lerpInt floors.
assert_eq!(fps.color(14_000_000), 0xFF7F_FF00);
let tps = Chart::Tps { mspt: 50.0 };
assert_eq!(tps.color(10_000_000), GREEN);
assert_eq!(Chart::Bandwidth.color(0), CYAN);
}
}
+17
View File
@@ -433,6 +433,23 @@ mod tests {
assert_eq!(h.overlay, 0);
}
#[test]
fn switcher_modifier_release_does_not_toggle_the_debug_overlay() {
let (mut k, mut h, mut b) = (DebugKeys::default(), Host::default(), KeyBinds::default());
// Screen release handling must also work with rebound debug keys.
b.set("key.debug.modifier", "key.keyboard.f7");
b.set("key.debug.overlay", "key.keyboard.f7");
b.set("key.debug.switchGameMode", "key.keyboard.f8");
press(&mut k, &mut h, &b, "key.keyboard.f7", 0);
assert!(!press(&mut k, &mut h, &b, "key.keyboard.f8", 1));
assert_eq!(h.actions, [(DebugAction::SwitchGameMode, false)]);
h.screen = Some(OpenScreen::GameModeSwitcher);
release(&mut k, &mut h, &b, "key.keyboard.f8");
release(&mut k, &mut h, &b, "key.keyboard.f7");
assert!(!k.modifier_down);
assert_eq!(h.overlay, 0);
}
#[test]
fn a_separate_overlay_key_toggles_on_press() {
let (mut k, mut h, mut b) = (DebugKeys::default(), Host::default(), KeyBinds::default());
+14 -1
View File
@@ -309,6 +309,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
map.insert("equipment".into(), Tag::Compound(equipment));
}
"minecraft:bat" => {
map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag)));
}
"minecraft:creaking" => {
// home_pos: the heart it is bound to.
if let Some(home) = m.extra.home {
@@ -386,6 +389,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
crate::mobs::nautilus::to_nbt(m, map);
}
"minecraft:sulfur_cube" => crate::mobs::sulfur_cube::to_nbt(m, map),
"minecraft:bee" => crate::mobs::bee::to_nbt(m, map),
"minecraft:sniffer" => crate::mobs::sniffer::to_nbt(m, map),
"minecraft:wither" => {
map.insert("Invul".into(), Tag::Int(m.extra.counter));
@@ -597,7 +601,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.main_hand = None;
}
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
m.persistent |= flag(tag, "PersistenceRequired");
// Mob.readAdditionalSaveData overrides what the constructor set (copper
// golems and elder guardians start persistent).
m.persistent = flag(tag, "PersistenceRequired");
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
m.custom_name = custom_name(tag);
if m.kind.category == "creature" {
@@ -612,6 +618,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32;
m.silent = flag(tag, "Silent");
m.invulnerable_flag = flag(tag, "Invulnerable");
if m.species() == crate::mobs::Species::Bat {
// Bat.readAdditionalSaveData: BatFlags bit 0, resting.
m.extra.flag = number(tag.get("BatFlags")).unwrap_or(0) & 1 != 0;
}
if m.species() == crate::mobs::Species::Creeper {
m.extra.charged = flag(tag, "powered");
// Creeper.readAdditionalSaveData: `ignited` lights the fuse.
@@ -761,6 +771,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
if m.species() == crate::mobs::Species::SulfurCube {
crate::mobs::sulfur_cube::from_nbt(&mut m, tag);
}
if m.species() == crate::mobs::Species::Bee {
crate::mobs::bee::from_nbt(&mut m, tag);
}
if m.species() == crate::mobs::Species::Creaking
&& let Some(Tag::IntArray(home)) = tag.get("home_pos")
&& home.len() == 3
+240 -13
View File
@@ -33,6 +33,7 @@ const MAKE: u64 = id("create.make", 0);
const SERVER: u64 = id("mp.row", 0);
const JOIN: u64 = id("mp.join", 0);
const DIRECT: u64 = id("mp.direct", 0);
const FRIEND: u64 = id("mp.friend", 0);
const ADD: u64 = id("mp.add", 0);
const EDIT: u64 = id("mp.edit", 0);
const DELETE: u64 = id("mp.delete", 0);
@@ -108,7 +109,7 @@ impl Title {
/// live backdrop is visible (0 shows the plain cold background).
pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) {
if classic(&self.mode) {
self.draw(ui.atlas, ui.batch, ui.cursor);
self.draw(ui.atlas, ui.batch, ui.cursor, false);
return;
}
let reveal = self.opening_phase(backdrop >= 1.0);
@@ -153,6 +154,7 @@ impl Title {
seed,
creative,
focus,
..
} => {
let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
create_page(ui, x, w, name, seed, *creative, *focus, caret);
@@ -378,14 +380,7 @@ impl Title {
};
}
}
CREATE => {
self.mode = Mode::Create {
name: "New World".into(),
seed: String::new(),
creative: false,
focus: 0,
}
}
CREATE => self.mode = Title::new_world(),
DELETE_WORLD => {
if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() {
self.mode = Mode::Delete { world };
@@ -435,6 +430,7 @@ impl Title {
let id = match hit {
JOIN => Some(40),
DIRECT => Some(41),
FRIEND => Some(47),
ADD => Some(42),
EDIT => Some(43),
DELETE => Some(44),
@@ -443,15 +439,17 @@ impl Title {
Screen::List { .. } => 46,
Screen::Edit { .. } => 51,
Screen::Direct { .. } => 53,
Screen::Friend { .. } => 57,
Screen::Disconnected { .. } => 54,
}),
CANCEL_RETRY => Some(55),
DONE => Some(match screen {
Screen::Direct { .. } => 52,
Screen::Friend { .. } => 56,
_ => 50,
}),
FIELD_A | FIELD_B => {
if let Screen::Edit { focus, .. } = screen {
if let Screen::Edit { focus, .. } | Screen::Friend { focus, .. } = screen {
*focus = u8::from(hit == FIELD_B);
}
None
@@ -484,6 +482,25 @@ impl Title {
}
}
/// The end of `text` that fits `width`, led by an ellipsis when cut.
fn tail_fit(ui: &Ui, text: &str, width: f32) -> String {
if ui.measure(Face::Regular, BODY, text) <= width {
return text.to_owned();
}
let chars: Vec<char> = text.chars().collect();
let mut start = 0;
while start < chars.len() {
let tail: String = std::iter::once('…')
.chain(chars[start..].iter().copied())
.collect();
if ui.measure(Face::Regular, BODY, &tail) <= width {
return tail;
}
start += 1;
}
String::new()
}
/// The page header plus a row of actions under it; returns the y below.
fn header(ui: &mut Ui, x: f32, title: &str, description: &str) -> f32 {
let y = 36.0;
@@ -791,6 +808,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
selected,
pings,
lan,
..
} => {
let games = lan.games();
let sub = match servers.len() {
@@ -803,6 +821,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
let saved = selected.is_some_and(|i| i < servers.len());
let mut items = vec![
(JOIN, "Join", Kind::Primary, has),
(FRIEND, "Join a friend", Kind::Secondary, true),
(ADD, "Add server", Kind::Secondary, true),
(DIRECT, "Direct connect", Kind::Secondary, true),
(REFRESH, "Refresh", Kind::Ghost, true),
@@ -955,6 +974,67 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
);
ui.divider(x, y + rh, w);
}
Screen::Friend { code, relay, focus } => {
let y = header(
ui,
x,
"Join a friend",
"Paste the invite code your friend sees in their pause menu.",
);
let parsed = horizon_friends::invite::parse_detailed(code);
let ok = parsed.is_ok();
actions_right(
ui,
x + w,
y - 24.0 - 58.0,
&[
(DONE, "Join", Kind::Primary, ok),
(BACK, "Cancel", Kind::Ghost, true),
],
);
ui.divider(x, y, w);
let rh = 12.0 + CONTROL + 12.0;
let fx = x + t::ROW_LABEL + 16.0;
let fw = w - t::ROW_LABEL - 16.0;
let rows = [
(FIELD_A, "Invite code", code, "Paste the code here", fw),
(
FIELD_B,
"Relay (optional)",
relay,
"host:port, for short codes",
fw.min(360.0),
),
];
let mut ry = y;
for (i, (fid, label, value, hint, width)) in rows.into_iter().enumerate() {
ui.text_line(Face::Regular, BODY, rh, x, ry, color::MUTED, label);
// A long code shows its end, where the typing is.
let shown = tail_fit(ui, value, width - 28.0);
ui.field(
fid,
[fx, ry + 12.0, width, CONTROL],
&shown,
hint,
usize::from(*focus) == i,
caret,
);
ry += rh;
ui.divider(x, ry, w);
}
let note = match parsed {
_ if code.trim().is_empty() => None,
Err(e) => Some(e.to_string()),
Ok(horizon_friends::invite::Parsed::Short(_)) if relay.trim().is_empty() => Some(
"This is a relay's short code: fill in your friend's relay above, or ask for the full code."
.to_owned(),
),
Ok(_) => None,
};
if let Some(note) = note {
ui.text(Face::Regular, SMALL, x, ry + 12.0, color::MUTED, &note);
}
}
Screen::Disconnected { reason, retry } => {
let mut y = header(
ui,
@@ -1018,12 +1098,39 @@ pub fn wrap(ui: &Ui, text: &str, width: f32) -> Vec<String> {
/// blurred world, with the game's actions as a page. Ids match
/// `game/screens.rs`'s PauseScreen actions: 0 back to game, 1 options,
/// 2 save and quit, 3 statistics, 4 advancements, 9 world options.
/// Play with friends as the pause menu shows it (game/friends.rs fills it).
#[derive(Clone, Debug, Default)]
pub struct FriendsView {
/// A singleplayer world (not a server): the button 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,
}
pub mod pause {
use super::*;
fn act(a: u8) -> u64 {
id("pause", u64::from(a))
}
pub fn draw(ui: &mut Ui, world: &str, quit_label: &str, opened: Instant) {
pub fn draw(
ui: &mut Ui,
world: &str,
quit_label: &str,
opened: Instant,
friends: &FriendsView,
) {
let (w, h) = (ui.w, ui.h);
let p = t::ease_out_quint(opened.elapsed().as_secs_f32() / t::move_());
ui.opacity = p;
@@ -1065,8 +1172,21 @@ pub mod pause {
Kind::Secondary,
true,
);
if friends.shown {
let iw = ui.button_width("Invite friends", true);
ui.button(
act(10),
[x + bw + lw + 16.0, y, iw, CONTROL_LARGE],
"Invite friends",
Kind::Secondary,
!friends.sharing,
);
}
y += CONTROL_LARGE + 32.0;
ui.row_index = 0;
if friends.sharing {
y = invite(ui, x, y, cw, friends);
}
ui.divider(x, y, cw);
let rh = ui.row(
x,
@@ -1088,6 +1208,109 @@ pub mod pause {
ui.opacity = 1.0;
ui.offset = (0.0, 0.0);
}
/// The invite section while sharing: the code with Copy and Stop
/// sharing, who is here, and what changed. Returns the y below it.
/// The code's groups packed into lines of at most `width`.
fn code_lines(ui: &Ui, 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 ui.measure(Face::Mono, BODY, &format!("{l}-{group}")) <= width => {
l.push('-');
l.push_str(group);
}
_ => lines.push(group.to_owned()),
}
}
lines
}
fn invite(ui: &mut Ui, x: f32, mut y: f32, cw: f32, f: &FriendsView) -> f32 {
ui.divider(x, y, cw);
let top = y + 12.0;
ui.text(
Face::Regular,
BODY,
x,
top + 6.0,
color::MUTED,
"Invite code",
);
let vx = x + t::ROW_LABEL + 16.0;
let stop = "Stop sharing";
let sw = ui.button_width(stop, false);
ui.button(
act(12),
[x + cw - sw, top, sw, CONTROL],
stop,
Kind::Danger,
true,
);
let copy = if f.copied { "Copied" } else { "Copy" };
let copy_w = ui.button_width("Copied", false);
let buttons = sw + 8.0 + copy_w;
ui.button(
act(11),
[x + cw - buttons, top, copy_w, CONTROL],
copy,
Kind::Secondary,
f.code.is_some(),
);
let line = (BODY * 1.45).round();
let value_w = (cw - t::ROW_LABEL - 16.0 - buttons - 16.0).max(120.0);
y = top + 6.0;
match &f.code {
Some(code) => {
for l in code_lines(ui, code, value_w) {
ui.text(Face::Mono, BODY, vx, y, color::TEXT, &l);
y += line;
}
}
None => {
for l in wrap(ui, &f.status, value_w) {
ui.text(Face::Regular, BODY, vx, y, color::MUTED, &l);
y += line;
}
}
}
y = y.max(top + CONTROL) + 10.0;
let small = (SMALL * 1.45).round();
if f.code.is_some() {
// Who can join: plain when friends anywhere can, in the text
// colour (it asks for something) when only the LAN and VPNs can.
let tint = if f.reachable {
color::MUTED
} else {
color::TEXT
};
for l in wrap(ui, &f.status, cw) {
ui.text(Face::Regular, SMALL, x, y, tint, &l);
y += small;
}
if let Some(help) = &f.help {
let l = ui.fit(Face::Regular, SMALL, &format!("Help: {help}"), cw);
ui.text(Face::Regular, SMALL, x, y, color::FAINT, &l);
y += small;
}
}
let here = if f.guests.is_empty() {
"No friends here yet.".to_owned()
} else {
format!("Here now: {}", f.guests.join(", "))
};
let hint =
"Friends paste the code in Multiplayer, Join a friend, or on the launcher's Play page.";
let lines = [
Some((here, color::MUTED)),
f.notice.clone().map(|n| (n, color::MUTED)),
Some((hint.to_owned(), color::FAINT)),
];
for (line, tint) in lines.into_iter().flatten() {
let line = ui.fit(Face::Regular, SMALL, &line, cw);
ui.text(Face::Regular, SMALL, x, y, tint, &line);
y += small;
}
y + 12.0
}
/// The PauseScreen action under a click, if any.
pub fn click(
atlas: &HudAtlas,
@@ -1096,6 +1319,7 @@ pub mod pause {
y: f32,
world: &str,
quit_label: &str,
friends: &FriendsView,
) -> Option<u8> {
let mut ui = Ui::dry(atlas, batch, (x, y));
draw(
@@ -1103,6 +1327,7 @@ pub mod pause {
world,
quit_label,
Instant::now() - std::time::Duration::from_secs(5),
friends,
);
let hit = ui.hit((x, y))?;
let nav = id("pause.nav", 0);
@@ -1111,7 +1336,9 @@ pub mod pause {
h if h == nav + 1 => Some(4),
h if h == nav + 2 => Some(3),
h if h == nav + 3 => Some(1),
h => [0u8, 1, 2, 3, 4, 9].into_iter().find(|&a| act(a) == h),
h => [0u8, 1, 2, 3, 4, 9, 10, 11, 12]
.into_iter()
.find(|&a| act(a) == h),
}
}
}
@@ -1173,7 +1400,7 @@ mod tests {
for (i, folder) in ["C", "B", "A"].iter().enumerate() {
world(&saves, folder, 1000 * (i as i64 + 1));
}
let mut title = Title::new(saves.clone());
let mut title = Title::new(saves.clone(), &saves);
title.mode = Mode::Select {
worlds: list_worlds(&saves),
selected: None,
+395 -66
View File
@@ -8,6 +8,7 @@ mod armor_stands;
mod backdrop;
mod banners;
mod beacon;
mod beehives;
mod block_entity_anims;
mod blockctl;
mod boats;
@@ -40,8 +41,10 @@ mod fireworks;
mod fishing;
mod fov;
mod frames;
mod friends;
mod functions;
mod game_mode;
mod gamemode_switcher;
mod ghasts;
mod golems;
mod growth;
@@ -215,6 +218,8 @@ struct Options {
/// `--dedicated`: run as a dedicated server; vanilla's server arguments
/// (`--nogui`, `--port`, `--world`, `--universe`, `--initSettings`) follow.
dedicated: Option<Vec<String>>,
/// `--benchmark SCENARIO`: run the benchmark, write its report and quit.
benchmark: Option<String>,
}
impl Options {
/// The name to join servers with: the one given, else the offline name kept
@@ -263,6 +268,7 @@ impl Options {
.ok()
.filter(|n| !n.is_empty()),
dedicated: None,
benchmark: None,
};
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
let mut args = std::env::args().skip(1);
@@ -270,7 +276,7 @@ impl Options {
match arg.as_str() {
"--help" | "-h" => {
println!(
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
);
return Ok(None);
}
@@ -312,6 +318,15 @@ impl Options {
"--smoke-report" => o.report = Some(value.into()),
"--screenshot-after" => o.screenshot_after = Some(value.parse()?),
"--world" => o.world = Some(value),
"--benchmark" => {
if horizon_client::benchmark::scenes(&value).is_none() {
return Err(format!(
"unknown benchmark {value}: standard, village, forest, ocean or mountain"
)
.into());
}
o.benchmark = Some(value);
}
"--server" => o.server = Some(value),
"--name" => o.player_name = Some(value),
"--session-file" => session_file = Some(value),
@@ -351,6 +366,7 @@ impl Options {
#[derive(Clone, Copy, PartialEq, Eq)]
enum Screen {
Playing,
GameModeSwitcher,
Paused,
Options,
Chat,
@@ -837,7 +853,7 @@ struct Game<'a> {
end_portal_travel: bool,
end: end::EndState,
block_ticks: Ticks,
tick_chunks: HashSet<(i32, i32)>,
tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership,
random_tick_sections: horizon_client::random_tick_sections::RandomTickSections,
level_events: Vec<LevelEvent>,
falling: Vec<FallingBlock>,
@@ -904,6 +920,8 @@ struct Game<'a> {
creative_screen: Creative,
control: Option<horizon_client::control::Server>,
frame_stats: horizon_client::control::FrameStats,
/// This play session's frame and tick times, for opt-in performance statistics.
perf: horizon_client::telemetry::Session,
/// Control replies waiting for a rendered frame or a benchmark deadline.
pending_screenshot: Option<std::sync::mpsc::Sender<String>>,
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
@@ -926,16 +944,21 @@ struct Game<'a> {
remote: Option<remote::Remote>,
/// This world is open to the network (game/lan.rs).
lan: Option<lan::LanHost>,
/// The open world is shared behind an invite code (game/friends.rs).
friends: Option<friends::Sharing>,
world_options: Option<lan_screen::WorldOptions>,
/// KeyboardHandler's debug key state (game/debug_keys.rs), the physical
/// keys held, and the debug renderers F3+B and F3+G switch on.
debug_keys: horizon_client::debug_keys::DebugKeys,
/// The F3 overlay's charts (F3+2, F3+3).
debug_charts: horizon_client::debug_chart::DebugCharts,
show_hitboxes: bool,
show_chunk_borders: bool,
/// PauseScreen.showPauseMenu (false after F3+Escape).
pause_menu: bool,
/// MultiPlayerGameMode.previousLocalPlayerMode (F3+N goes back to it).
previous_mode: Option<horizon_client::command::args::GameMode>,
gamemode_switcher: Option<horizon_client::game_mode_switcher::GameModeSwitcher>,
/// The system clipboard (`KeyboardHandler.clipboardManager`).
clipboard: horizon_client::clipboard::SystemClipboard,
/// Select All in the append-only text fields.
@@ -1550,16 +1573,20 @@ impl Game<'_> {
}
/// Track which chunks are ticking (Ticks needs chunk load/unload).
fn sync_tick_chunks(&mut self) {
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
for k in loaded.difference(&self.tick_chunks.clone()) {
self.register_chunk_ticks(*k);
if !self.tick_chunks.synchronize(&self.world.chunks) {
return;
}
for k in self.tick_chunks.difference(&loaded) {
self.random_tick_sections.remove(k);
// Move only the added keys out so registration can borrow all of Game.
let added = self.tick_chunks.take_added();
for &key in &added {
self.register_chunk_ticks(key);
}
for &key in self.tick_chunks.removed() {
self.random_tick_sections.remove(&key);
self.block_ticks
.remove_chunk(horizon_core::position::ChunkPos::new(k.0, k.1));
.remove_chunk(horizon_core::position::ChunkPos::new(key.0, key.1));
}
self.tick_chunks = loaded;
self.tick_chunks.recycle_added(added);
}
/// ServerLevel.tick block phases: scheduled ticks, random ticks within the
/// simulation distance, block events and moving pistons.
@@ -2119,6 +2146,10 @@ impl Game<'_> {
self.pending.record_saved(pos, &tag);
}
self.creaking_heart_broken(pos);
let hive = match self.world.block_entities.get(&key) {
Some(BlockEntity::Beehive(h)) => self.hive_state(pos).map(|s| ((**h).clone(), s)),
_ => None,
};
// playerWillDestroy and Level.removeBlock through the vanilla behaviour
// library: the block entity's side effects (containers spill), neighbour
// and shape updates, and the destroy event (particles, sound).
@@ -2168,6 +2199,12 @@ impl Game<'_> {
self.pop_resource(pos, d);
}
}
// BeehiveBlock.playerDestroy: silk touch keeps the bees in.
if let Some((hive, (honey, facing))) = hive
&& !silk
{
self.hive_broken_by_player(pos, hive, honey, facing);
}
// SpawnerBlock.spawnAfterBreak pops its experience whatever the tool.
let xp = if silk && &*facts.name != "minecraft:spawner" {
0
@@ -2214,11 +2251,17 @@ impl Game<'_> {
{
return Ok(());
}
// An EntityHitResult may fall through to Item.use, never to useItemOn.
let block_hit = if self.entity_targeted() {
None
} else {
self.pick()
};
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
let mut anchor_passed = None;
// MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item.
if !(sneaking && self.held().is_some())
&& let Some(hit) = self.pick()
&& let Some(hit) = block_hit.as_ref()
{
let held = self.held().cloned();
if self.use_lectern(hit.pos, held.as_ref()) {
@@ -2297,12 +2340,12 @@ impl Game<'_> {
let Some(info) = self.res.items.get(&stack.item).cloned() else {
return Ok(());
};
if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? {
if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) {
return Ok(());
}
use horizon_client::first_person::UseResult;
let swings = self.swings_started;
match self.use_tool(&stack)? {
match self.use_tool(&stack, block_hit.is_some())? {
UseResult::Success { swing } => {
if (UseResult::Success { swing }).should_swing(swings, self.swings_started) {
self.swing_arm();
@@ -2312,7 +2355,10 @@ impl Game<'_> {
UseResult::Fail => return Ok(()),
UseResult::Pass => {}
}
if self.use_potion_item(&stack)? || self.throw_item(&stack)? {
if self.use_potion_item(&stack)?
|| ((block_hit.is_some() || !stack.item.ends_with("_spawn_egg"))
&& self.throw_item(&stack)?)
{
return Ok(());
}
if self.raise_shield(self.selected)
@@ -2324,7 +2370,7 @@ impl Game<'_> {
|| self.use_book(&stack)
// Block items (heads, carved pumpkins) aimed at a block are
// placed first (useItemOn before useItem).
|| (!(info.block.is_some() && self.pick().is_some()) && self.equip_from_hand(&stack))
|| (!(info.block.is_some() && block_hit.is_some()) && self.equip_from_hand(&stack))
{
return Ok(());
}
@@ -2339,26 +2385,28 @@ impl Game<'_> {
return Ok(());
}
// Block foods attempt placement before starting consumption.
if !(info.block.is_some() && self.pick().is_some()) && self.start_eating(&info) {
if !(info.block.is_some() && block_hit.is_some()) && self.start_eating(&info) {
return Ok(());
}
// BoatItem.use also performs its own fluid/block raycast.
if self.place_boat(&stack) {
return Ok(());
}
if let Some(hit) = self.pick()
&& (self.launch_firework(&hit, &stack)
|| self.place_minecart(&hit, &stack)
|| self.place_painting(&hit, &stack)
|| self.place_item_frame(&hit, &stack)
|| self.place_armor_stand(&hit, &stack)
|| self.place_end_crystal(&hit, &stack))
if let Some(hit) = block_hit.as_ref()
&& (self.launch_firework(hit, &stack)
|| self.place_minecart(hit, &stack)
|| self.place_painting(hit, &stack)
|| self.place_item_frame(hit, &stack)
|| self.place_armor_stand(hit, &stack)
|| self.place_end_crystal(hit, &stack))
{
return Ok(());
}
if self.use_ender_eye(&stack)? {
if self.use_ender_eye(&stack, block_hit.is_some())? {
return Ok(());
}
let Some(hit) = self.pick() else {
let Some(hit) = block_hit else {
self.use_offhand();
return Ok(());
};
if info.block.is_none() {
@@ -2813,6 +2861,7 @@ impl Game<'_> {
}
fn tick(&mut self) -> Result<()> {
self.tick_debug_keys()?;
self.tick_debug_charts();
if self.remote.is_some() {
return self.tick_remote();
}
@@ -2827,7 +2876,7 @@ impl Game<'_> {
self.tick_weather_effects();
}
if self.ticks.is_multiple_of(6000) {
self.save_game()?;
self.save_game_with(false)?;
}
if running {
self.advance_clock();
@@ -2963,6 +3012,7 @@ impl Game<'_> {
elytra.damage += glider_wear;
}
let feet = [player.position.x, player.position.y, player.position.z];
let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z];
self.previous_eye = self.eye;
self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5;
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
@@ -2972,13 +3022,59 @@ impl Game<'_> {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet),
MotionEvent::Emission {
position, state, ..
state, in_water, ..
} if !crouching => {
// Entity.playStepSound: the block's step sound at 0.15 volume.
let sounds = self.res.facts.get(state).sounds.clone();
// Entity.playStepSound: the block's step sound at 0.15 volume,
// muffled under the swim sound in water.
let (volume, pitch) = if in_water {
(sounds.volume * 0.05, sounds.pitch * 0.8)
} else {
(sounds.volume * 0.15, sounds.pitch)
};
self.audio.play(&sounds.step, Some(feet), volume, pitch);
}
MotionEvent::Swim { volume, pitch } => {
self.audio
.play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch);
let _ = position;
.play("minecraft:entity.player.swim", Some(feet), volume, pitch);
}
MotionEvent::Drown => {
// LivingEntity.makeDrownParticles: eight bubbles moving
// with the player.
use horizon_client::particles::{ParticleOptions, ParticleType};
for _ in 0..8 {
let mut triangle = || {
let r = self.particles.random();
r.next_double() - r.next_double()
};
let p = [
feet[0] + triangle(),
feet[1] + triangle(),
feet[2] + triangle(),
];
self.particles.add(
&ParticleOptions::simple(ParticleType::Bubble),
p,
player_velocity,
);
}
}
MotionEvent::BubbleColumnParticle { bubble, position } => {
// ServerLevel.sendParticles: SPLASH (speed 1) or BUBBLE
// (y spread 0.01, speed 0.2), one each.
use horizon_client::particles::{ParticleOptions, ParticleType};
let (kind, spread, speed) = if bubble {
(ParticleType::Bubble, [0.0, 0.01, 0.0], 0.2)
} else {
(ParticleType::Splash, [0.0; 3], 1.0)
};
self.particles.send_particles(
&ParticleOptions::simple(kind),
[position.x, position.y, position.z],
spread,
speed,
1,
);
}
MotionEvent::Fall(horizon_client::landing::FallEvent::Sound {
sound,
@@ -3152,6 +3248,7 @@ impl Game<'_> {
});
}
horizon_client::spans::time("tick_lan", || self.tick_lan());
self.tick_friends();
horizon_client::spans::time("tick_hand", || self.tick_hand());
horizon_client::spans::time("tick_sleep", || self.tick_sleep());
horizon_client::spans::time("tick_portal", || self.tick_nether_portal())?;
@@ -3372,7 +3469,12 @@ impl Game<'_> {
title.draw_horizon(&mut ui, fade);
ui.finish();
} else {
title.draw(&self.res.atlas, &mut batch, self.cursor);
title.draw(
&self.res.atlas,
&mut batch,
self.cursor,
self.settings.file.bool("hideSplashTexts"),
);
}
return batch;
}
@@ -3550,7 +3652,7 @@ impl Game<'_> {
2 => "north (Towards negative Z)",
_ => "east (Towards positive X)",
};
let lines = [
let mut lines = vec![
format!("Horizon 26.3 (Rust) {:.0} fps", self.fps),
format!(
"C: {} chunks, {} sections drawn / {}",
@@ -3593,7 +3695,9 @@ impl Game<'_> {
self.world.day_time / 24000,
self.world.day_time % 24000
),
String::new(),
];
lines.extend(self.debug_chart_lines());
for (i, line) in lines.iter().enumerate() {
if line.is_empty() {
continue;
@@ -3616,6 +3720,22 @@ impl Game<'_> {
false,
);
}
let charts = self.debug_charts.draw(
&atlas.font,
w as i32,
h as i32,
self.settings.max_fps,
1000.0 / self.clock.rate(),
self.remote.is_some(),
);
hud_layout::paint(&mut batch, atlas, &charts);
if self.debug_charts.lightmap
&& let Some(r) = &self.renderer
{
let view =
horizon_client::debug_chart::lightmap(&r.lightmap_pixels, w as i32, h as i32);
hud_layout::paint(&mut batch, atlas, &view);
}
}
if !self.ui.hide_gui
&& let Some((text, at)) = &self.message
@@ -3641,6 +3761,7 @@ impl Game<'_> {
true,
);
}
Screen::GameModeSwitcher => self.draw_gamemode_switcher(&mut batch),
Screen::Dead => self.draw_death_screen(&mut batch),
Screen::Stats => self.draw_stats(&mut batch),
Screen::Advancements => self.draw_advancements(&mut batch),
@@ -3697,7 +3818,8 @@ impl Game<'_> {
| BlockEntity::Sculk(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_)
| BlockEntity::Spawner(_),
| BlockEntity::Spawner(_)
| BlockEntity::Beehive(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -3946,7 +4068,8 @@ impl Game<'_> {
| BlockEntity::Sculk(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_)
| BlockEntity::Spawner(_),
| BlockEntity::Spawner(_)
| BlockEntity::Beehive(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -3995,6 +4118,9 @@ impl Game<'_> {
self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0);
}
self.draw_slot_tooltip(batch);
if self.container.is_none() && self.craft_size == 2 && !self.mount_active() {
self.draw_inventory_effects(batch, (ox, oy), 176);
}
}
pub(super) fn close_container(&mut self) {
self.close_station();
@@ -4856,6 +4982,22 @@ impl Game<'_> {
f.input_clicked(&self.res.recipes, before);
}
}
/// `Camera.setRotation`: the camera's orientation, turned round in
/// third-person front view.
pub(super) fn camera_orientation(&self) -> glam::Quat {
let (view_yaw, view_pitch) =
if self.camera_type == perspective::CameraType::ThirdPersonFront {
(self.yaw + 180.0, -self.pitch)
} else {
(self.yaw, self.pitch)
};
glam::Quat::from_euler(
glam::EulerRot::YXZ,
std::f32::consts::PI - view_yaw.to_radians(),
-view_pitch.to_radians(),
0.0,
)
}
/// ItemEntityRenderer: items bob and spin; blocks render as small cubes.
fn entity_geometry(
&mut self,
@@ -5006,21 +5148,9 @@ impl Game<'_> {
if let Some(r) = &self.renderer {
let lid = |p: [i32; 3]| self.chest_lid(p, alpha as f32);
let anim = |p: [i32; 3]| self.block_anim(p, alpha as f32);
let (view_yaw, view_pitch) =
if self.camera_type == perspective::CameraType::ThirdPersonFront {
(self.yaw + 180.0, -self.pitch)
} else {
(self.yaw, self.pitch)
};
let scene = horizon_client::block_entity_render::Scene {
camera,
// Camera.setRotation.
orientation: glam::Quat::from_euler(
glam::EulerRot::YXZ,
std::f32::consts::PI - view_yaw.to_radians(),
-view_pitch.to_radians(),
0.0,
),
orientation: self.camera_orientation(),
anim: &anim,
texts: None,
partial: alpha as f32,
@@ -5450,6 +5580,7 @@ impl Game<'_> {
self.tick_beacons();
self.tick_creaking_hearts()?;
self.tick_spawners()?;
self.tick_beehives();
let mut lit_changes = Vec::new();
for (pos, entity) in self.world.block_entities.iter_mut() {
if let BlockEntity::Furnace(f) = entity
@@ -5593,7 +5724,7 @@ impl Game<'_> {
}
out
}
/// CloudRenderer (fancy): 12x4x12 cells from clouds.png drifting east.
/// CloudRenderer: flat or 12x4x12 extruded cells drifting east.
fn cloud_geometry(
&self,
sky: &horizon_client::environment::Sky,
@@ -5650,6 +5781,12 @@ impl Game<'_> {
});
}
};
if self.settings.clouds == "fast" {
for p in horizon_client::clouds::flat_cell(x0, z0, bottom) {
quad(p, 1.0);
}
continue;
}
let faces = [
(
[[x1, y0, z0], [x1, y0, z1], [x0, y0, z1], [x0, y0, z0]],
@@ -5700,7 +5837,9 @@ impl Game<'_> {
name: Option<&str>,
seed: Option<i64>,
creative: bool,
create: Option<&horizon_client::title::WorldOptions>,
) -> Result<()> {
self.perf.world_opening();
let save_root = std::env::current_dir()?.join("saves").join(folder);
horizon_client::save::upgrade_older_world(&save_root)?;
horizon_client::save::migrate_legacy(&save_root)?;
@@ -5719,7 +5858,9 @@ impl Game<'_> {
.map(|d| horizon_client::random_sequences::RandomSequences::from_nbt(&d))
.unwrap_or_default();
self.border = Default::default();
let level = Level::read(&save_root).unwrap_or_else(|| Level {
let existing = Level::read(&save_root);
let created = existing.is_none();
let level = existing.unwrap_or_else(|| Level {
name: name.unwrap_or(folder).to_owned(),
// WorldOptions.randomSeed when no seed was given.
seed: seed.unwrap_or_else(|| {
@@ -5736,6 +5877,13 @@ impl Game<'_> {
..Level::default()
});
let mut level = level;
// CreateWorldScreen's choices, before streaming reads the generator.
if created && let Some(o) = create {
level.hardcore = o.hardcore;
level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into();
level.allow_commands = Some(o.commands(creative));
horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?;
}
horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name));
if let Some(d) = &self.options.dimension {
level.dimension = d.clone();
@@ -5966,6 +6114,7 @@ impl Game<'_> {
return Ok(());
};
// Save the departing dimension's changed chunks.
self.streaming.save(&mut self.world, true);
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
self.save
@@ -6125,6 +6274,27 @@ impl Game<'_> {
/// Leaving the game with a world open (window closed, Quit, `quit`):
/// menu items go back (Player.closeContainer), then the world is saved,
/// once.
/// Keeps this play session's performance summary for the launcher to send, if the player
/// allows performance statistics (`horizon_client::telemetry`), and starts the next one.
pub(super) fn finish_perf(&mut self) {
let s = &self.settings;
let settings = horizon_telemetry::payload::Settings {
render_distance: s.render_distance.clamp(0, 255) as u8,
simulation_distance: s.simulation_distance.clamp(0, 255) as u8,
// 260 is the slider's "unlimited".
max_fps: if s.max_fps >= 260 {
0
} else {
s.max_fps.min(u32::from(u16::MAX)) as u16
},
vsync: s.vsync,
fullscreen: s.fullscreen,
graphics: s.graphics_preset.clone(),
};
self.perf
.finish(&horizon_client::logging::game_home(), settings);
}
pub(super) fn save_for_exit(&mut self) -> Result<()> {
if self.title.is_some() || self.saved_for_exit {
return Ok(());
@@ -6146,6 +6316,7 @@ impl Game<'_> {
if self.remote.is_some() {
return self.leave_server(None);
}
self.finish_perf();
self.stats.custom("leave_game", 1);
self.save_game()?;
self.lan_close(false);
@@ -6154,6 +6325,7 @@ impl Game<'_> {
self.save.flush();
self.session_lock = None;
horizon_client::crash::clear_detail("World");
self.debug_charts.reset();
self.streaming.paused = true;
self.world = World::new(self.res.facts.air, 0);
self.player = None;
@@ -6166,7 +6338,10 @@ impl Game<'_> {
if let Some(r) = self.renderer.as_mut() {
r.clear_sections();
}
self.title = Some(Title::new(std::env::current_dir()?.join("saves")));
self.title = Some(Title::new(
std::env::current_dir()?.join("saves"),
&self.options.resources,
));
self.capture(false);
Ok(())
}
@@ -6500,7 +6675,11 @@ impl Game<'_> {
}
}
/// Block tool use: distinguish success, failure and fall-through for hand feedback.
fn use_tool(&mut self, stack: &ItemStack) -> Result<horizon_client::first_person::UseResult> {
fn use_tool(
&mut self,
stack: &ItemStack,
allow_block_actions: bool,
) -> Result<horizon_client::first_person::UseResult> {
use horizon_client::first_person::UseResult;
let item = stack.item.trim_start_matches("minecraft:").to_owned();
let at = |p: [i32; 3]| {
@@ -6510,7 +6689,8 @@ impl Game<'_> {
f64::from(p[2]) + 0.5,
]
};
if let Some(hit) = self.pick()
if allow_block_actions
&& let Some(hit) = self.pick()
&& self.use_on_cauldron(hit.pos)?
{
return Ok(UseResult::Success { swing: true });
@@ -6572,11 +6752,16 @@ impl Game<'_> {
}
return Ok(UseResult::Success { swing: true });
}
// BucketItem.use has its own ray, even when the crosshair hits an entity.
let bucket = horizon_client::items::bucket_contents(&stack.item);
if !allow_block_actions && bucket.is_none() {
return Ok(UseResult::Pass);
}
let Some(hit) = self.pick() else {
return Ok(UseResult::Pass);
};
let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
if let Some((content, sound, mob)) = horizon_client::items::bucket_contents(&stack.item) {
if let Some((content, sound, mob)) = bucket {
if !self.may_build() {
return Ok(UseResult::Fail);
}
@@ -7127,9 +7312,17 @@ impl Game<'_> {
.clamp_gui_scale([r.config.width as i32, r.config.height as i32]);
}
self.streaming.radius = self.settings.render_distance;
// Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves:
// LevelExtractor.allChanged when they change.
let (s, st) = (&self.settings, &self.streaming);
let remesh = (s.biome_blend, s.smooth_lighting, s.cutout_leaves)
!= (st.biome_blend, st.smooth_lighting, st.cutout_leaves);
self.streaming.biome_blend = self.settings.biome_blend;
self.streaming.smooth_lighting = self.settings.smooth_lighting;
self.streaming.cutout_leaves = self.settings.cutout_leaves;
if remesh {
self.all_sections_changed();
}
self.audio.master = self.settings.master_volume;
horizon_client::hud::GUI_SCALE.store(
self.settings.gui_scale,
@@ -7137,6 +7330,14 @@ impl Game<'_> {
);
self.apply_ui_settings();
}
/// `LevelExtractor.allChanged`: every loaded section is rebuilt.
fn all_sections_changed(&mut self) {
for &(x, z) in self.world.chunks.keys() {
for sy in 0..horizon_client::chunk::HEIGHT / 16 {
self.world.dirty_sections.insert((x, sy, z));
}
}
}
/// Whether precipitation at a column is snow (Biome.coldEnoughToSnow:
/// base temperature lowered above y 80) or none (no precipitation).
fn precipitation(&self, x: i32, y: i32, z: i32) -> Option<bool> {
@@ -7582,6 +7783,7 @@ impl Game<'_> {
let name = self.res.names.item(&item);
self.tooltip(batch, &name, self.cursor.0, self.cursor.1);
}
self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32);
}
fn creative_trash_hovered(batch: &HudBatch, cursor: (f32, f32)) -> bool {
let (ox, oy) = Self::creative_origin(batch);
@@ -7777,14 +7979,24 @@ impl Game<'_> {
.collect();
}
fn save_game(&mut self) -> Result<()> {
self.save_game_with(true)
}
/// The autosave doesn't `wait` for the chunks to be on disk: every
/// generated chunk is saved, hundreds at a time, encoded and written on
/// the region writer meanwhile.
fn save_game_with(&mut self, wait: bool) -> Result<()> {
if self.remote.is_some() {
return Ok(());
}
self.streaming.save(&mut self.world, wait);
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
self.save
.save(&chunks, self.res.assets.registry, &self.res.biomes)?;
self.save_entities()?;
.save_later(&chunks, self.res.assets.registry, &self.res.biomes)?;
if wait {
self.save.flush();
}
self.save_entities(wait)?;
self.save_maps();
self.save_random_sequences();
self.save_raids();
@@ -7973,9 +8185,11 @@ impl Game<'_> {
self.end_geometry(camera, &mut entities);
}
if (!title || live) && self.dim == Dim::Overworld {
horizon_client::spans::time("clouds", || {
self.cloud_geometry(&sky, camera, alpha, &mut entities)
});
if horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3]) {
horizon_client::spans::time("clouds", || {
self.cloud_geometry(&sky, camera, alpha, &mut entities)
});
}
if self.settings.horizon.weather {
horizon_client::spans::time("weather", || {
self.weather_geometry(camera, alpha, &mut entities)
@@ -8071,6 +8285,7 @@ impl Game<'_> {
} else {
None
},
menu_blur: self.menu_blur(),
};
let result = match self.renderer.as_mut() {
Some(renderer) => horizon_client::spans::time("renderer", || renderer.render(&frame)),
@@ -8080,6 +8295,18 @@ impl Game<'_> {
self.entity_vertices = entities;
result
}
/// `Screen.extractBlurredBackground` over the panorama: every classic
/// screen of the title menus but the title itself (`TitleScreen`
/// doesn't blur), when `menuBackgroundBlurriness` is at least 1.
fn menu_blur(&self) -> Option<f32> {
let blurred = !horizon_client::ui_theme::horizon()
&& self.title.as_ref().is_some_and(|t| {
self.screen == Screen::Options
|| !matches!(t.mode, horizon_client::title::Mode::Main)
});
let radius = self.settings.menu_blur as f32;
(blurred && radius >= 1.0).then_some(radius)
}
/// `LevelExtractor` / `LevelRenderer`: the world border wall this frame.
fn border_draw(
&mut self,
@@ -8138,6 +8365,7 @@ impl Game<'_> {
self.pause_menu = true;
self.capture(true);
}
Screen::GameModeSwitcher => self.close_gamemode_switcher(false),
Screen::Dead => {}
Screen::Stats => self.screen = Screen::Paused,
Screen::Advancements => self.close_advancements(),
@@ -8504,6 +8732,11 @@ impl ApplicationHandler for Game<'_> {
if self.screen == Screen::Inventory || self.creative_inventory_open() {
self.inventory_drag_move();
}
if let Some(title) = &mut self.title
&& !horizon_client::ui_theme::horizon()
{
title.drag(self.cursor, (b.width, b.height));
}
if self.dragging && self.screen == Screen::Options {
let _ = b;
self.options_drag()?;
@@ -8579,6 +8812,15 @@ impl ApplicationHandler for Game<'_> {
)?;
}
}
WindowEvent::MouseInput {
state: ElementState::Released,
button: MouseButton::Left,
..
} if self.title.is_some() && self.screen != Screen::Options => {
if let Some(title) = &mut self.title {
title.release();
}
}
WindowEvent::MouseInput {
state,
button: MouseButton::Left,
@@ -8607,13 +8849,23 @@ impl ApplicationHandler for Game<'_> {
match action {
Action::Quit => event_loop.exit(),
Action::Options => self.open_options(true),
Action::Play { folder } => self.open_world(&folder, None, None, false)?,
Action::Accessibility => self
.open_options_at(true, horizon_client::options_ui::Page::Accessibility),
Action::Language => {
self.open_options_at(true, horizon_client::options_ui::Page::Language)
}
Action::Play { folder } => {
self.open_world(&folder, None, None, false, None)?
}
Action::Create {
folder,
name,
seed,
creative,
} => self.open_world(&folder, Some(&name), seed, creative)?,
options,
} => {
self.open_world(&folder, Some(&name), seed, creative, Some(&options))?
}
Action::Connect { address } => {
self.connect_server(&address, &self.options.player_name())?
}
@@ -8870,7 +9122,13 @@ impl ApplicationHandler for Game<'_> {
for _ in 0..steps {
let started = Instant::now();
if self.title.is_none() && !self.pause {
let tick = Instant::now();
horizon_client::spans::time("tick", || self.tick())?;
// In single player the tick is the integrated server's.
if self.remote.is_none() {
self.perf.tick(tick.elapsed().as_secs_f32() * 1000.0);
self.debug_charts.log_tick(tick, tick.elapsed());
}
self.tick_ambience();
self.tick_fov();
} else if self.title.is_some() {
@@ -8956,6 +9214,19 @@ impl ApplicationHandler for Game<'_> {
}
if rendered {
self.frame_stats.record(elapsed.as_secs_f32() * 1000.0);
self.debug_charts.frame_times.log(elapsed.as_nanos() as i64);
if self.frames == 0 {
// The launcher times Play to this line (launcher/src/perf.rs).
log::info!(
"Horizon: first frame after {} ms",
self.started.elapsed().as_millis()
);
}
if self.title.is_some() {
self.perf.title_shown();
} else if self.screen == Screen::Playing && self.player.is_some() {
self.perf.frame(elapsed.as_secs_f32() * 1000.0);
}
self.frames += 1;
self.fps_frames += 1;
horizon_client::crash::debug_crash_tick();
@@ -8999,7 +9270,14 @@ impl ApplicationHandler for Game<'_> {
return;
}
if let Some(w) = &self.window {
w.request_redraw();
if self.options.offscreen {
// Offscreen frames don't wait for the window to be drawn: an
// occluded window (a locked macOS session) gets no redraws.
let id = w.id();
self.window_event(event_loop, id, WindowEvent::RedrawRequested);
} else {
w.request_redraw();
}
}
event_loop.set_control_flow(ControlFlow::Poll);
}
@@ -9010,6 +9288,7 @@ impl ApplicationHandler for Game<'_> {
if let Err(e) = self.save_for_exit() {
log::warn!("Horizon: failed to save the world on exit: {e}");
}
self.finish_perf();
}
}
/// clouds.png as filled cells (`CloudRenderer.prepare`: alpha 10 or more).
@@ -9177,6 +9456,15 @@ pub fn run() -> Result<()> {
player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main")
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
};
// These batches share the exported document instead of reparsing it per layer.
let (armor_stand_assets, boat_models, cart_models) = {
let document = horizon_client::mobs::EntityModelDocument::load(&root).ok();
(
armor_stands::ArmorStandAssets::load(&root, document.as_ref()),
boats::BoatModels::load(document.as_ref()),
minecarts::CartModels::load(document.as_ref()),
)
};
let inventory = vec![None; 36];
let now = Instant::now();
let game_root = options.resources.clone();
@@ -9336,7 +9624,7 @@ pub fn run() -> Result<()> {
end_portal_travel: false,
end: Default::default(),
block_ticks: Ticks::new(0),
tick_chunks: HashSet::new(),
tick_chunks: Default::default(),
random_tick_sections: Default::default(),
level_events: Vec::new(),
falling: Vec::new(),
@@ -9349,9 +9637,9 @@ pub fn run() -> Result<()> {
glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"),
armor_stands: Vec::new(),
others: Vec::new(),
armor_stand_assets: armor_stands::ArmorStandAssets::load(&root),
armor_stand_assets,
boats: Vec::new(),
boat_models: boats::BoatModels::load(&root),
boat_models,
crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"),
carts: Vec::new(),
jukebox_sounds: HashMap::new(),
@@ -9370,7 +9658,7 @@ pub fn run() -> Result<()> {
.join("assets/skins"),
),
skin_slots: Vec::new(),
cart_models: minecarts::CartModels::load(&root),
cart_models,
riding: None,
ender_items: vec![None; 27],
ender_open: None,
@@ -9390,6 +9678,7 @@ pub fn run() -> Result<()> {
creative_screen: Creative::load(&game_root)?,
control: None,
frame_stats: Default::default(),
perf: Default::default(),
pending_screenshot: None,
pending_bench: None,
flight: None,
@@ -9403,11 +9692,14 @@ pub fn run() -> Result<()> {
remote: None,
lan: None,
world_options: None,
friends: None,
debug_keys: Default::default(),
debug_charts: Default::default(),
show_hitboxes: false,
show_chunk_borders: false,
pause_menu: true,
previous_mode: None,
gamemode_switcher: None,
clipboard: Default::default(),
text_selection: Default::default(),
saved_for_exit: false,
@@ -9442,6 +9734,14 @@ pub fn run() -> Result<()> {
player_model: None,
};
game.ui.vanilla_root = vanilla_root;
if game.options.benchmark.is_some() {
// The same conditions on every machine: no VSync, no frame cap, no
// pause or idle limit without focus. In memory only, never saved.
game.settings.vsync = false;
game.settings.max_fps = 260;
game.settings.inactivity_fps_limit = "minimized".into();
game.options.no_pause = true;
}
game.apply_settings();
if let Some(path) = &game.options.control {
let server = horizon_client::control::Server::start(path)
@@ -9449,6 +9749,29 @@ pub fn run() -> Result<()> {
log::info!("Horizon: control socket {}", server.path().display());
game.control = Some(server);
}
if let Some(scenario) = game.options.benchmark.clone() {
let control = game
.control
.get_or_insert_with(horizon_client::control::Server::local);
horizon_client::benchmark::start(
control.sender(),
horizon_client::benchmark::Setup {
scenario,
started,
app: horizon_bench::App {
name: "horizon-client".into(),
version: horizon_client::crash::version(),
commit: option_env!("HORIZON_COMMIT").map(str::to_owned),
mods: Vec::new(),
},
simulation_distance: game.settings.simulation_distance as u32,
vsync: false,
fps_cap: None,
offscreen: game.options.offscreen,
game_dir: std::env::current_dir()?,
},
);
}
if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") {
return game.dispense_fixture(&spec);
}
@@ -9471,10 +9794,13 @@ pub fn run() -> Result<()> {
}
Some(folder) => {
let (seed, creative) = (game.options.seed, game.options.creative);
game.open_world(&folder, None, Some(seed), creative)?;
game.open_world(&folder, None, Some(seed), creative, None)?;
}
None => {
let title = Title::new(std::env::current_dir()?.join("saves"));
let title = Title::new(
std::env::current_dir()?.join("saves"),
&game.options.resources,
);
// The launcher's opening, once per session and only in Horizon's style.
if horizon_client::ui_theme::horizon() && game.options.frames.is_none() {
title
@@ -9534,6 +9860,9 @@ mod runtime_reset_tests {
}
}
#[cfg(test)]
mod entity_model_loading_tests;
#[cfg(test)]
mod tests {
use super::*;
+215 -38
View File
@@ -19,27 +19,99 @@ pub(super) struct Toast {
icon: String,
frame: Frame,
title: Text,
shown: Option<Instant>,
/// A `RecipeToast`: the icon is a recipe result.
recipe: bool,
slide: Slide,
/// A `RecipeToast`: the crafting station and result of each display
/// unlocked while it lasts (`recipeItems`); empty for an advancement.
recipes: Vec<(String, ItemStack)>,
/// `RecipeToast.changed` and `lastChanged`.
changed: bool,
last_changed: i64,
}
impl Toast {
pub(super) fn is_recipe(&self) -> bool {
self.recipe
}
pub(super) fn was_shown(&self) -> bool {
self.shown.is_some()
}
/// `RecipeToast`: "New Recipe(s) Unlocked!" with the recipe's result.
pub(super) fn recipe(icon: &str) -> Self {
/// `RecipeToast.addOrUpdate` on a new toast.
pub(super) fn recipe(items: Vec<(String, ItemStack)>) -> Self {
Self {
icon: icon.to_owned(),
icon: String::new(),
frame: Frame::Task,
title: Text::literal(""),
shown: None,
recipe: true,
slide: Slide::default(),
recipes: items,
changed: true,
last_changed: 0,
}
}
pub(super) fn is_recipe(&self) -> bool {
!self.recipes.is_empty()
}
/// `RecipeToast.addItem`: more displays on a toast still queued or shown.
pub(super) fn add_recipes(&mut self, items: Vec<(String, ItemStack)>) {
self.recipes.extend(items);
self.changed = true;
}
/// `Toast.update` with `fullyVisibleForMs`: whether it wants to be shown.
fn wants_show(&mut self, fully_for: i64, multiplier: f64) -> bool {
let time = 5000.0 * multiplier;
if self.recipes.is_empty() {
// AdvancementToast.
return (fully_for as f64) < time;
}
if self.changed {
self.last_changed = fully_for;
self.changed = false;
}
((fully_for - self.last_changed) as f64) < time
}
/// `RecipeToast.displayedRecipeIndex`: the displays take turns over the
/// toast's display time.
fn displayed_recipe(&self, fully_for: i64, multiplier: f64) -> usize {
let n = self.recipes.len() as f64;
(fully_for as f64 / (5000.0 * multiplier / n).max(1.0) % n) as usize
}
}
/// `ToastManager.ToastInstance`: slides a toast in and out over 600 ms,
/// eased by the square, and counts how long it has been fully shown.
#[derive(Default)]
struct Slide {
/// When it first updated; the times below are milliseconds since.
origin: Option<Instant>,
begun: bool,
/// `animationStartTime`.
start: i64,
/// `becameFullyVisibleAt`.
fully_at: i64,
show: bool,
/// `visiblePortion`: 0 off screen, 1 fully in.
portion: f32,
/// `fullyVisibleFor`.
fully_for: i64,
}
impl Slide {
const MS: i64 = 600;
/// `ToastInstance.update` at `now`; `wants_show` is the toast's own
/// update. The visibility it switched to (the sound to play), and whether
/// it has finished sliding out.
fn update(&mut self, now: i64, wants_show: impl FnOnce(i64) -> bool) -> (Option<bool>, bool) {
let was = self.show;
if !self.begun {
self.begun = true;
self.start = now;
self.show = true;
}
if self.show && now - self.start <= Self::MS {
self.fully_at = now;
}
self.fully_for = now - self.fully_at;
let progress = ((now - self.start) as f32 / Self::MS as f32).clamp(0.0, 1.0);
let progress = progress * progress;
self.portion = if self.show { progress } else { 1.0 - progress };
let wanted = wants_show(self.fully_for);
if wanted != self.show {
self.start = now - ((1.0 - self.portion) * Self::MS as f32) as i64;
self.show = wanted;
}
let finished = !self.show && now - self.start > Self::MS;
((self.show != was).then_some(self.show), finished)
}
}
#[derive(Default)]
pub(super) struct AdvState {
@@ -430,8 +502,10 @@ impl Game<'_> {
icon: d.icon.clone(),
frame: d.frame,
title: text_of(&d.title),
shown: None,
recipe: false,
slide: Slide::default(),
recipes: Vec::new(),
changed: false,
last_changed: 0,
});
}
if d.announce && self.ui.rules.bool("show_advancement_messages") {
@@ -679,45 +753,57 @@ impl Game<'_> {
c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to)
});
}
/// `ToastManager` with the `AdvancementToast`.
/// `ToastManager` with the `AdvancementToast` and the `RecipeToast`,
/// one at a time.
pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) {
let multiplier = f64::from(self.settings.notification_display_time);
let Some(t) = self.adv.toasts.front_mut() else {
return;
};
let shown = *t.shown.get_or_insert_with(Instant::now);
let ms = shown.elapsed().as_millis() as f32;
// AdvancementToast.DISPLAY_TIME: 5 s, sliding 600 ms in and out.
if ms > 5600.0 {
let first = t.slide.origin.is_none();
let origin = *t.slide.origin.get_or_insert_with(Instant::now);
let now = origin.elapsed().as_millis() as i64;
let mut slide = std::mem::take(&mut t.slide);
let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier));
t.slide = slide;
if finished {
self.adv.toasts.pop_front();
return;
}
let slide = if ms < 600.0 {
ms / 600.0
} else if ms > 5000.0 {
1.0 - (ms - 5000.0) / 600.0
} else {
1.0
};
let (title, frame, icon, recipe) = (t.title.clone(), t.frame, t.icon.clone(), t.recipe);
if recipe {
// RecipeToast: black description under a purple title.
let x = batch.width - 160.0 * t.slide.portion;
let fully_for = t.slide.fully_for;
let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone());
let recipe = t
.is_recipe()
.then(|| t.recipes[t.displayed_recipe(fully_for, multiplier)].clone());
// ToastManager.update: the sound of the new visibility, and a
// challenge's own sound as it leaves the queue.
if let Some(show) = sound {
let event = if show { "ui.toast.in" } else { "ui.toast.out" };
self.audio
.play(&format!("minecraft:{event}"), None, 1.0, 1.0);
}
if first && recipe.is_none() && frame == Frame::Challenge {
self.audio
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
}
if let Some((station, item)) = recipe {
// RecipeToast: black description under a purple title, the
// station at 0.6 scale in the corner over the cycling result.
let atlas = &self.res.atlas;
let x = batch.width - 160.0 * slide;
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
let description = self.translate("recipe.toast.description", "Check your recipe book");
let atlas = &self.res.atlas;
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0);
let start = batch.vertices.len();
self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, 3.0);
batch.scale_since(start, x, 0.0, 0.6, 0.6);
self.draw_item_model(batch, &item, x + 8.0, 8.0);
return;
}
if frame == Frame::Challenge && ms < 50.0 {
self.audio
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
}
let atlas = &self.res.atlas;
let x = batch.width - 160.0 * slide;
batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0);
let (key, color) = match frame {
Frame::Task => ("advancements.toast.task", 0xFF00_FFFF),
@@ -813,3 +899,94 @@ pub(super) fn text_of(v: &Value) -> Text {
Text::empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn recipes(n: usize) -> Toast {
Toast::recipe(
(0..n)
.map(|i| {
let item = ItemStack::new(&format!("minecraft:item_{i}"), 1);
("minecraft:crafting_table".to_owned(), item)
})
.collect(),
)
}
/// Drives a toast frame by frame (every `step` ms) and returns the slide
/// portions at the given times and when it finished.
fn run(toast: &mut Toast, step: i64, until: i64, at: &[i64]) -> (Vec<f32>, Option<i64>) {
let mut slide = Slide::default();
let mut seen = Vec::new();
for now in (0..=until).step_by(step as usize) {
let (_, finished) = slide.update(now, |f| toast.wants_show(f, 1.0));
if finished {
return (seen, Some(now));
}
if at.contains(&now) {
seen.push(slide.portion);
}
}
(seen, None)
}
#[test]
fn toasts_slide_in_squared_and_out_after_five_seconds() {
let mut toast = recipes(1);
let (portions, finished) = run(&mut toast, 10, 10_000, &[0, 300, 600, 3000]);
// (300 / 600)² = 0.25: ToastInstance.calculateVisiblePortion.
assert_eq!(portions, [0.0, 0.25, 1.0, 1.0]);
// Fully in at 600, shown 5000 ms, out over 600 more.
assert!(
finished.is_some_and(|t| (6200..=6220).contains(&t)),
"{finished:?}"
);
}
#[test]
fn the_first_update_plays_the_show_sound_and_the_hide_sound_follows() {
let mut toast = recipes(1);
let mut slide = Slide::default();
assert_eq!(slide.update(0, |f| toast.wants_show(f, 1.0)).0, Some(true));
assert_eq!(slide.update(100, |f| toast.wants_show(f, 1.0)).0, None);
assert_eq!(
slide.update(5600, |f| toast.wants_show(f, 1.0)).0,
Some(false)
);
}
#[test]
fn recipe_toasts_cycle_through_their_displays_over_the_display_time() {
let toast = recipes(4);
let shown: Vec<usize> = [0, 1249, 1250, 2500, 3750, 4999, 5000]
.iter()
.map(|&t| toast.displayed_recipe(t, 1.0))
.collect();
assert_eq!(shown, [0, 0, 1, 2, 3, 3, 0]);
// notificationDisplayTime doubles each turn.
assert_eq!(toast.displayed_recipe(2500, 2.0), 1);
}
#[test]
fn unlocking_more_recipes_keeps_the_toast_up_five_more_seconds() {
let mut toast = recipes(1);
let mut slide = Slide::default();
let mut finished = None;
for now in (0..=20_000).step_by(10) {
if now == 4000 {
toast.add_recipes(recipes(1).recipes);
}
if slide.update(now, |f| toast.wants_show(f, 1.0)).1 {
finished = Some(now);
break;
}
}
assert_eq!(toast.recipes.len(), 2);
// lastChanged moved to 3400 ms fully shown: hidden at 8400 + 600.
assert!(
finished.is_some_and(|t| (9600..=9620).contains(&t)),
"{finished:?}"
);
}
}
+19 -3
View File
@@ -368,6 +368,7 @@ impl Game<'_> {
}
match self.screen {
Screen::Playing => "playing",
Screen::GameModeSwitcher => "gamemode-switcher",
Screen::Paused => "paused",
Screen::Options => "options",
Screen::Inventory if self.station.is_some() => "station",
@@ -484,11 +485,19 @@ impl Game<'_> {
seed,
creative,
focus,
options,
} => json!({
"mode": "create-world",
"tab": (["game", "world", "more"][options.tab.min(2)]),
"fields": { "name": name, "seed": seed },
"focus": match focus { 0 => "name", 1 => "seed", _ => "none" },
"creative": creative,
"hardcore": options.hardcore,
"difficulty": horizon_client::title::DIFFICULTIES[options.difficulty()],
"allow_commands": options.commands(*creative),
"superflat": options.flat,
"generate_structures": options.structures,
"bonus_chest": options.bonus_chest(),
}),
Mode::Edit {
world,
@@ -1321,10 +1330,17 @@ impl Game<'_> {
let title = self.title.as_mut().ok_or("no title screen")?;
if let Some(field) = &field {
match &mut title.mode {
horizon_client::title::Mode::Create { focus, .. } => {
horizon_client::title::Mode::Create { focus, options, .. } => {
// Each box is on its own tab.
*focus = match field.as_str() {
"name" => 0,
"seed" => 1,
"name" => {
options.tab = 0;
0
}
"seed" => {
options.tab = 1;
1
}
other => {
return Err(format!(
"the create-world fields are name and seed, not {other}"
@@ -27,8 +27,11 @@ pub(super) struct ArmorStandAssets {
pub equipment: HashMap<String, HashMap<String, (String, Option<u32>)>>,
}
impl ArmorStandAssets {
pub fn load(root: &std::path::Path) -> Self {
let load = |key: &str| horizon_client::mobs::load_model(root, key);
pub fn load(
root: &std::path::Path,
document: Option<&horizon_client::mobs::EntityModelDocument>,
) -> Self {
let load = |key: &str| document.and_then(|document| document.model(key));
let mut layers = HashMap::new();
let mut player = HashMap::new();
for slot in ["helmet", "chestplate", "leggings", "boots"] {
+11
View File
@@ -274,6 +274,17 @@ impl Game<'_> {
}
}
/// Clicks on the power, confirm and cancel buttons.
/// The effect, upgrade, confirm and cancel buttons a controller can
/// focus (GUI origin relative).
pub(super) fn beacon_targets(&self) -> Vec<[f32; 4]> {
let (ux, uy) = upgrade_button();
buttons()
.into_iter()
.map(|(_, x, y, _)| (x, y))
.chain([(ux, uy), (164.0, 107.0), (190.0, 107.0)])
.map(|(x, y)| [x + SHIFT, y, 22.0, 22.0])
.collect()
}
pub(super) fn beacon_click(&mut self, local: (f32, f32)) -> bool {
let l = (local.0 - SHIFT, local.1);
let levels = self.beacon_levels();
+238
View File
@@ -0,0 +1,238 @@
//! Beehives and bee nests in the game (`crate::beehive` holds their logic):
//! their server tick, bees going in, and the bees let out, angry, when a
//! player breaks the hive or fire reaches it.
use super::Game;
use horizon_client::{
beehive::{self, Beehive, HiveHost, Release},
containers::BlockEntity,
mobs::{Mob, Who, bee},
};
use horizon_core::{
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource},
};
use horizon_world::{nbt::Tag, registry::BlockStateId};
struct GameHive<'g, 'a> {
game: &'g mut Game<'a>,
}
impl HiveHost for GameHive<'_, '_> {
fn random(&mut self) -> &mut LegacyRandom {
&mut self.game.world.random
}
fn bees_stay_in_hive(&self, _at: [i32; 3]) -> bool {
bee::bees_stay_in_hive(&self.game.mob_world_base(&[]))
}
fn blocked(&self, at: [i32; 3]) -> bool {
!self
.game
.mob_world_base(&[])
.block_collision_boxes(at[0], at[1], at[2])
.is_empty()
}
fn set_honey_level(&mut self, at: [i32; 3], level: i32) {
let state = self.game.world.block(at[0], at[1], at[2]);
if let Some(state) = self.game.hive_with_honey(state, level) {
let _ = self.game.level_set(at, state);
}
}
fn load(&mut self, tag: &Tag) -> Option<Mob> {
let kind = horizon_client::entity_nbt::kind(tag)?;
if !self
.game
.res
.mob_data
.entity_has("minecraft:beehive_inhabitors", &kind)
{
return None;
}
let id = self.game.load_mob(tag.clone(), None)?;
let i = self.game.mobs.iter().position(|m| m.id == id)?;
Some(self.game.mobs.remove(i))
}
fn add(&mut self, m: Mob) -> bool {
self.game.mobs.push(m);
true
}
fn sound(&mut self, name: &'static str, at: [f64; 3]) {
self.game
.audio
.play(&format!("minecraft:{name}"), Some(at), 1.0, 1.0);
}
}
impl Game<'_> {
fn hive_with_honey(&self, state: BlockStateId, level: i32) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
let mut s = registry.state(state)?.clone();
s.properties
.insert("honey_level".to_owned(), level.to_string());
registry.resolve(&s).ok()
}
/// The hive's honey level and front, from its block state.
pub(super) fn hive_state(&self, at: [i32; 3]) -> Option<(Option<i32>, [i32; 2])> {
let state = self.world.block(at[0], at[1], at[2]);
let name = &self.res.facts.get(state).name;
if !self
.res
.items
.block_tags
.get("minecraft:beehives")
.is_some_and(|t| t.contains(&**name))
{
return None;
}
let props = &self.res.assets.registry.state(state)?.properties;
let honey = props.get("honey_level").and_then(|v| v.parse().ok());
let facing = beehive::facing_step(props.get("facing").map(String::as_str));
Some((honey, facing))
}
/// `BeehiveBlockEntity.serverTick` for every hive, after an emergency
/// exit for those with fire beside them (`BeehiveBlock.updateShape`).
pub(super) fn tick_beehives(&mut self) {
let mut keys: Vec<(i32, i32, i32)> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Beehive(_)))
.map(|(k, _)| *k)
.collect();
keys.sort_unstable();
for key in keys {
let at = [key.0, key.1, key.2];
let Some((honey, facing)) = self.hive_state(at) else {
continue;
};
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key)
else {
continue;
};
let fire = [
[1, 0, 0],
[-1, 0, 0],
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0, 0, -1],
]
.iter()
.any(|d| {
let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]);
&*self.res.facts.get(state).name == "minecraft:fire"
});
let mut host = GameHive { game: self };
if fire && !hive.bees.is_empty() {
hive.release_all(at, facing, honey, Release::Emergency, &mut host);
}
hive.server_tick(at, facing, honey, &mut host);
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
}
}
/// `BeehiveBlockEntity.addOccupant` for a bee its `BeeEnterHiveGoal`
/// sent in: off its lead, its tag stored, the bee gone.
pub(super) fn bee_enter_hive(&mut self, mob: u32, at: [i32; 3]) {
let key = (at[0], at[1], at[2]);
let Some(i) = self
.mobs
.iter()
.position(|m| m.id == mob && m.alive() && !m.removed)
else {
return;
};
if !matches!(self.world.block_entities.get(&key), Some(BlockEntity::Beehive(h)) if !h.full())
{
return;
}
if self.mobs[i].extra.leash.is_some() {
self.break_leash(mob, true, false);
self.mobs[i].extra.leash = None;
}
self.mobs[i].extra.mount = None;
let tag = self.mob_tree_nbt(i);
let flower = bee::get(&self.mobs[i]).and_then(|b| b.flower);
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else {
return;
};
let stored = hive.add_occupant(at, tag, flower, &mut GameHive { game: self });
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
if stored && let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
m.removed = true;
}
}
/// `BeehiveBlockEntity.emptyAllLivingFromHive` with no player about.
pub(super) fn empty_hive(&mut self, at: [i32; 3], facing: [i32; 2], status: Release) {
let key = (at[0], at[1], at[2]);
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else {
return;
};
hive.release_all(at, facing, None, status, &mut GameHive { game: self });
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
}
/// `BeehiveBlock.playerDestroy` without silk touch: the bees come out
/// angry at the player unless smoke calms them, then
/// `angerNearbyBees`.
pub(super) fn hive_broken_by_player(
&mut self,
at: [i32; 3],
mut hive: Beehive,
honey: Option<i32>,
facing: [i32; 2],
) {
let released = hive.release_all(
at,
facing,
honey,
Release::Emergency,
&mut GameHive { game: self },
);
let sedated = beehive::smokey(&self.mob_world_base(&[]), at);
if let Some(p) = self.player_view().map(|p| p.position) {
for m in self.mobs.iter_mut().filter(|m| released.contains(&m.id)) {
if m.distance_sqr(p) <= 16.0 {
if sedated {
bee::set_stay_out_of_hive_countdown(m);
} else {
m.ai.target = Some(Who::Player);
}
}
}
}
self.anger_nearby_bees(at);
}
/// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down)
/// without a target go for a player in the same box.
fn anger_nearby_bees(&mut self, at: [i32; 3]) {
let min = Vec3::new(
f64::from(at[0]) - 8.0,
f64::from(at[1]) - 6.0,
f64::from(at[2]) - 8.0,
);
let area = Aabb::new(min, Vec3::new(min.x + 17.0, min.y + 13.0, min.z + 17.0));
if !self
.player_view()
.is_some_and(|p| p.bounds.intersects(area))
{
return;
}
let mut bees: Vec<usize> = (0..self.mobs.len())
.filter(|&i| {
let m = &self.mobs[i];
m.species() == horizon_client::mobs::Species::Bee
&& !m.removed
&& m.bounds().intersects(area)
})
.collect();
bees.retain(|&i| self.mobs[i].ai.target.is_none());
for i in bees {
// Util.getRandom over the one player.
let _ = self.world.random.next_int_bound(1);
self.mobs[i].ai.target = Some(Who::Player);
}
}
}
+5 -8
View File
@@ -151,25 +151,22 @@ impl BoatModels {
self.models.contains_key(wood)
}
}
pub fn load(root: &std::path::Path) -> Self {
pub fn load(document: Option<&horizon_client::mobs::EntityModelDocument>) -> Self {
let mut models = HashMap::new();
let mut chest_models = HashMap::new();
if let Ok(bytes) = std::fs::read(root.join("entity-models.json"))
&& let Ok(serde_json::Value::Object(all)) =
serde_json::from_slice::<serde_json::Value>(&bytes)
{
for key in all.keys() {
if let Some(document) = document {
for key in document.keys() {
if let Some(wood) = key
.strip_prefix("minecraft:boat/")
.and_then(|k| k.strip_suffix("#main"))
&& let Some(part) = horizon_client::mobs::load_model(root, key)
&& let Some(part) = document.model(key)
{
models.insert(wood.to_owned(), part);
}
if let Some(wood) = key
.strip_prefix("minecraft:chest_boat/")
.and_then(|k| k.strip_suffix("#main"))
&& let Some(part) = horizon_client::mobs::load_model(root, key)
&& let Some(part) = document.model(key)
{
chest_models.insert(wood.to_owned(), part);
}
+7 -2
View File
@@ -139,6 +139,11 @@ impl Game<'_> {
PhysicalKey::Code(k) => Some(k),
_ => None,
};
self.book_input(key, event.text.as_deref());
}
/// A key and the text it typed in the open book (the keyboard, or a
/// controller's on-screen keyboard).
pub(super) fn book_input(&mut self, key: Option<KeyCode>, text: Option<&str>) {
match self.book.as_mut() {
Some(BookScreen::View { .. }) => match key {
Some(KeyCode::Escape) => self.close_book(),
@@ -167,7 +172,7 @@ impl Game<'_> {
}
}
_ => {
if let Some(typed) = event.text.as_ref() {
if let Some(typed) = text {
self.text_selection.take(BOOK_TITLE, title);
for c in typed.chars().filter(|c| !c.is_control()) {
if title.chars().count() < 15 {
@@ -193,7 +198,7 @@ impl Game<'_> {
self.type_into_page("\n")
}
_ => {
if let Some(typed) = event.text.as_ref().map(|t| t.to_string()) {
if let Some(typed) = text {
let typed: String = typed.chars().filter(|c| !c.is_control()).collect();
if !typed.is_empty() {
self.take_page_selection();
+50 -3
View File
@@ -32,7 +32,7 @@ const HELP: &[&str] = &[
"options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs graphics graphics-advanced)",
"stats [reset] frame-time summary since the last reset",
"bench SECONDS reset stats, wait, then reply with the summary",
"fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH] fly the camera along a line at constant speed, then reply with the frame summary",
"fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]] fly the camera along a line at constant speed, then reply with the frame summary (raw: every frame time too)",
"open WORLD [SEED] [creative] open or create a world from the title screen",
"save save the world",
"save-all save the world, rewriting every resident chunk",
@@ -51,6 +51,8 @@ pub struct Flight {
pitch: f32,
started: Instant,
seconds: f64,
/// Reply with every frame time too (`fly ... PITCH raw`).
raw: bool,
reply: Sender<String>,
}
@@ -76,7 +78,13 @@ impl Game<'_> {
if t >= 1.0
&& let Some(flight) = self.flight.take()
{
let _ = flight.reply.send(self.frame_stats.summary().to_string());
let mut summary = self.frame_stats.summary();
if flight.raw {
summary["frame_ms"] = self.frame_stats.frame_millis().into();
summary["cpu_ms"] = self.frame_stats.cpu_millis().into();
summary["gpu_ms"] = self.frame_stats.gpu_millis().into();
}
let _ = flight.reply.send(summary.to_string());
}
}
pub(super) fn poll_control(&mut self, event_loop: &ActiveEventLoop) {
@@ -120,6 +128,9 @@ impl Game<'_> {
if let Some(value) = self.lan_control(&words)? {
return Ok(Some(value));
}
if let Some(value) = self.friends_control(&words)? {
return Ok(Some(value));
}
match self.agent_command(&words, line, reply, event_loop)? {
super::agent::Handled::Reply(value) => return Ok(Some(value)),
super::agent::Handled::Deferred => return Ok(None),
@@ -131,6 +142,7 @@ impl Game<'_> {
.chain(super::station_control::HELP)
.chain(super::blockctl::HELP)
.chain(super::lan::HELP)
.chain(super::friends::HELP)
.chain(super::render_control::HELP)
.chain(super::sculk::HELP)
.chain(super::agent::HELP)
@@ -464,6 +476,7 @@ impl Game<'_> {
pitch,
started: Instant::now(),
seconds: n(7)?.max(0.1),
raw: words.get(9) == Some(&"raw"),
reply: reply.clone(),
});
Ok(None)
@@ -475,7 +488,7 @@ impl Game<'_> {
let folder = arg(1)?;
let seed = words.get(2).map(|s| s.parse::<i64>()).transpose()?;
let creative = words.get(3) == Some(&"creative");
self.open_world(folder, Some(folder), seed, creative)?;
self.open_world(folder, Some(folder), seed, creative, None)?;
ok()
}
"connect" => {
@@ -562,6 +575,7 @@ impl Game<'_> {
}
match self.screen {
Screen::Playing => "playing",
Screen::GameModeSwitcher => "gamemode-switcher",
Screen::Paused => "paused",
Screen::Options => "options",
Screen::Inventory => "inventory",
@@ -594,6 +608,15 @@ impl Game<'_> {
let memory = r.device.generate_allocator_report();
json!({
"gpu": r.info.name,
"vendor": vendor_name(r.info.vendor),
"driver": format!("{} {}", r.info.driver, r.info.driver_info).trim(),
"device_type": match r.info.device_type {
wgpu::DeviceType::IntegratedGpu => "integrated",
wgpu::DeviceType::DiscreteGpu => "discrete",
wgpu::DeviceType::VirtualGpu => "virtual",
wgpu::DeviceType::Cpu => "cpu",
wgpu::DeviceType::Other => "other",
},
"backend": format!("{:?}", r.info.backend),
"size": [r.config.width, r.config.height],
"present_mode": format!("{:?}", r.config.present_mode),
@@ -647,13 +670,36 @@ impl Game<'_> {
"pending_chunks": self.streaming.pending() + self.pending_uploads.len(),
"generated_chunks": self.streaming.generated_total,
"meshed_sections": self.streaming.meshed_total,
"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!({
"width": m.size().width,
"height": m.size().height,
"scale": m.scale_factor(),
"refresh_hz": m.refresh_rate_millihertz().map(|r| r.div_ceil(1000)),
})),
"uptime_seconds": self.started.elapsed().as_secs_f64(),
"server": self.remote_status(),
})
}
}
/// PCI vendor IDs of the GPU makers players have (Apple's is wgpu's Metal value).
fn vendor_name(id: u32) -> String {
match id {
0x10de => "nvidia".into(),
0x1002 | 0x1022 => "amd".into(),
0x8086 => "intel".into(),
0x106b => "apple".into(),
0x5143 => "qualcomm".into(),
0x13b5 => "arm".into(),
0x10005 => "mesa".into(),
0 => String::new(),
other => format!("{other:#06x}"),
}
}
fn key_code(name: &str) -> Option<KeyCode> {
let name = name.to_ascii_lowercase();
let letters = [
@@ -713,6 +759,7 @@ fn key_code(name: &str) -> Option<KeyCode> {
"f1" => KeyCode::F1,
"f2" => KeyCode::F2,
"f3" => KeyCode::F3,
"f4" => KeyCode::F4,
"f5" => KeyCode::F5,
"f11" => KeyCode::F11,
"slash" | "/" => KeyCode::Slash,
+4 -1
View File
@@ -884,6 +884,7 @@ impl Game<'_> {
self.golem_chest_slot(chest, slot, stack)
}
MobEvent::BecomeStatue { mob } => self.golem_become_statue(mob),
MobEvent::EnterHive { mob, hive } => self.bee_enter_hive(mob, hive),
MobEvent::Gift { target, item } => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target)
&& m.saddle_item().is_none()
@@ -2441,7 +2442,9 @@ impl Game<'_> {
consume = true;
eat = sound;
}
None => handled = false,
// Animal.mobInteract still consumes the client click when
// an adult cannot breed, without swinging or taking food.
None => return Ok(true),
}
}
_ => handled = false,
+122 -18
View File
@@ -49,6 +49,7 @@ impl DebugHost for Host<'_, '_> {
impl Game<'_> {
fn open_screen(&self) -> OpenScreen {
match self.screen {
Screen::GameModeSwitcher => OpenScreen::GameModeSwitcher,
Screen::Playing if self.book.is_none() && self.sign_edit.is_none() => OpenScreen::None,
Screen::Paused if !self.pause_menu => OpenScreen::PauseWithoutMenu,
_ => OpenScreen::Other,
@@ -62,6 +63,19 @@ impl Game<'_> {
return false;
};
let pressed = action != KeyAction::Release;
let switcher_open = self.screen == Screen::GameModeSwitcher;
if switcher_open && pressed {
if name == self.settings.keys.get("key.debug.switchGameMode") {
if let Some(switcher) = &mut self.gamemode_switcher {
switcher.cycle();
}
} else if key == KeyCode::Escape {
self.close_gamemode_switcher(false);
} else if matches!(key, KeyCode::F2 | KeyCode::F11) {
return false;
}
return true;
}
// Screens with a text box take every key press first
// (EditBox.keyPressed); releases still reach KeyboardHandler.
let typing = matches!(
@@ -116,6 +130,13 @@ impl Game<'_> {
now,
);
self.debug_keys = keys;
if switcher_open {
if name == binds.get("key.debug.modifier") {
self.close_gamemode_switcher(true);
return true;
}
return false;
}
if !pressed {
return false;
}
@@ -130,7 +151,7 @@ impl Game<'_> {
}
}
/// `Util.getMillis` (positive: KeyboardHandler treats 0 as unset).
fn debug_millis(&self) -> i64 {
pub(super) fn debug_millis(&self) -> i64 {
self.started.elapsed().as_millis() as i64 + 1_000_000
}
/// `KeyboardHandler.tick`: the debug crash countdown.
@@ -159,6 +180,79 @@ impl Game<'_> {
}
Ok(())
}
/// The network charts' samples each tick: `PingDebugMonitor.tick` while
/// they show, `BandwidthDebugMonitor.tick` always.
pub(super) fn tick_debug_charts(&mut self) {
let shown = self.debug && self.debug_charts.network;
let Some(r) = &self.remote else {
// The integrated server answers within the tick.
if shown {
self.debug_charts.ping.log(0);
}
return;
};
let received = r
.session
.counters
.lock()
.unwrap()
.as_ref()
.map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed));
if let Some(total) = received {
self.debug_charts.log_bandwidth(total);
}
if shown {
use horizon_protocol::packets::{play::Serverbound, status::Ping};
let time = self.debug_millis();
self.send(Serverbound::PingRequest(Ping { time }));
}
}
/// The overlay's chart lines (`DebugScreenOverlay`'s "Debug charts").
pub(super) fn debug_chart_lines(&self) -> [String; 3] {
let keys = &self.settings.keys;
let modifier = keys.get("key.debug.modifier");
let key = |mapping: &str| {
let prefix = if modifier == "key.keyboard.unknown" {
String::new()
} else {
format!("{}+", keybinds::display_name(modifier).plain())
};
format!(
"[{prefix}{}]",
keybinds::display_name(keys.get(mapping)).plain()
)
};
let chart = |mapping: &str, name: &str, on: bool| {
format!(
"{} {name} {}",
key(mapping),
if on { "visible" } else { "hidden" }
)
};
let remote = self.remote.is_some();
let c = &self.debug_charts;
[
format!(
"Debug charts: {}; {};",
chart("key.debug.profilingChart", "Profiler", false),
chart(
"key.debug.fpsCharts",
if remote { "fps" } else { "fps + tps" },
c.fps
),
),
format!(
"{}; {}",
chart(
"key.debug.networkCharts",
if remote { "Bandwidth + Ping" } else { "Ping" },
c.network
),
chart("key.debug.lightmapTexture", "Lightmap", c.lightmap),
),
format!("To edit: press {}", key("key.debug.debugOptions")),
]
}
/// `KeyMapping.getTranslatedKeyMessage`.
fn key_text(&self, mapping: &str) -> Text {
keybinds::display_name(self.settings.keys.get(mapping))
@@ -190,7 +284,7 @@ impl Game<'_> {
self.settings.reduced_debug_info || self.ui.rules.bool("reduced_debug_info")
}
/// `Permissions.COMMANDS_GAMEMASTER` (`GameModeCommand.PERMISSION_CHECK`).
fn gamemaster(&self) -> bool {
pub(super) fn gamemaster(&self) -> bool {
self.ui.registries.permission >= 2
}
fn toggle_option(&mut self, key: &str) -> bool {
@@ -206,13 +300,7 @@ impl Game<'_> {
let player = self.player.is_some() && !self.reduced_debug_info();
match action {
DebugAction::ReloadChunks => {
// LevelExtractor.allChanged: every section is rebuilt.
let keys: Vec<(i32, i32)> = self.world.chunks.keys().copied().collect();
for (x, z) in keys {
for sy in 0..horizon_client::chunk::HEIGHT / 16 {
self.world.dirty_sections.insert((x, sy, z));
}
}
self.all_sections_changed();
self.debug_translated("debug.reload_chunks.message");
true
}
@@ -268,10 +356,10 @@ impl Game<'_> {
true
}
DebugAction::SwitchGameMode if self.open_screen() == OpenScreen::None => {
// Minecraft.canSwitchGameMode and the permission; the
// GameModeSwitcherScreen itself is not drawn yet.
if self.player.is_none() || !self.gamemaster() {
self.debug_translated("debug.gamemodes.error");
} else {
self.open_gamemode_switcher();
}
true
}
@@ -324,16 +412,25 @@ impl Game<'_> {
});
true
}
DebugAction::FpsCharts => {
self.debug_charts.toggle_fps(&mut self.debug);
true
}
DebugAction::NetworkCharts => {
self.debug_charts.toggle_network(&mut self.debug);
true
}
DebugAction::LightmapTexture => {
self.debug_charts.toggle_lightmap(&mut self.debug);
true
}
// Screens and overlays Horizon does not draw yet (the debug
// options screen, the profiler and its charts, the lightmap, the
// texture dump): the keys are used up as in vanilla.
// options screen, the profiler and its chart, the texture dump):
// the keys are used up as in vanilla.
DebugAction::DebugOptions
| DebugAction::DumpDynamicTextures
| DebugAction::Profiling
| DebugAction::ProfilingChart
| DebugAction::FpsCharts
| DebugAction::NetworkCharts
| DebugAction::LightmapTexture => true,
| DebugAction::ProfilingChart => true,
DebugAction::ShowHitboxes
| DebugAction::ShowChunkBorders
| DebugAction::SwitchGameMode
@@ -343,8 +440,15 @@ impl Game<'_> {
/// `ServerboundChangeGameModePacket` handled by the integrated server:
/// `GameModeCommand.setGameMode` with its feedback.
pub(super) fn change_game_mode(&mut self, mode: GameMode) {
// On a server the packet decides; Horizon's client does not send it yet.
if self.remote.is_some() {
use horizon_protocol::packets::play::{ChangeGameMode, Serverbound};
let mode = match mode {
GameMode::Survival => 0,
GameMode::Creative => 1,
GameMode::Adventure => 2,
GameMode::Spectator => 3,
};
self.send(Serverbound::ChangeGameMode(ChangeGameMode { mode }));
return;
}
if self.set_game_mode(mode) {
+7 -1
View File
@@ -372,7 +372,13 @@ impl Game<'_> {
let world_dir = std::env::current_dir()?.join(&universe).join(&level_name);
let folder = world_dir.to_string_lossy().into_owned();
let new_world = !world_dir.join("level.dat").exists();
self.open_world(&folder, Some(&level_name), Some(props.seed), game_mode == 1)?;
self.open_world(
&folder,
Some(&level_name),
Some(props.seed),
game_mode == 1,
None,
)?;
if new_world {
self.level.hardcore = props.hardcore;
}
+13 -1
View File
@@ -1552,10 +1552,11 @@ impl Game<'_> {
&& let Some(level) = honey
&& level >= 5
{
// releaseBeesAndResetHoneyLevel (the bees themselves are not modelled).
// releaseBeesAndResetHoneyLevel.
if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) {
self.level_set([target.0, target.1, target.2], reset)?;
}
self.dispenser_empty_hive(target, state);
let bottle = ItemStack::new("minecraft:honey_bottle", 1);
self.post_block_game_event("minecraft:fluid_pickup", [pos.0, pos.1, pos.2], None, None);
return Ok((
@@ -1624,6 +1625,16 @@ impl Game<'_> {
}
Ok((Some(stack), FAIL))
}
/// The bees of a hive a dispenser harvested come out (`BEE_RELEASED`:
/// not at night nor in the rain), through the front of its old state.
fn dispenser_empty_hive(&mut self, target: Pos, old: BlockStateId) {
let facing = self.prop(old, "facing");
self.empty_hive(
[target.0, target.1, target.2],
horizon_client::beehive::facing_step(facing.as_deref()),
horizon_client::beehive::Release::BeeReleased,
);
}
fn shear_beehive(&mut self, target: Pos) -> Result<bool> {
let state = self.block_at(target);
let name = self.dispenser_block_name(target);
@@ -1652,6 +1663,7 @@ impl Game<'_> {
if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) {
self.level_set(p, reset)?;
}
self.dispenser_empty_hive(target, state);
self.post_block_game_event("minecraft:shear", p, None, None);
Ok(true)
}
+5 -1
View File
@@ -233,7 +233,7 @@ impl Game<'_> {
/// EnderEyeItem.useOn: fill an empty End portal frame, then light the
/// portal when the ring of twelve filled frames is complete.
pub(super) fn use_ender_eye(&mut self, stack: &ItemStack) -> Result<bool> {
pub(super) fn use_ender_eye(&mut self, stack: &ItemStack, use_on_block: bool) -> Result<bool> {
if &*stack.item != "minecraft:ender_eye" {
return Ok(false);
}
@@ -247,6 +247,10 @@ impl Game<'_> {
self.throw_ender_eye();
return Ok(true);
};
if !use_on_block {
// EnderEyeItem.use passes on a frame; only useOn can insert an eye.
return Ok(false);
}
if state.properties.get("eye").map(String::as_str) == Some("true") {
// Both useOn and use pass on a filled frame.
return Ok(true);
@@ -0,0 +1,272 @@
//! Model-batch equivalence tests and an opt-in benchmark of the actual loaders.
use super::{armor_stands::ArmorStandAssets, boats::BoatModels, minecarts::CartModels};
use horizon_client::mobs::{EntityModelDocument, Part, load_model};
use serde_json::{Value, json};
use std::{collections::BTreeMap, fs, hint::black_box, path::Path, time::Instant};
const WOODS: [&str; 11] = [
"oak",
"spruce",
"birch",
"jungle",
"acacia",
"dark_oak",
"mangrove",
"cherry",
"bamboo",
"pale_oak",
"test_wood",
];
const CARTS: [&str; 6] = [
"minecart",
"chest_minecart",
"hopper_minecart",
"furnace_minecart",
"tnt_minecart",
"command_block_minecart",
];
fn fixture() -> Value {
let mut all = serde_json::Map::new();
let part = json!({
"pose": [1,2,3,0.25,-0.5,0.75,1,2,0.5],
"polygons": [[[0,0,0,0,0],[1,0,0,1,0],[1,1,0,1,1],[0,1,0,0,1]]],
"normals": [[0,0,1]],
"children": {"root": {"children": {"bone": {"pose": [4,5,6]}}}, "other": {}}
});
for wood in WOODS {
for prefix in ["boat", "chest_boat"] {
all.insert(format!("minecraft:{prefix}/{wood}#main"), part.clone());
}
}
for cart in CARTS {
all.insert(format!("minecraft:{cart}#main"), part.clone());
}
for model in ["player", "armor_stand", "armor_stand_small"] {
for layer in ["helmet", "chestplate", "leggings", "boots"] {
all.insert(format!("minecraft:{model}#{layer}"), part.clone());
}
}
for model in ["armor_stand", "armor_stand_small"] {
all.insert(format!("minecraft:{model}#main"), part.clone());
}
// Discovery must exclude other models and non-main boat layers.
all.insert("minecraft:boat/oak#water_patch".into(), part.clone());
all.insert("minecraft:unrelated#main".into(), part);
Value::Object(all)
}
struct FixtureRoot(std::path::PathBuf);
impl FixtureRoot {
fn new() -> Self {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let next = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let root = std::env::temp_dir().join(format!(
"horizon-entity-models-{}-{next}",
std::process::id()
));
fs::create_dir(&root).unwrap();
Self(root)
}
}
impl Drop for FixtureRoot {
fn drop(&mut self) {
fs::remove_dir_all(&self.0).unwrap();
}
}
// Preserve the previous production algorithm: one discovery parse, then a full
// file read/parse through load_model for each of the 42 selected layers.
fn baseline(root: &Path) -> BTreeMap<String, Part> {
let mut models = BTreeMap::new();
if let Ok(bytes) = fs::read(root.join("entity-models.json"))
&& let Ok(Value::Object(all)) = serde_json::from_slice::<Value>(&bytes)
{
for key in all.keys() {
for (prefix, label) in [
("minecraft:boat/", "boat"),
("minecraft:chest_boat/", "chest_boat"),
] {
if let Some(wood) = key
.strip_prefix(prefix)
.and_then(|k| k.strip_suffix("#main"))
&& let Some(part) = load_model(root, key)
{
models.insert(format!("{label}/{wood}"), part);
}
}
}
}
for cart in CARTS {
if let Some(part) = load_model(root, &format!("minecraft:{cart}#main")) {
models.insert(format!("cart/{cart}"), part);
}
}
for slot in ["helmet", "chestplate", "leggings", "boots"] {
for model in ["player", "armor_stand", "armor_stand_small"] {
if let Some(part) = load_model(root, &format!("minecraft:{model}#{slot}")) {
models.insert(format!("{model}/{slot}"), part);
}
}
}
// The fixture contains only entity-models.json; armor equipment is absent.
let _ = fs::read_dir(root.join("assets/minecraft/equipment"));
for model in ["armor_stand", "armor_stand_small"] {
if let Some(part) = load_model(root, &format!("minecraft:{model}#main")) {
models.insert(format!("{model}/main"), part);
}
}
models
}
fn optimized(root: &Path) -> BTreeMap<String, Part> {
let document = EntityModelDocument::load(root).ok();
let boats = BoatModels::load(document.as_ref());
let carts = CartModels::load(document.as_ref());
let armor = ArmorStandAssets::load(root, document.as_ref());
let mut models = BTreeMap::new();
for (label, group) in [("boat", boats.models), ("chest_boat", boats.chest_models)] {
for (wood, part) in group {
models.insert(format!("{label}/{wood}"), part);
}
}
for (kind, part) in carts.models {
models.insert(
format!("cart/{}", kind.id().trim_start_matches("minecraft:")),
part,
);
}
for ((slot, small), part) in armor.layers {
let model = if small {
"armor_stand_small"
} else {
"armor_stand"
};
models.insert(format!("{model}/{slot}"), part);
}
for (slot, part) in armor.player {
models.insert(format!("player/{slot}"), part);
}
for (model, part) in [
("armor_stand", armor.main),
("armor_stand_small", armor.small),
] {
if let Some(part) = part {
models.insert(format!("{model}/main"), part);
}
}
models
}
fn assert_equivalent(root: &Path) {
// Debug includes every part name, pose, polygon normal/vertex and child.
assert_eq!(
format!("{:?}", baseline(root)),
format!("{:?}", optimized(root))
);
}
#[test]
fn entity_model_batches_preserve_parts_missing_layers_and_load_failures() {
let root = FixtureRoot::new();
assert_equivalent(&root.0); // missing file
let file = root.0.join("entity-models.json");
for bytes in [b"{".as_slice(), b"null", b"[]", b"{}"] {
fs::write(&file, bytes).unwrap();
assert_equivalent(&root.0);
}
let mut all = fixture();
fs::write(&file, serde_json::to_vec(&all).unwrap()).unwrap();
assert_equivalent(&root.0);
assert_eq!(optimized(&root.0).len(), 42);
all.as_object_mut()
.unwrap()
.remove("minecraft:armor_stand_small#main");
all.as_object_mut()
.unwrap()
.remove("minecraft:boat/oak#main");
fs::write(&file, serde_json::to_vec(&all).unwrap()).unwrap();
assert_equivalent(&root.0);
assert_eq!(optimized(&root.0).len(), 40);
let document = EntityModelDocument::load(&root.0).unwrap();
let mut first = document.model("minecraft:armor_stand#main").unwrap();
first.children.clear();
assert!(
!document
.model("minecraft:armor_stand#main")
.unwrap()
.children
.is_empty()
);
}
#[test]
fn armor_equipment_loads_without_an_entity_model_document() {
let root = FixtureRoot::new();
let equipment = root.0.join("assets/minecraft/equipment");
fs::create_dir_all(&equipment).unwrap();
fs::write(
equipment.join("leather.json"),
serde_json::to_vec(&json!({"layers": {"humanoid": [{
"texture": "minecraft:leather", "dyeable": {"color_when_undyed": 0x123456}
}]}}))
.unwrap(),
)
.unwrap();
fs::write(equipment.join("invalid.json"), b"{").unwrap();
let assets = ArmorStandAssets::load(&root.0, None);
assert!(assets.main.is_none());
assert!(assets.layers.is_empty());
assert_eq!(
assets.equipment["minecraft:leather"]["humanoid"],
("entity/equipment/humanoid/leather".into(), Some(0x123456))
);
assert!(!assets.equipment.contains_key("minecraft:invalid"));
}
#[test]
#[ignore = "opt-in benchmark; requires ENTITY_MODEL_BENCH_DOCUMENT"]
fn entity_model_document_benchmark() {
let input = std::env::var("ENTITY_MODEL_BENCH_DOCUMENT").unwrap();
let root = FixtureRoot::new();
let bytes = fs::read(&input).unwrap();
fs::write(root.0.join("entity-models.json"), &bytes).unwrap();
assert_equivalent(&root.0);
let model_count = optimized(&root.0).len();
let repetitions: usize = std::env::var("ENTITY_MODEL_BENCH_REPETITIONS")
.unwrap_or_else(|_| "15".into())
.parse()
.unwrap();
assert!(repetitions > 0);
for _ in 0..3 {
black_box(baseline(black_box(&root.0)));
black_box(optimized(black_box(&root.0)));
}
let mut before = Vec::new();
let mut after = Vec::new();
for i in 0..repetitions {
for optimized_first in [i % 2 == 0, i % 2 != 0] {
let started = Instant::now();
if optimized_first {
black_box(optimized(black_box(&root.0)));
after.push(started.elapsed().as_secs_f64() * 1000.0);
} else {
black_box(baseline(black_box(&root.0)));
before.push(started.elapsed().as_secs_f64() * 1000.0);
}
}
}
before.sort_by(f64::total_cmp);
after.sort_by(f64::total_cmp);
let old = before[repetitions / 2];
let new = after[repetitions / 2];
println!(
"{}",
json!({
"document_bytes": bytes.len(), "selected_models": model_count,
"warmup_pairs": 3, "repetitions": repetitions,
"baseline_ms": before, "optimized_ms": after,
"baseline_median_ms": old, "optimized_median_ms": new, "speedup": old / new
})
);
}
+1 -1
View File
@@ -123,7 +123,7 @@ impl Game<'_> {
{
log::info!(
"Horizon: reconnecting to {} in {} s",
retry.address,
horizon_client::net::shown_address(&retry.address),
retry.seconds_left(std::time::Instant::now())
);
*slot = Some(retry);
+28 -34
View File
@@ -2,8 +2,10 @@
//! from a block face, boosting a gliding player, the 1.15 horizontal
//! acceleration and 0.04 lift, the flight-duration lifetime, explosion
//! damage with line of sight, and the client explosion (`createFireworks`).
use super::{Game, Hit, view_vector};
use super::{Game, Hit, item_draw::owner_at, view_vector};
use horizon_assets::item_model::DisplayContext;
use horizon_client::{
block_entity_render::vertex_light,
collisions::SceneCollisions,
items::ItemStack,
mesher::Vertex,
@@ -27,7 +29,8 @@ pub(super) struct Rocket {
/// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on
/// the first block it hits.
angled: bool,
icon: Option<String>,
/// `DATA_ID_FIREWORKS_ITEM`: the stack it was launched from.
item: ItemStack,
}
impl Rocket {
/// Position and motion (the dispenser parity fixture).
@@ -61,7 +64,7 @@ impl Game<'_> {
explosions,
attached,
angled: false,
icon: Some("item/firework_rocket".into()),
item: stack.clone(),
}
}
/// `FireworkRocketItem.useOn`: launch from the clicked point.
@@ -244,44 +247,35 @@ impl Game<'_> {
self.particles
.fireworks(at, v, r.explosions.clone(), camera);
}
/// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera,
/// lit at the rocket's light probe.
pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
let up = right.cross(forward).normalize_or_zero();
let orientation = glam::Mat4::from_quat(self.camera_orientation());
for r in self.rockets.iter().filter(|r| !r.attached) {
let Some(s) = r
.icon
.as_ref()
.and_then(|n| self.res.atlas.sprites.get(n))
.copied()
else {
continue;
};
let p = glam::DVec3::new(
r.previous.x + (r.position.x - r.previous.x) * alpha,
r.previous.y + (r.position.y - r.previous.y) * alpha,
r.previous.z + (r.position.z - r.previous.z) * alpha,
) - camera;
let h = 0.25;
let c = [
p - right * h - up * h,
p + right * h - up * h,
p + right * h + up * h,
p - right * h + up * h,
];
for (v, uv) in c
.iter()
.zip([[s.u0, s.v1], [s.u1, s.v1], [s.u1, s.v0], [s.u0, s.v0]])
{
out.push(Vertex {
normal: [0; 4],
pos: v.as_vec3().to_array(),
uv,
layer: 0,
color: 0xFFFF_FFFF,
light: 240 | 240 << 8,
});
);
// `updateForNonLiving`: GROUND, owned by the rocket.
let owner = owner_at(p.to_array(), 0.0, "minecraft:firework_rocket");
let state = self.resolve_item(&r.item, DisplayContext::Ground, Some(&owner), 0);
if state.is_empty() {
continue;
}
let mut pose = glam::Mat4::from_translation((p - camera).as_vec3()) * orientation;
if r.angled {
pose *= glam::Mat4::from_rotation_z(std::f32::consts::PI)
* glam::Mat4::from_rotation_y(std::f32::consts::PI)
* glam::Mat4::from_rotation_x(std::f32::consts::FRAC_PI_2);
}
// getLightProbePosition: the eye, 0.85 of its 0.25 height.
let light = self.world.light(
p.x.floor() as i32,
(p.y + 0.2125).floor() as i32,
p.z.floor() as i32,
);
self.submit_item_world(&state, pose, vertex_light(light), out);
}
}
}
+254
View File
@@ -0,0 +1,254 @@
//! Play with friends, host side: "Invite friends" 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
//! configured adds a short code and a fallback. The integrated server is the
//! 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_friends::{Host, HostConfig, HostEvent, PathMode, host::DEFAULT_PORT, reach, stun};
use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION};
use std::time::{Duration, Instant};
pub(super) struct Sharing {
host: Host,
/// Sharing opened the world to LAN, so stopping closes it again.
opened_lan: bool,
code: Option<String>,
/// Wrong codes tried so far.
wrong: u32,
notice: Option<String>,
copied: Option<Instant>,
/// Sessions carried directly and through the relay so far.
paths: (u32, u32),
}
pub const HELP: &[&str] = &[
"friends host share the open world behind an invite code",
"friends stop stop sharing",
"friends status the code, how friends reach this host, the guests",
];
/// `HORIZON_STUN_SERVERS`, else `friendsStun` in horizon.txt, else the defaults.
fn stun_servers() -> Vec<String> {
if std::env::var_os("HORIZON_STUN_SERVERS").is_some() {
return stun::servers_from_env();
}
let dir = std::env::current_dir().unwrap_or_default();
match horizon_client::ui_theme::preference(&dir, "friendsStun") {
Some(list) => stun::parse_servers(&list),
None => stun::servers_from_env(),
}
}
fn env_flag(name: &str, default: bool) -> bool {
std::env::var(name).map_or(default, |v| v != "0")
}
impl Game<'_> {
/// Start sharing the open world.
pub(super) fn friends_start(&mut self) -> Result<()> {
if self.friends.is_some() {
return Ok(());
}
if self.remote.is_some() || self.title.is_some() {
return Err("open a singleplayer world first".into());
}
let opened_lan = self.lan.is_none();
if opened_lan {
// ShareToLanScreen's defaults, as the world options screen offers them.
self.lan_open(LanSettings {
port: horizon_client::lan::available_port(),
guest_commands: false,
force_game_mode: true,
})?;
}
let port = self.lan_port().ok_or("the world isn't open to LAN")?;
let host = match Host::start(HostConfig {
lan: std::net::SocketAddr::from(([127, 0, 0, 1], port)),
protocol: PROTOCOL_VERSION,
game: GAME_VERSION.to_owned(),
relay: horizon_client::net::friends_relay_setting(),
path: PathMode::from_env(),
port: std::env::var("HORIZON_FRIENDS_PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(DEFAULT_PORT),
reach: reach::Options {
// HORIZON_FRIENDS_UPNP=0 leaves the router alone.
map_port: env_flag("HORIZON_FRIENDS_UPNP", true),
stun: stun_servers(),
// Both ends on one machine (tests).
loopback: env_flag("HORIZON_FRIENDS_LOOPBACK", false),
},
}) {
Ok(h) => h,
Err(e) => {
if opened_lan {
self.lan_close(true);
}
return Err(e.into());
}
};
self.friends = Some(Sharing {
host,
opened_lan,
code: None,
wrong: 0,
notice: None,
copied: None,
paths: (0, 0),
});
Ok(())
}
/// Stop sharing: the code ends (direct port closed, router mapping
/// deleted); the world closes to LAN again if sharing opened it.
pub(super) fn friends_stop(&mut self) {
let Some(mut sharing) = self.friends.take() else {
return;
};
sharing.host.stop();
if sharing.opened_lan {
self.lan_close(true);
} else {
self.system_message(Text::literal("Stopped sharing the invite code."));
}
}
/// The LAN server is closing: the code goes with it.
pub(super) fn friends_lan_closed(&mut self) {
if let Some(mut sharing) = self.friends.take() {
sharing.host.stop();
}
}
/// New codes and sessions, once a tick and while the pause menu is drawn.
pub(super) fn tick_friends(&mut self) {
let Some(sharing) = self.friends.as_mut() else {
return;
};
let mut announce = false;
for event in sharing.host.poll() {
match event {
HostEvent::Code(code) => {
if sharing.code.is_some() && sharing.wrong >= horizon_friends::host::MAX_WRONG {
sharing.notice = Some(
"Someone kept trying a wrong short code, so it changed.".to_owned(),
);
sharing.wrong = 0;
}
announce = sharing.code.is_none();
sharing.code = Some(code);
}
HostEvent::WrongCode { count } => {
sharing.wrong = count;
sharing.notice = Some("Someone tried a wrong code.".to_owned());
}
HostEvent::Connected { direct: true, .. } => sharing.paths.0 += 1,
HostEvent::Connected { direct: false, .. } => sharing.paths.1 += 1,
HostEvent::Disconnected { .. } => {}
}
}
if announce {
self.system_message(Text::literal(
"Your invite code is ready in the pause menu: copy it and send it to your friends.",
));
}
}
pub(super) fn friends_copy(&mut self) {
let Some(code) = self.friends.as_ref().and_then(|s| s.code.clone()) else {
return;
};
use horizon_client::clipboard::Clipboard;
self.clipboard.set(&code);
if let Some(s) = self.friends.as_mut() {
s.copied = Some(Instant::now());
}
}
/// What the pause menu 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 Some(s) = &self.friends else {
return FriendsView {
shown: self.remote.is_none(),
..FriendsView::default()
};
};
let state = s.host.state();
let mut status = if s.code.is_none() {
"Finding how friends can reach you…".to_owned()
} else {
state.summary.clone()
};
if let Some(short) = &state.short {
status.push_str(&format!(" Short code for the relay: {short}."));
}
if let Some(problem) = &state.relay_problem {
status.push(' ');
status.push_str(problem);
}
let reachable = matches!(
state.verdict,
Some(reach::Verdict::Mapped(_) | reach::Verdict::Public)
) || state.short.is_some();
FriendsView {
shown: true,
sharing: true,
code: s.code.clone(),
status,
reachable,
help: (!reachable && s.code.is_some()).then(|| reach::HELP_URL.to_owned()),
guests,
notice: s.notice.clone(),
copied: s
.copied
.is_some_and(|t| t.elapsed() < Duration::from_secs(2)),
}
}
/// `horizon-ctl friends ...`.
pub(super) fn friends_control(&mut self, words: &[&str]) -> Result<Option<serde_json::Value>> {
use serde_json::json;
if words[0] != "friends" {
return Ok(None);
}
match words.get(1).copied() {
Some("host") => {
self.friends_start()?;
Ok(Some(json!({ "ok": true, "lan_port": self.lan_port() })))
}
Some("stop") => {
self.friends_stop();
Ok(Some(json!({ "ok": true })))
}
Some("status") => {
self.tick_friends();
let view = self.friends_view();
let state = self.friends.as_ref().map(|s| s.host.state());
Ok(Some(json!({
"sharing": view.sharing,
"code": view.code,
"short": state.as_ref().and_then(|s| s.short.as_ref().map(ToString::to_string)),
"summary": view.status,
"reachable": view.reachable,
"verdict": state.as_ref().and_then(|s| s.verdict.as_ref().map(|v| format!("{v:?}"))),
"direct_port": state.as_ref().map(|s| s.port),
"sessions": self.friends.as_ref().map_or(0, |s| s.host.sessions()),
"direct": self.friends.as_ref().map_or(0, |s| s.paths.0),
"relayed": self.friends.as_ref().map_or(0, |s| s.paths.1),
"guests": view.guests,
"lan_port": self.lan_port(),
})))
}
_ => Err("friends host|stop|status".into()),
}
}
}
@@ -0,0 +1,86 @@
//! The non-pausing F3+F4 screen (`GameModeSwitcherScreen`).
use super::{Game, ItemStack, Screen};
use horizon_client::{
game_mode_switcher::{GameModeSwitcher, ICONS, MODES, slot_origin},
hud::HudBatch,
keybinds,
text::Text,
};
impl Game<'_> {
pub(super) fn open_gamemode_switcher(&mut self) {
self.gamemode_switcher = Some(GameModeSwitcher::new(self.mode, self.previous_mode));
self.screen = Screen::GameModeSwitcher;
self.keys.clear();
self.left = false;
self.right = false;
self.mining = None;
self.capture(false);
}
pub(super) fn close_gamemode_switcher(&mut self, apply: bool) {
let selected = self.gamemode_switcher.take().map(|s| s.selected);
self.screen = Screen::Playing;
self.capture(true);
if apply
&& self.player.is_some()
&& self.gamemaster()
&& let Some(mode) = selected
&& mode != self.mode
{
self.change_game_mode(mode);
}
}
pub(super) fn draw_gamemode_switcher(&mut self, batch: &mut HudBatch) {
let (w, h) = (batch.width as i32, batch.height as i32);
let Some(switcher) = &mut self.gamemode_switcher else {
return;
};
switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32));
let selected = switcher.selected;
let atlas = &self.res.atlas;
batch.sprite_region(
atlas,
"gui/container/gamemode_switcher",
[(w / 2 - 62) as f32, (h / 2 - 58) as f32, 125.0, 75.0],
128.0,
128.0,
);
let title = Text::translate(&format!("gameMode.{}", selected.name()), &[]);
let help = Text::translate(
"debug.gamemodes.select_next",
&[
keybinds::display_name(self.settings.keys.get("key.debug.switchGameMode"))
.with_color(0x55FFFF),
],
);
for (text, y) in [(title, h / 2 - 51), (help, h / 2 + 5)] {
let x = w / 2 - (HudBatch::text_width(atlas, &text.plain()) / 2.0) as i32;
batch.text_styled(atlas, &text, x as f32, y as f32, u32::MAX, true);
}
for (index, mode) in MODES.into_iter().enumerate() {
let (x, y) = slot_origin(w, h, index);
batch.sprite(
&self.res.atlas,
"gui/sprites/gamemode_switcher/slot",
x as f32,
y as f32,
);
if mode == selected {
batch.sprite(
&self.res.atlas,
"gui/sprites/gamemode_switcher/selection",
x as f32,
y as f32,
);
}
self.draw_item_model(
batch,
&ItemStack::new(ICONS[index], 1),
(x + 5) as f32,
(y + 5) as f32,
);
}
}
}
+1
View File
@@ -450,6 +450,7 @@ impl Game<'_> {
/// IntegratedServer.unpublishServer: the guests are sent away.
pub(super) fn lan_close(&mut self, announce: bool) {
self.friends_lan_closed();
let Some(mut host) = self.lan.take() else {
return;
};
@@ -412,6 +412,32 @@ impl Game<'_> {
}
}
S::ChatCommand(c) => self.guest_command(host, conn, &c.command),
S::ChangeGameMode(p) if host.hub.guests[gi].permission >= 2 => {
if let Some(mode) = usize::try_from(p.mode)
.ok()
.and_then(|index| horizon_client::command::args::GameMode::ALL.get(index))
{
let lines = self.as_guest(host, conn, |g| {
g.chat_capture = Some(Vec::new());
g.change_game_mode(*mode);
g.chat_capture
.take()
.unwrap_or_default()
.iter()
.map(|t| horizon_client::lan::data::component_nbt(&t.component()))
.collect::<Vec<_>>()
});
for content in lines.unwrap_or_default() {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content,
overlay: false,
}),
);
}
}
}
S::Unknown(8, payload) => {
// A signed command: the text comes first.
if let Ok(text) = horizon_protocol::buf::Reader::new(&payload).string(32767) {
+20 -7
View File
@@ -333,13 +333,26 @@ impl Game<'_> {
o.port.shortcut(shortcut, &mut self.clipboard);
return;
}
if !o.port.key(key, ctrl, false)
&& !ctrl
&& let Some(text) = &event.text
{
let digits: String = text.chars().filter(char::is_ascii_digit).collect();
if !digits.is_empty() {
o.port.insert_text(&digits);
if !o.port.key(key, ctrl, false) && !ctrl {
self.world_options_text(event.text.as_deref());
}
}
/// Digits typed into the port field (the keyboard, or a controller's
/// on-screen keyboard), and its backspace.
pub(super) fn world_options_text(&mut self, text: Option<&str>) {
let Some(o) = self.world_options.as_mut().filter(|o| o.port.focused) else {
return;
};
match text {
Some(text) => {
let digits: String = text.chars().filter(char::is_ascii_digit).collect();
if !digits.is_empty() {
o.port.insert_text(&digits);
}
}
None => {
o.port
.key(winit::keyboard::KeyCode::Backspace, false, false);
}
}
}
+18
View File
@@ -128,6 +128,24 @@ impl Game<'_> {
}
false
}
/// The pattern buttons a controller can focus (GUI origin relative).
pub(super) fn loom_targets(&self) -> Vec<[f32; 4]> {
let Some(loom) = self.station.as_ref().map(|s| &s.loom).filter(|l| l.display) else {
return Vec::new();
};
(0..16)
.filter(|i| (i / 4 + loom.start_row) * 4 + i % 4 < loom.patterns.len())
.map(|i| {
let (row, column) = (i / 4, i % 4);
[
60.0 + column as f32 * BUTTON,
13.0 + row as f32 * BUTTON,
BUTTON,
BUTTON,
]
})
.collect()
}
/// `LoomScreen.mouseDragged` on the scroller.
pub(super) fn loom_drag(&mut self) {
let Some(size) = self
@@ -159,6 +159,10 @@ impl Containers<'_> {
});
}
let entity = self.world.block_entities.get(&pos)?;
// A beehive keeps bees, not items: it is no `Container`.
if matches!(entity, BlockEntity::Beehive(_)) {
return None;
}
let kind = match (entity, name) {
(BlockEntity::Furnace(_), _) => Kind::Furnace,
(BlockEntity::Crafter(_), _) => Kind::Crafter,
+2 -4
View File
@@ -191,7 +191,7 @@ pub(super) struct CartModels {
pub models: HashMap<CartKind, Part>,
}
impl CartModels {
pub fn load(root: &std::path::Path) -> Self {
pub fn load(document: Option<&horizon_client::mobs::EntityModelDocument>) -> Self {
let kinds = [
CartKind::Rideable,
CartKind::Chest,
@@ -202,9 +202,7 @@ impl CartModels {
];
let models = kinds
.into_iter()
.filter_map(|k| {
horizon_client::mobs::load_model(root, &format!("{}#main", k.id())).map(|m| (k, m))
})
.filter_map(|k| document?.model(&format!("{}#main", k.id())).map(|m| (k, m)))
.collect();
Self { models }
}
+8 -2
View File
@@ -26,13 +26,16 @@ impl Game<'_> {
}
/// Open the options screens (OptionsScreen) from the title or pause menu.
pub(super) fn open_options(&mut self, from_title: bool) {
self.open_options_at(from_title, Page::Main);
}
pub(super) fn open_options_at(&mut self, from_title: bool, page: Page) {
// Gameplay keys must not stay held behind the options screen, where
// bindings can also change before the physical key is released.
self.keys.clear();
self.screen = Screen::Options;
self.options_from_title = from_title;
let ui = &mut self.ui.options;
ui.open(!from_title && self.title.is_none());
ui.open_at(!from_title && self.title.is_none(), page);
let root = self.options.resources.clone();
ui.languages = lang::available(&[&root]);
self.refresh_pack_lists();
@@ -240,7 +243,10 @@ impl Game<'_> {
has_screen: self.title.is_some() || self.screen != super::Screen::Playing,
has_overlay: false,
};
framerate_limit(self.settings.max_fps as i32, context)
let limit = framerate_limit(self.settings.max_fps as i32, context);
self.settings
.horizon
.battery_limit(limit, self.title.is_none(), self.focused)
}
/// `Minecraft.runTick`'s frame limiter: `FramerateLimiter.limitDisplayFPS`
/// below 260 frames per second, sleeping then spin-waiting until the
+9 -12
View File
@@ -255,7 +255,7 @@ impl Game<'_> {
if down && !self.pad_focused() {
return Ok(());
}
let playing = self.title.is_none() && self.screen == Screen::Playing;
let playing = !self.pad_in_menu();
if down && playing && !self.captured && self.focused {
// Like a click into the window: take the pointer.
self.capture(true);
@@ -315,6 +315,11 @@ impl Game<'_> {
/// B and Start: what Escape does where the pad is.
pub(super) fn pad_back(&mut self) -> Result<()> {
// The options open over the title screen too: they come first, as
// for the keyboard's Escape.
if self.screen == Screen::Options {
return self.options_key(KeyCode::Escape, None);
}
if let Some(title) = self.title.as_mut() {
title.escape();
return Ok(());
@@ -340,11 +345,7 @@ impl Game<'_> {
/// The left stick as the move vector, while playing.
pub(super) fn pad_move(&self) -> Option<[f32; 2]> {
let settings = &self.settings.controller;
if !settings.enabled
|| self.title.is_some()
|| self.screen != Screen::Playing
|| !self.pad_focused()
{
if !settings.enabled || self.pad_in_menu() || !self.pad_focused() {
return None;
}
gamepad::move_vector(self.pad.state.left, settings.move_deadzone)
@@ -353,12 +354,7 @@ impl Game<'_> {
/// The right stick turns the view, once per frame (`Entity.turn`).
pub(super) fn pad_look(&mut self, seconds: f32) {
let settings = &self.settings.controller;
if !settings.enabled
|| self.title.is_some()
|| self.screen != Screen::Playing
|| self.player.is_none()
|| !self.pad_focused()
{
if !settings.enabled || self.pad_in_menu() || self.player.is_none() || !self.pad_focused() {
return;
}
// A long frame (a hitch) must not spin the view.
@@ -478,6 +474,7 @@ impl Game<'_> {
"reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis,
})),
"in_use": self.pad.in_use,
"menu": self.pad_menu_status(),
"held": held,
"left": s.left,
"right": s.right,
+713 -79
View File
@@ -1,17 +1,29 @@
//! A controller in menus, screens and inventories (Horizon's own;
//! docs/controllers.md): a virtual cursor the left stick moves and the
//! D-pad steps between slots and buttons, with A, X and the stick feeding
//! the screens the same pointer events a mouse sends. Every screen keeps
//! its mouse behaviour (drags, sliders, scrollbars) with no pad code of its
//! own.
//! docs/controllers.md). Two ways to drive them, picked in the controller
//! options:
//!
//! - **Focus** (console-style): a highlight steps between the widgets, list
//! rows, fields and slots each screen registers (`widgets::target_as`)
//! with vanilla's arrow-key navigation; A presses the focused one, the
//! bumpers switch tabs, left/right move a focused slider, A on a text field
//! opens the on-screen keyboard (`osk`).
//! - **Pointer**: a virtual cursor the left stick moves and the D-pad steps
//! between slots and buttons.
//!
//! Both feed the screens the same pointer events a mouse sends (the pointer
//! sits on the focused widget, hidden), so every screen keeps its mouse
//! behaviour (drags, sliders, scrollbars, hover highlights) with no pad code
//! of its own. A screen with nothing registered falls back to the pointer,
//! and a right stick click swaps modes for the open screen.
use super::{Game, Screen};
use horizon_client::{
Result,
creative::Creative,
gamepad::{self, Button},
gamepad::{self, Button, MenuNav, Rect},
hud::{HudBatch, rgba},
options_ui::{Event, Page},
widgets,
osk::{self, Keyboard},
widgets::{self, Kind, Target},
};
use std::time::Instant;
use winit::{
@@ -19,7 +31,7 @@ use winit::{
dpi::PhysicalPosition,
event::{DeviceId, ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent},
event_loop::ActiveEventLoop,
keyboard::KeyCode,
keyboard::{KeyCode, NamedKey},
};
/// D-pad auto-repeat: the first step at once, the next after a pause.
@@ -27,6 +39,23 @@ const REPEAT_DELAY: f32 = 0.35;
const REPEAT_EVERY: f32 = 0.09;
/// Lines per second the right stick scrolls at full tilt.
const SCROLL_SPEED: f32 = 12.0;
/// How far the stick must lean to step focus.
const STICK_STEP: f32 = 0.55;
/// Scrolls a step may try to reveal the next row of a list.
const SCROLL_TRIES: u8 = 4;
/// A focus step that ran off the visible part of a list: the list was
/// scrolled and the step runs again once a new frame is drawn. When the
/// targets didn't move (nothing scrolled), the step takes vanilla's vague
/// pass instead.
#[derive(Clone)]
struct Pending {
button: Button,
from: Rect,
generation: u64,
tries: u8,
before: Vec<Rect>,
}
#[derive(Default)]
pub(super) struct MenuCursor {
@@ -45,12 +74,31 @@ pub(super) struct MenuCursor {
os_hidden: bool,
/// Polls since a menu opened (its widgets are drawn after one frame).
open_polls: u32,
/// Focus mode: the focused target as last drawn.
focus: Option<Target>,
/// The left stick's step direction last poll.
stick: Option<Button>,
/// A right stick click swapped modes for this screen.
swapped: bool,
pending: Option<Pending>,
/// The focused slider being nudged and where the pad put its handle.
nudge: Option<(Rect, f32)>,
/// Steps since the held direction went down (sliders speed up).
repeats: u32,
/// The on-screen keyboard, open over a text field.
pub(super) osk: Option<Keyboard>,
/// The keyboard was closed on this screen (it doesn't open by itself again).
osk_dismissed: bool,
}
impl Game<'_> {
/// A menu, a screen or the title is open: the pad drives a cursor.
/// A menu, a screen, the title, a sign or a book is open: the pad drives
/// it instead of the player.
pub(super) fn pad_in_menu(&self) -> bool {
self.title.is_some() || self.screen != Screen::Playing
self.title.is_some()
|| self.screen != Screen::Playing
|| self.sign_edit.is_some()
|| self.book.is_some()
}
fn gui_scale(&self) -> Option<HudBatch> {
@@ -59,46 +107,96 @@ impl Game<'_> {
.map(|r| HudBatch::new([r.config.width, r.config.height]))
}
/// Where focus can land: buttons drawn last frame, and the slots and
/// tabs of inventories (centres, GUI pixels).
fn pad_targets(&self) -> Vec<(f32, f32)> {
let mut targets: Vec<(f32, f32)> = widgets::last()
/// Focus mode is on for the open screen.
fn pad_focus_mode(&self) -> bool {
(self.settings.controller.menu_nav == MenuNav::Focus) != self.pad.menu.swapped
}
/// Where focus can land: buttons drawn last frame, every registered
/// target (sliders, fields, rows, Horizon-style widgets), and the slots
/// and tabs of inventories (GUI pixels), on screen.
fn pad_targets(&self) -> Vec<Target> {
let mut targets = self.pad_all_targets();
if let Some(batch) = self.gui_scale() {
let (w, h) = (batch.width + 0.5, batch.height + 0.5);
targets.retain(|t| {
let [x, y, tw, th] = t.rect;
x >= -0.5 && y >= -0.5 && x + tw <= w && y + th <= h
});
}
targets
}
fn pad_all_targets(&self) -> Vec<Target> {
let mut targets: Vec<Target> = widgets::last()
.iter()
.filter(|w| w.enabled)
.map(|w| (w.x + w.w / 2.0, w.y + w.h / 2.0))
.chain(
widgets::last_targets()
.into_iter()
.map(|[x, y, w, h]| (x + w / 2.0, y + h / 2.0)),
)
.map(|w| Target {
rect: [w.x, w.y, w.w, w.h],
kind: Kind::Button,
})
.collect();
if self.title.is_some() {
for t in widgets::last_targets() {
// A Horizon button is 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 {
targets.push(t);
}
}
if self.title.is_some() || self.sign_edit.is_some() || self.book.is_some() {
return targets;
}
let Some(batch) = self.gui_scale() else {
return targets;
};
let slot = |x: f32, y: f32| Target {
rect: [x, y, 16.0, 16.0],
kind: Kind::Slot,
};
match self.screen {
Screen::Inventory => {
let (ox, oy) = self.inventory_origin(&batch);
targets.extend(self.slots().into_iter().map(|i| {
let (x, y) = self.slot_position(i);
(ox + x + 8.0, oy + y + 8.0)
slot(ox + x, oy + y)
}));
targets.extend(
self.station_targets()
.into_iter()
.map(|[x, y, w, h]| Target {
rect: [ox + x, oy + y, w, h],
kind: Kind::Button,
}),
);
targets.extend(self.recipe_book_targets());
}
Screen::Creative => {
let (ox, oy) = Self::creative_origin(&batch);
for r in 0..5 {
if self.creative_inventory_open() {
targets.extend(self.slots().into_iter().map(|i| {
let (x, y) = self.slot_position(i);
slot(ox + x, oy + y)
}));
} else {
for r in 0..5 {
for c in 0..9 {
targets.push(slot(
ox + 9.0 + c as f32 * 18.0,
oy + 18.0 + r as f32 * 18.0,
));
}
}
for c in 0..9 {
targets.push((ox + 17.0 + c as f32 * 18.0, oy + 26.0 + r as f32 * 18.0));
targets.push(slot(ox + 9.0 + c as f32 * 18.0, oy + 112.0));
}
}
for c in 0..9 {
targets.push((ox + 17.0 + c as f32 * 18.0, oy + 120.0));
}
for t in &self.creative_screen.tabs {
for (i, t) in self.creative_screen.tabs.iter().enumerate() {
let (x, y) = Creative::tab_position(t);
targets.push((ox + x + 13.0, oy + y + 16.0));
targets.push(Target {
rect: [ox + x, oy + y, 26.0, 32.0],
kind: Kind::Tab(i == self.creative_screen.selected),
});
}
}
_ => {}
@@ -107,25 +205,40 @@ impl Game<'_> {
}
/// Where focus starts when a menu opens: the held hotbar slot in an
/// inventory, else the first button.
fn pad_first_target(&self) -> Option<(f32, f32)> {
/// inventory, else the first button, else the first target that isn't
/// a tab.
fn pad_first_target(&self, targets: &[Target]) -> Option<Target> {
let batch = self.gui_scale()?;
match self.screen {
Screen::Inventory if self.title.is_none() => {
let (ox, oy) = self.inventory_origin(&batch);
let (x, y) = self.slot_position(self.selected);
return Some((ox + x + 8.0, oy + y + 8.0));
let at = |x: f32, y: f32| {
targets
.iter()
.find(|t| t.rect[0] == x && t.rect[1] == y)
.copied()
};
if self.title.is_none() {
match self.screen {
Screen::Inventory => {
let (ox, oy) = self.inventory_origin(&batch);
let (x, y) = self.slot_position(self.selected);
if let Some(t) = at(ox + x, oy + y) {
return Some(t);
}
}
Screen::Creative if !self.creative_inventory_open() => {
let (ox, oy) = Self::creative_origin(&batch);
if let Some(t) = at(ox + 9.0 + self.selected as f32 * 18.0, oy + 112.0) {
return Some(t);
}
}
_ => {}
}
Screen::Creative if self.title.is_none() => {
let (ox, oy) = Self::creative_origin(&batch);
return Some((ox + 17.0 + self.selected as f32 * 18.0, oy + 120.0));
}
_ => {}
}
widgets::last()
targets
.iter()
.find(|w| w.enabled)
.map(|w| (w.x + w.w / 2.0, w.y + w.h / 2.0))
.find(|t| t.kind == Kind::Button)
.or_else(|| targets.iter().find(|t| !matches!(t.kind, Kind::Tab(_))))
.or(targets.first())
.copied()
}
/// Send the window a pointer move to `at` (GUI pixels), as the mouse would.
@@ -178,6 +291,13 @@ impl Game<'_> {
);
}
/// A click (press and release) at a point, the pointer staying there.
fn pad_click_at(&mut self, event_loop: &ActiveEventLoop, at: (f32, f32), right: bool) {
self.pad_pointer_to(event_loop, at);
self.pad_pointer_button(event_loop, right, true);
self.pad_pointer_button(event_loop, right, false);
}
fn pad_wheel(&mut self, event_loop: &ActiveEventLoop, x: f32, y: f32) {
let Some(id) = self.window.as_ref().map(|w| w.id()) else {
return;
@@ -193,15 +313,26 @@ impl Game<'_> {
);
}
/// Put the cursor where the pad last left it, or on the first target.
/// Put the pointer where the pad last left it, or on the first target
/// (focus mode: focus lands there too).
fn pad_take_pointer(&mut self, event_loop: &ActiveEventLoop) {
if self.pad.menu.pos.is_some() {
return;
}
let at = self.pad_first_target().unwrap_or(self.cursor);
let targets = self.pad_targets();
let first = self.pad_first_target(&targets);
if self.pad_focus_mode() && first.is_some() {
self.pad.menu.focus = first;
}
let at = first.map_or(self.cursor, |t| t.center());
self.pad_pointer_to(event_loop, at);
}
/// Focus mode with something to focus on this screen.
fn pad_focusing(&self) -> bool {
self.pad_focus_mode() && self.pad.menu.focus.is_some()
}
/// A button in a menu.
pub(super) fn pad_menu_button(
&mut self,
@@ -232,8 +363,45 @@ impl Game<'_> {
}
return self.handle_option_events(vec![Event::Changed]);
}
// The on-screen keyboard takes every button while it is open.
if let Some(keyboard) = self.pad.menu.osk.as_mut() {
if let Some(out) = keyboard.button(button) {
self.pad_osk_output(out);
}
if matches!(
button,
Button::DPadUp | Button::DPadDown | Button::DPadLeft | Button::DPadRight
) {
self.pad.menu.repeat = Some((button, Instant::now(), false));
}
return Ok(());
}
match button {
Button::East | Button::Start => return self.pad_back(),
Button::RightStick => {
// Swap focus and pointer for this screen.
self.pad.menu.swapped = !self.pad.menu.swapped;
self.pad.menu.focus = None;
self.pad.menu.pending = None;
self.pad.menu.nudge = None;
self.pad.menu.pos = None;
self.pad_take_pointer(event_loop);
}
Button::South if self.pad_focusing() => {
let focus = self.pad.menu.focus.expect("focusing");
match focus.kind {
// A click would jump the handle; left/right move it.
Kind::Slider { .. } => {}
Kind::Field => {
self.pad_click_at(event_loop, focus.center(), false);
self.pad_open_keyboard();
}
_ => {
self.pad_pointer_to(event_loop, focus.center());
self.pad_pointer_button(event_loop, false, true);
}
}
}
Button::South | Button::West => {
self.pad_take_pointer(event_loop);
self.pad_pointer_button(event_loop, button == Button::West, true);
@@ -256,20 +424,56 @@ impl Game<'_> {
self.physical_keys.remove(&KeyCode::ShiftLeft);
}
}
// View / left stick in an inventory: throw one / the stack from
// the slot under focus (Q / Ctrl+Q).
Button::Select | Button::LeftStick
if matches!(self.screen, Screen::Inventory | Screen::Creative)
&& self.title.is_none() =>
{
self.pad_take_pointer(event_loop);
let all = button == Button::LeftStick;
let ctrl = self.physical_keys.contains(&KeyCode::ControlLeft);
if all {
self.physical_keys.insert(KeyCode::ControlLeft);
}
let result = self.key_pressed(KeyCode::KeyQ);
if all && !ctrl {
self.physical_keys.remove(&KeyCode::ControlLeft);
}
result?;
}
Button::DPadUp | Button::DPadDown | Button::DPadLeft | Button::DPadRight => {
self.pad_focus_step(event_loop, button);
self.pad.menu.repeats = 0;
self.pad_step(event_loop, button);
self.pad.menu.repeat = Some((button, Instant::now(), false));
}
// Bumpers switch creative tabs.
Button::LeftBumper | Button::RightBumper if self.screen == Screen::Creative => {
self.pad_creative_tab(event_loop, button == Button::RightBumper);
// Bumpers switch tabs (creative, Horizon's options sections, ...).
Button::LeftBumper | Button::RightBumper => {
self.pad_tab(event_loop, button == Button::RightBumper);
}
_ => {}
}
Ok(())
}
fn pad_focus_step(&mut self, event_loop: &ActiveEventLoop, button: Button) {
/// One D-pad (or stick) step in either mode.
fn pad_step(&mut self, event_loop: &ActiveEventLoop, button: Button) {
if let Some(keyboard) = self.pad.menu.osk.as_mut() {
keyboard.step(button);
return;
}
if self.pad_focus_mode() {
let targets = self.pad_targets();
if !targets.is_empty() {
self.pad_focus_step(event_loop, button, &targets);
return;
}
}
self.pad_pointer_step(event_loop, button);
}
/// Pointer mode: hop the cursor to the nearest target that way.
fn pad_pointer_step(&mut self, event_loop: &ActiveEventLoop, button: Button) {
if self.pad.menu.pos.is_none() {
self.pad_take_pointer(event_loop);
return;
@@ -287,9 +491,106 @@ impl Game<'_> {
return;
}
let from = self.cursor;
let targets = self.pad_targets();
if let Some(i) = gamepad::focus_step(from, button, &targets) {
self.pad_pointer_to(event_loop, targets[i]);
let centres: Vec<(f32, f32)> = self.pad_targets().iter().map(Target::center).collect();
if let Some(i) = gamepad::focus_step(from, button, &centres) {
self.pad_pointer_to(event_loop, centres[i]);
}
}
/// Focus mode: move the highlight (or a focused slider's value).
fn pad_focus_step(&mut self, event_loop: &ActiveEventLoop, button: Button, targets: &[Target]) {
let Some(focus) = self.pad.menu.focus else {
self.pad.menu.pos = None;
self.pad_take_pointer(event_loop);
return;
};
if let Kind::Slider { value, track } = focus.kind
&& matches!(button, Button::DPadLeft | Button::DPadRight)
{
let from = match self.pad.menu.nudge {
Some((rect, x)) if rect == focus.rect => x,
_ => gamepad::slider_x(track, value),
};
let step = gamepad::slider_step(self.pad.menu.repeats);
let x = (from
+ if button == Button::DPadLeft {
-step
} else {
step
})
.clamp(track[0], track[0] + track[1]);
self.pad.menu.nudge = Some((focus.rect, x));
self.pad_click_at(event_loop, (x, focus.center().1), false);
return;
}
let rects: Vec<Rect> = targets.iter().map(|t| t.rect).collect();
let vertical = matches!(button, Button::DPadUp | Button::DPadDown);
let step = if vertical {
gamepad::focus_step_strict(focus.rect, button, &rects)
} else {
gamepad::focus_step_rect(focus.rect, button, &rects)
};
match step {
Some(i) => self.pad_focus_on(event_loop, targets[i]),
None if vertical => {
// Off the visible rows of a list: scroll it and try again on
// the next frame.
let up = button == Button::DPadUp;
self.pad_wheel(event_loop, 0.0, if up { 1.0 } else { -1.0 });
self.pad.menu.pending = Some(Pending {
button,
from: focus.rect,
generation: widgets::generation(),
tries: 1,
before: rects,
});
}
None => {}
}
}
fn pad_focus_on(&mut self, event_loop: &ActiveEventLoop, target: Target) {
self.pad.menu.focus = Some(target);
self.pad.menu.pending = None;
self.pad.menu.nudge = None;
if !self.pad.menu.held[0] {
self.pad_pointer_to(event_loop, target.center());
}
}
/// A bumper: the next or previous tab, wrapping (creative keeps its own
/// order; other screens register their tabs).
fn pad_tab(&mut self, event_loop: &ActiveEventLoop, next: bool) {
if self.screen == Screen::Creative && self.title.is_none() {
self.pad_creative_tab(event_loop, next);
return;
}
let tabs: Vec<(Rect, bool)> = self
.pad_targets()
.into_iter()
.filter_map(|t| match t.kind {
Kind::Tab(selected) => Some((t.rect, selected)),
_ => None,
})
.collect();
let Some(i) = gamepad::tab_step(&tabs, next) else {
return;
};
let rect = tabs[i].0;
let back = self.pad.menu.pos;
self.pad_click_at(
event_loop,
(rect[0] + rect[2] / 2.0, rect[1] + rect[3] / 2.0),
false,
);
if self.pad_focus_mode() {
// The page changed under the old focus: start again on the new one.
self.pad.menu.focus = Some(Target {
rect,
kind: Kind::Tab(true),
});
} else if let Some(at) = back {
self.pad_pointer_to(event_loop, at);
}
}
@@ -311,17 +612,16 @@ impl Game<'_> {
let (ox, oy) = Self::creative_origin(&batch);
let (x, y) = Creative::tab_position(&self.creative_screen.tabs[tab]);
let back = self.pad.menu.pos;
self.pad_pointer_to(event_loop, (ox + x + 13.0, oy + y + 16.0));
self.pad_pointer_button(event_loop, false, true);
self.pad_pointer_button(event_loop, false, false);
self.pad_click_at(event_loop, (ox + x + 13.0, oy + y + 16.0), false);
if let Some(at) = back {
self.pad_pointer_to(event_loop, at);
}
}
/// Once per poll in a menu: the stick moves the cursor, the right stick
/// scrolls, a held D-pad repeats, and the OS pointer hides while the
/// pad's cursor shows.
/// Once per poll in a menu: the stick moves the cursor (pointer) or
/// steps focus, the right stick scrolls, a held direction repeats, focus
/// follows its widget from frame to frame, and the OS pointer hides
/// while the pad drives.
pub(super) fn pad_menu_frame(&mut self, event_loop: &ActiveEventLoop) {
let now = Instant::now();
let seconds = self
@@ -332,10 +632,17 @@ impl Game<'_> {
self.pad.menu.last_poll = Some(now);
let in_menu = self.pad_in_menu() && self.settings.controller.enabled;
if !in_menu {
self.pad.menu.open_polls = 0;
self.pad.menu.pos = None;
self.pad.menu.repeat = None;
self.pad.menu.held = [false; 2];
let menu = &mut self.pad.menu;
menu.open_polls = 0;
menu.pos = None;
menu.repeat = None;
menu.held = [false; 2];
menu.focus = None;
menu.swapped = false;
menu.pending = None;
menu.nudge = None;
menu.osk = None;
menu.osk_dismissed = false;
self.pad_show_os_pointer(true);
return;
}
@@ -345,29 +652,65 @@ impl Game<'_> {
&& ((at.0 - self.cursor.0).abs() > 0.5 || (at.1 - self.cursor.1).abs() > 0.5)
{
self.pad.menu.pos = None;
self.pad.menu.focus = None;
self.pad.in_use = false;
}
// Focus lands on the menu as it opens when the pad was in use.
if self.pad.in_use && self.pad.menu.pos.is_none() && self.pad.menu.open_polls == 3 {
self.pad_take_pointer(event_loop);
}
let focus_mode = self.pad_focus_mode();
let targets = if focus_mode {
self.pad_targets()
} else {
Vec::new()
};
let focusing = focus_mode && !targets.is_empty();
if focusing {
self.pad_follow_focus(event_loop, &targets);
}
let (move_deadzone, look_deadzone) = (
self.settings.controller.move_deadzone,
self.settings.controller.look_deadzone,
);
let state = self.pad.state;
let (dx, dy) = gamepad::cursor_delta(state.left, move_deadzone, seconds);
if dx != 0.0 || dy != 0.0 {
self.pad_take_pointer(event_loop);
let at = self.cursor;
self.pad_pointer_to(event_loop, (at.0 + dx, at.1 + dy));
self.pad.menu.moving = true;
} else if self.pad.menu.moving {
// Let go: settle onto a slot or button close by.
self.pad.menu.moving = false;
let targets = self.pad_targets();
if let Some(i) = gamepad::nearest(self.cursor, &targets, 10.0) {
self.pad_pointer_to(event_loop, targets[i]);
if focusing || self.pad.menu.osk.is_some() {
// The stick steps like the D-pad.
let dir =
gamepad::stick_direction(gamepad::radial(state.left, move_deadzone), STICK_STEP);
if dir != self.pad.menu.stick {
if let Some((b, ..)) = self.pad.menu.repeat
&& Some(b) == self.pad.menu.stick
{
self.pad.menu.repeat = None;
}
self.pad.menu.stick = dir;
if let Some(button) = dir {
if self.pad.menu.pos.is_none() && self.pad.menu.osk.is_none() {
self.pad_take_pointer(event_loop);
} else {
self.pad.menu.repeats = 0;
self.pad_step(event_loop, button);
}
self.pad.menu.repeat = Some((button, now, false));
}
}
} else {
self.pad.menu.stick = None;
let (dx, dy) = gamepad::cursor_delta(state.left, move_deadzone, seconds);
if dx != 0.0 || dy != 0.0 {
self.pad_take_pointer(event_loop);
let at = self.cursor;
self.pad_pointer_to(event_loop, (at.0 + dx, at.1 + dy));
self.pad.menu.moving = true;
} else if self.pad.menu.moving {
// Let go: settle onto a slot or button close by.
self.pad.menu.moving = false;
let centres: Vec<(f32, f32)> =
self.pad_targets().iter().map(Target::center).collect();
if let Some(i) = gamepad::nearest(self.cursor, &centres, 10.0) {
self.pad_pointer_to(event_loop, centres[i]);
}
}
}
let scroll = gamepad::radial(state.right, look_deadzone);
@@ -392,12 +735,88 @@ impl Game<'_> {
};
if now.duration_since(since).as_secs_f32() >= wait {
self.pad.menu.repeat = Some((button, now, true));
self.pad_focus_step(event_loop, button);
self.pad.menu.repeats = self.pad.menu.repeats.saturating_add(1);
self.pad_step(event_loop, button);
}
}
self.pad_auto_keyboard();
self.pad_show_os_pointer(self.pad.menu.pos.is_none());
}
/// Focus mode, each poll: find the focused widget in the new frame (a
/// list scrolled, a page changed), finish a step that scrolled a list,
/// and keep the hidden pointer on the focused widget.
fn pad_follow_focus(&mut self, event_loop: &ActiveEventLoop, targets: &[Target]) {
let rects: Vec<Rect> = targets.iter().map(|t| t.rect).collect();
let ready = self
.pad
.menu
.pending
.as_ref()
.map(|p| widgets::generation() > p.generation);
if ready == Some(true)
&& let Some(p) = self.pad.menu.pending.take()
{
// A step scrolled a list: carry on from where the focused row
// moved, or take the vague pass when nothing scrolled.
let step = match gamepad::scroll_shift(&p.before, &rects) {
Some(dy) => {
let mut from = p.from;
from[1] += dy;
self.pad.menu.focus = gamepad::refind(from, &rects, 2.0).map(|i| targets[i]);
gamepad::focus_step_strict(from, p.button, &rects).map(|i| (i, Some(from)))
}
None => gamepad::focus_step_vague(p.from, p.button, &rects).map(|i| (i, None)),
};
match step {
Some((i, _)) => self.pad_focus_on(event_loop, targets[i]),
None => {
if let Some(dy) = gamepad::scroll_shift(&p.before, &rects)
&& p.tries < SCROLL_TRIES
{
let up = p.button == Button::DPadUp;
self.pad_wheel(event_loop, 0.0, if up { 1.0 } else { -1.0 });
let mut from = p.from;
from[1] += dy;
self.pad.menu.pending = Some(Pending {
from,
generation: widgets::generation(),
tries: p.tries + 1,
before: rects.clone(),
..p
});
}
}
}
} else if ready.is_none() {
if let Some(focus) = self.pad.menu.focus {
self.pad.menu.focus = gamepad::refind(focus.rect, &rects, 12.0).map(|i| targets[i]);
if self.pad.menu.focus.is_none() && self.pad.menu.pos.is_some() {
// The widget went away (a page changed): start again.
self.pad.menu.focus = self.pad_first_target(targets);
}
} else if self.pad.menu.pos.is_some() {
// The pad drives but nothing is focused (switched from the pointer).
let centres: Vec<(f32, f32)> = targets.iter().map(Target::center).collect();
self.pad.menu.focus =
gamepad::nearest(self.cursor, &centres, f32::INFINITY).map(|i| targets[i]);
}
}
let Some(focus) = self.pad.menu.focus else {
return;
};
if self.pad.menu.pos.is_none() || self.pad.menu.held.iter().any(|h| *h) {
return;
}
let at = match self.pad.menu.nudge {
Some((rect, x)) if rect == focus.rect => (x, focus.center().1),
_ => focus.center(),
};
if (at.0 - self.cursor.0).abs() > 0.5 || (at.1 - self.cursor.1).abs() > 0.5 {
self.pad_pointer_to(event_loop, at);
}
}
fn pad_show_os_pointer(&mut self, show: bool) {
if self.pad.menu.os_hidden != show {
return;
@@ -408,12 +827,178 @@ impl Game<'_> {
}
}
/// The pad's cursor, over everything else.
/// `pad status`: the menu mode, the focused target and every target.
pub(super) fn pad_menu_status(&self) -> serde_json::Value {
let kind = |k: Kind| match k {
Kind::Button => "button",
Kind::Slider { .. } => "slider",
Kind::Field => "field",
Kind::Row => "row",
Kind::Slot => "slot",
Kind::Tab(true) => "tab*",
Kind::Tab(false) => "tab",
};
let target = |t: &Target| serde_json::json!({ "rect": t.rect, "kind": kind(t.kind) });
serde_json::json!({
"mode": if self.pad_focus_mode() { "focus" } else { "pointer" },
"focus": self.pad.menu.focus.as_ref().map(target),
"keyboard": self.pad.menu.osk.is_some(),
"targets": self.pad_targets().iter().map(target).collect::<Vec<_>>(),
})
}
// ---- text fields ----
/// A text field has keyboard focus: chat, a sign, a book being written,
/// a search box, the anvil's name, the title screens' and the options'
/// fields, the LAN port.
fn pad_typing(&self) -> bool {
(self.screen == Screen::Chat && self.title.is_none())
|| self.sign_edit.is_some()
|| matches!(self.book, Some(super::books::BookScreen::Edit { .. }))
|| (self.screen == Screen::Creative && self.creative_screen.tab().search)
|| self.recipe_search_focused()
|| self.station_typing()
|| self.remote_chat_open()
}
/// Open the on-screen keyboard over the focused field: Horizon's, or
/// Steam's on a Steam Deck (`steam://open/keyboard`, which types into
/// the window like a real keyboard).
fn pad_open_keyboard(&mut self) {
// Without xdg-open (macOS, Windows), Horizon's keyboard instead.
if gamepad::steam_keyboard(self.settings.controller.keyboard)
&& std::process::Command::new("xdg-open")
.arg("steam://open/keyboard")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.is_ok()
{
return;
}
self.pad.menu.osk = Some(Keyboard::default());
}
/// Chat or a sign opened by the pad in focus mode: the keyboard opens
/// with it (once per screen; B closes it for good).
fn pad_auto_keyboard(&mut self) {
let menu = &self.pad.menu;
if menu.osk.is_none()
&& !menu.osk_dismissed
&& self.pad.in_use
&& menu.open_polls >= 3
&& self.pad_focus_mode()
&& (self.screen == Screen::Chat || self.sign_edit.is_some() || self.remote_chat_open())
{
self.pad.menu.osk_dismissed = true;
self.pad_open_keyboard();
}
}
/// What a key of the on-screen keyboard does: the same as a typed key in
/// the field that has focus.
fn pad_osk_output(&mut self, out: osk::Output) {
use osk::Output;
let (key, named, text) = match &out {
Output::Text(t) => (None, None, Some(t.as_str())),
Output::Backspace => (Some(KeyCode::Backspace), Some(NamedKey::Backspace), None),
Output::Enter => (Some(KeyCode::Enter), Some(NamedKey::Enter), None),
Output::Close => {
self.pad.menu.osk = None;
self.pad.menu.osk_dismissed = true;
return;
}
};
let backspace = key == Some(KeyCode::Backspace);
if self.screen == Screen::Chat && self.title.is_none() {
match text {
Some(t) => self.chat_type(t),
None => self.chat_key_code(key.expect("a key"), None),
}
} else if self.sign_edit.is_some() {
self.sign_input(key, text);
} else if self.book.is_some() {
self.book_input(key, text);
} else if self.screen == Screen::Creative && self.creative_screen.tab().search {
if key != Some(KeyCode::Enter) {
self.creative_search_edit(text, backspace);
}
} else if self.recipe_search_focused() {
if key != Some(KeyCode::Enter) {
self.recipe_text(text, backspace);
}
} else if self.station_typing() {
if key != Some(KeyCode::Enter) {
self.station_text(text, backspace);
}
} else if self.remote_chat_open() {
self.remote_chat_input(named, text);
} else if self.screen == Screen::WorldOptions {
if key != Some(KeyCode::Enter) {
self.world_options_text(text);
}
} else if self.screen == Screen::Options {
let result = match text {
Some(t) => {
self.ui.options.type_text(&self.res.atlas, t);
Ok(())
}
None => self.options_key(key.expect("a key"), None),
};
if let Err(e) = result {
log::warn!("Horizon: on-screen keyboard: {e}");
}
} else if self.title.is_some() {
match key {
Some(KeyCode::Enter) => {
if let Some(t) = self.title.as_mut() {
t.confirm_edit();
}
}
Some(KeyCode::Backspace) => self.title_edit(None, true),
_ => self.title_edit(text, false),
}
}
// Enter ends the typing; a field that closed with it closes the keyboard.
if key == Some(KeyCode::Enter)
|| (!self.pad_typing()
&& self.title.is_none()
&& !matches!(self.screen, Screen::Options | Screen::WorldOptions))
{
self.pad.menu.osk = None;
}
}
// ---- drawing ----
/// The pad's cursor (pointer mode) or focus highlight (focus mode), and
/// the on-screen keyboard, over everything else.
pub(super) fn draw_pad_cursor(&self, batch: &mut HudBatch) {
if !self.pad_in_menu() {
return;
}
if let Some(keyboard) = &self.pad.menu.osk {
let at_top = self
.pad
.menu
.focus
.is_some_and(|f| f.center().1 > batch.height / 2.0)
|| self.screen == Screen::Chat
|| self.remote_chat_open();
let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor);
keyboard.draw(&mut ui, at_top, self.ui.options.pad_style);
ui.finish();
return;
}
let Some((x, y)) = self.pad.menu.pos else {
return;
};
if !self.pad_in_menu() {
if self.pad_focus_mode()
&& let Some(focus) = self.pad.menu.focus
{
self.draw_pad_focus(batch, focus);
return;
}
// An arrow, outlined, pointing up-left at (x, y).
@@ -444,4 +1029,53 @@ 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.
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.res.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.res.atlas;
let white = rgba(255, 255, 255, 255);
batch.fill(atlas, x, y, w, 1.0, white);
batch.fill(atlas, x, y + h - 1.0, w, 1.0, white);
batch.fill(atlas, x, y, 1.0, h, white);
batch.fill(atlas, x + w - 1.0, y, 1.0, h, white);
}
}
}
+9 -2
View File
@@ -830,7 +830,10 @@ impl Game<'_> {
out.into_iter().collect()
}
/// Write the entities of every resident chunk (an autosave or quit).
pub(super) fn save_entities(&mut self) -> Result<()> {
/// Without `wait` (the autosave) they are written on the region writer
/// meanwhile: `PersistentEntitySectionManager.autoSave` stores them
/// without `saveAll`'s flush.
pub(super) fn save_entities(&mut self, wait: bool) -> Result<()> {
self.spawn_loaded_entities();
let keys: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
let chunks = self.entity_chunks(&keys, false);
@@ -849,7 +852,11 @@ impl Game<'_> {
.collect();
self.persist.uuids.retain(|id, _| alive.contains(id));
self.persist.raw.retain(|id, _| alive.contains(id));
self.save.save_entities(chunks)
if wait {
self.save.save_entities(chunks)
} else {
self.save.save_entities_later(chunks)
}
}
/// Save and remove the entities of chunks that unloaded.
pub(super) fn unload_entities(&mut self, unloaded: &[Arc<Chunk>]) {
+27 -13
View File
@@ -7,7 +7,7 @@ use horizon_client::{
brewing,
effects::{EffectAction, EffectInstance, PlayerEffects},
hud::HudBatch,
hud_layout, hud_overlays,
hud_layout, hud_overlays, inventory_effects,
items::ItemStack,
};
use horizon_core::{geometry::Vec3, random::RandomSource};
@@ -573,22 +573,36 @@ impl Game<'_> {
.effects
.list
.iter()
.map(|e| {
let def = brewing::effect(e.id);
hud_overlays::EffectIcon {
id: e.id.to_owned(),
beneficial: def.is_some_and(|d| d.category == brewing::Category::Beneficial),
color: def.map_or(0, |d| d.color as i32),
ambient: e.ambient,
duration: e.duration,
// Horizon keeps no showIcon flag: every effect shows its icon.
show_icon: true,
}
})
.map(hud_overlays::EffectIcon::from)
.collect();
let draws = hud_overlays::effects(batch.width as i32, false, &icons);
hud_layout::paint(batch, &self.res.atlas, &draws);
}
/// `EffectsInInventory`: panels to the right of survival/creative inventory.
pub(super) fn draw_inventory_effects(
&self,
batch: &mut HudBatch,
origin: (f32, f32),
image_width: i32,
) {
let panels = inventory_effects::panels(
batch.width as i32,
[origin.0 as i32, origin.1 as i32],
image_width,
&self.potions.effects.list,
self.clock.rate(),
&|key| self.res.names.get(key).map(str::to_owned),
&|text| self.res.atlas.font.width(text).ceil() as i32,
);
if let Some(lines) = inventory_effects::paint(
batch,
&self.res.atlas,
&panels,
[self.cursor.0 as i32, self.cursor.1 as i32],
) {
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
}
}
/// Effects saved in level.dat (`Player.active_effects`).
pub(super) fn restore_effects(&mut self) {
self.potions = PotionState::default();
+107 -16
View File
@@ -197,28 +197,59 @@ impl Game<'_> {
search.reset_blink();
}
/// The toast for newly unlocked recipes: one for a burst of unlocks.
/// `RecipeToast.addOrUpdate` for each display of the recipes just
/// unlocked: its crafting station and result join the toast still
/// queued or shown, or a new one.
pub(super) fn recipe_toast(&mut self, recipes: &[String]) {
if recipes.is_empty() || self.adv.quiet {
return;
}
self.ensure_book();
let icon = self
.recipe_ui
.book
.as_ref()
.and_then(|b| recipes.iter().find_map(|id| b.entry(id)))
.map(|e| e.result.item.to_string());
let Some(icon) = icon else { return };
let fresh = self
.adv
.toasts
.back()
.is_some_and(|t| t.is_recipe() && !t.was_shown());
if !fresh {
self.adv
let index = &self.res.stations.recipe_index;
let book = self.recipe_ui.book.as_ref();
// SmithingTrimDemoSlotDisplay draws from a random of its own.
let mut random = super::dispenser::entity_random();
let mut items = Vec::new();
for id in recipes {
let Some(station) = index.toast_station(id) else {
continue;
};
for display in index.display_ids(id) {
// The book's displays carry their resolved results; the
// other recipe types name theirs, and trims are demos.
let result = book
.and_then(|b| {
b.entry_of_display(display)
.map(|i| b.entries[i].result.clone())
})
.or_else(|| index.result(id).map(|r| ItemStack::new(r, 1)))
.or_else(|| {
self.res.stations.recipes.trim_demo(
&self.res.stations.enchantments,
id,
&mut |n| {
horizon_core::random::RandomSource::next_int_bound(
&mut random,
n as i32,
)
.unwrap_or(0) as usize
},
)
});
if let Some(result) = result {
items.push((station.to_owned(), result));
}
}
}
if items.is_empty() {
return;
}
match self.adv.toasts.iter_mut().find(|t| t.is_recipe()) {
Some(toast) => toast.add_recipes(items),
None => self
.adv
.toasts
.push_back(super::advancements::Toast::recipe(&icon));
.push_back(super::advancements::Toast::recipe(items)),
}
}
@@ -629,6 +660,66 @@ impl Game<'_> {
}
false
}
/// The recipe book's buttons a controller can focus: the book button,
/// recipes, page arrows, the craftable filter and the tabs (GUI pixels;
/// the search box registers itself as a field).
pub(super) fn recipe_book_targets(&self) -> Vec<horizon_client::widgets::Target> {
use horizon_client::widgets::{Kind, Target};
let (Some(book_type), Some(batch)) = (self.active_book(), self.batch_for_size()) else {
return Vec::new();
};
let button = |rect| Target {
rect,
kind: Kind::Button,
};
let (ox, _) = self.inventory_origin(&batch);
let (bx, by) = self.book_button_pos(book_type, ox, &batch);
let mut out = vec![button([bx, by, 20.0, 18.0])];
if !self.book_open(book_type) || self.spectator() {
return out;
}
let (xo, yo) = self.book_origin(&batch);
if let Some(overlay) = &self.recipe_ui.overlay {
// The alternatives overlay takes every click while open.
let maxrow = if overlay.entries.len() <= 16 { 4 } else { 5 };
return (0..overlay.entries.len())
.map(|n| {
let x = overlay.x + 4.0 + 25.0 * (n % maxrow) as f32;
let y = overlay.y + 5.0 + 25.0 * (n / maxrow) as f32;
button([x, y, 24.0, 24.0])
})
.collect();
}
let first = self.recipe_ui.page * 20;
let shown = self
.recipe_ui
.view
.buttons
.len()
.saturating_sub(first)
.min(20);
out.extend((0..shown).map(|n| {
let (x, y) = Self::button_pos(xo, yo, n);
button([x, y, 25.0, 25.0])
}));
let pages = self.recipe_ui.view.buttons.len().div_ceil(20);
if pages > 1 && self.recipe_ui.page + 1 < pages {
out.push(button([xo + 93.0, yo + 137.0, 12.0, 17.0]));
}
if pages > 1 && self.recipe_ui.page > 0 {
out.push(button([xo + 38.0, yo + 137.0, 12.0, 17.0]));
}
out.push(button([xo + 110.0, yo + 12.0, 26.0, 16.0]));
let selected = self.recipe_ui.tab.unwrap_or(Tab::Search);
for (n, tab) in self.recipe_ui.view.tabs.iter().enumerate() {
let (x, y) = self.tab_pos(xo, yo, n);
out.push(Target {
rect: [x, y, 35.0, 27.0],
kind: Kind::Tab(*tab == selected),
});
}
out
}
fn shift_down(&self) -> bool {
self.has_shift_down()
}
+65 -19
View File
@@ -151,13 +151,14 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo
impl Game<'_> {
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
self.perf.world_opening();
let root = self.options.resources.clone();
let builtin = Builtin::find(&root)
.and_then(|p| Builtin::load(&p).ok())
.ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?;
let lang = Arc::new(horizon_client::net::load_language(&root));
let view = self.settings.render_distance.clamp(2, 32) as i8;
horizon_client::crash::set_detail("Server", address.to_owned());
horizon_client::crash::set_detail("Server", horizon_client::net::shown_address(address));
// A signed-in account always plays under its own name.
let auth = horizon_client::auth::current();
let name = auth.as_ref().map_or(name, |a| a.name.as_str());
@@ -262,6 +263,7 @@ impl Game<'_> {
/// Disconnect and return to the multiplayer screen (DisconnectedScreen).
pub(super) fn leave_server(&mut self, reason: Option<String>) -> Result<()> {
self.finish_perf();
if reason.is_none() {
// Leaving on purpose: nothing for auto-reconnect to retry.
self.extras_left();
@@ -270,6 +272,7 @@ impl Game<'_> {
r.session.disconnect();
}
horizon_client::crash::clear_detail("Server");
self.debug_charts.reset();
self.tab_list.reset();
self.score.board = Default::default();
self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1);
@@ -289,7 +292,7 @@ impl Game<'_> {
r.clear_sections();
}
let saves = std::env::current_dir()?.join("saves");
let mut title = horizon_client::title::Title::new(saves.clone());
let mut title = horizon_client::title::Title::new(saves.clone(), &self.options.resources);
title.mode = horizon_client::title::Mode::Multiplayer(match reason {
Some(reason) => horizon_client::multiplayer::Screen::Disconnected {
reason,
@@ -734,6 +737,11 @@ impl Game<'_> {
fn handle_packet(&mut self, packet: C) -> Result<()> {
match packet {
// PingDebugMonitor.onPongReceived.
C::PongResponse(p) => {
let delay = self.debug_millis() - p.time;
self.debug_charts.ping.log(delay);
}
C::Login(p) => {
if let Some(r) = self.remote.as_mut() {
r.online_mode = p.online_mode;
@@ -1754,12 +1762,24 @@ impl Game<'_> {
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
let feet = [player.position.x, player.position.y, player.position.z];
for event in events {
if let horizon_client::motion::MotionEvent::Emission { state, .. } = event
&& !crouching
{
let sounds = self.res.facts.get(state).sounds.clone();
self.audio
.play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch);
match event {
horizon_client::motion::MotionEvent::Emission {
state, in_water, ..
} if !crouching => {
let sounds = self.res.facts.get(state).sounds.clone();
// Player.playStepSound: muffled under the swim sound in water.
let (volume, pitch) = if in_water {
(sounds.volume * 0.05, sounds.pitch * 0.8)
} else {
(sounds.volume * 0.15, sounds.pitch)
};
self.audio.play(&sounds.step, Some(feet), volume, pitch);
}
horizon_client::motion::MotionEvent::Swim { volume, pitch } => {
self.audio
.play("minecraft:entity.player.swim", Some(feet), volume, pitch);
}
_ => {}
}
}
// The server owns health and hunger: undo local food/fall changes.
@@ -2286,7 +2306,7 @@ impl Game<'_> {
}
/// ChatScreen: typing, Enter to send, Escape to cancel.
pub(super) fn remote_chat_key(&mut self, event: &winit::event::KeyEvent) {
use winit::keyboard::{Key, NamedKey};
use winit::keyboard::Key;
if event.state != winit::event::ElementState::Pressed {
return;
}
@@ -2311,23 +2331,44 @@ impl Game<'_> {
return;
}
// Logical keys: the text, not the scancode, decides (layouts, virtual keyboards).
match &event.logical_key {
Key::Named(NamedKey::Escape) => {
let named = match &event.logical_key {
Key::Named(n) => Some(*n),
_ => None,
};
self.remote_chat_input(named, event.text.as_deref());
}
/// A named key or typed text in the chat input (the keyboard, or a
/// controller's on-screen keyboard).
pub(super) fn remote_chat_input(
&mut self,
named: Option<winit::keyboard::NamedKey>,
text: Option<&str>,
) {
use winit::keyboard::NamedKey;
const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0);
let Some(r) = self.remote.as_mut() else {
return;
};
let Some(input) = r.chat_input.as_mut() else {
return;
};
match named {
Some(NamedKey::Escape) => {
r.chat_input = None;
self.capture(true);
}
Key::Named(NamedKey::Backspace) => {
Some(NamedKey::Backspace) => {
if !self.text_selection.take(INPUT, input) {
input.pop();
}
}
Key::Named(NamedKey::Enter) => {
Some(NamedKey::Enter) => {
let message = r.chat_input.take().unwrap_or_default();
self.send_chat(&message);
self.capture(true);
}
_ => {
if let Some(text) = &event.text {
if let Some(text) = text {
self.text_selection.take(INPUT, input);
for c in text.chars().filter(|c| !c.is_control()) {
if input.chars().count() < 256 {
@@ -2595,10 +2636,8 @@ impl Game<'_> {
let atlas = &self.res.atlas;
let (w, h) = (batch.width, batch.height);
batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255));
for (i, line) in [r.status.as_str(), r.session.address.as_str()]
.iter()
.enumerate()
{
let shown = horizon_client::net::shown_address(&r.session.address);
for (i, line) in [r.status.as_str(), shown.as_str()].iter().enumerate() {
let tw = HudBatch::text_width(atlas, line);
batch.text(
atlas,
@@ -2680,7 +2719,7 @@ impl Game<'_> {
pub(super) fn remote_status(&self) -> Option<serde_json::Value> {
let r = self.remote.as_ref()?;
Some(serde_json::json!({
"address": r.session.address,
"address": horizon_client::net::shown_address(&r.session.address),
"name": r.session.name,
"joined": r.joined,
"status": r.status,
@@ -2693,6 +2732,13 @@ impl Game<'_> {
m
}),
"players": r.players.values().collect::<Vec<_>>(),
// Where the other players' entities are (harnesses check movement).
"player_positions": r
.entities
.values()
.filter(|t| t.kind == "minecraft:player")
.map(|t| t.position)
.collect::<Vec<_>>(),
"health": r.health.0,
"food": r.health.1,
"decode_errors": r.decode_errors,
+11 -1
View File
@@ -76,8 +76,10 @@ impl Game<'_> {
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.res.atlas, batch, self.cursor);
horizon_client::front::pause::draw(&mut ui, &world, quit, opened);
horizon_client::front::pause::draw(&mut ui, &world, quit, opened, &friends);
ui.finish();
return;
}
@@ -144,6 +146,7 @@ impl Game<'_> {
self.cursor.1,
&world,
quit,
&self.friends_view(),
)
} else {
pause_buttons(w, h)
@@ -163,6 +166,13 @@ 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(2) => self.close_world()?,
_ => {}
}
+15 -6
View File
@@ -49,18 +49,27 @@ impl Game<'_> {
self.sign_shortcut(shortcut);
return;
}
let key = match event.physical_key {
PhysicalKey::Code(k) => Some(k),
_ => None,
};
self.sign_input(key, event.text.as_deref());
}
/// A key and the text it typed on the sign being edited (the keyboard,
/// or a controller's on-screen keyboard).
pub(super) fn sign_input(&mut self, key: Option<KeyCode>, typed: Option<&str>) {
let Some(edit) = self.sign_edit.as_mut() else {
return;
};
let front = edit.front;
let id = sign_line_id(front, edit.line);
match event.physical_key {
PhysicalKey::Code(KeyCode::Escape) => self.close_sign_editor(),
PhysicalKey::Code(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3,
PhysicalKey::Code(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => {
match key {
Some(KeyCode::Escape) => self.close_sign_editor(),
Some(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3,
Some(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => {
edit.line = (edit.line + 1) & 3
}
PhysicalKey::Code(KeyCode::Backspace) => {
Some(KeyCode::Backspace) => {
let (line, key) = (edit.line, edit.pos);
if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) {
let text = if front {
@@ -75,7 +84,7 @@ impl Game<'_> {
}
}
_ => {
let Some(typed) = event.text.as_ref().map(|t| t.to_string()) else {
let Some(typed) = typed else {
return;
};
let line = edit.line;
@@ -1015,6 +1015,38 @@ impl Game<'_> {
self.station_changed();
}
/// Mouse click while a station or the brewing stand is open. True when handled.
/// A station's own buttons a controller can focus besides its slots
/// (GUI origin relative): offers, patterns, effects, enchantments and
/// stonecutter recipes.
pub(super) fn station_targets(&self) -> Vec<[f32; 4]> {
let Some(s) = self.station.as_ref() else {
return Vec::new();
};
match s.kind {
Kind::Merchant => self.merchant_targets(),
Kind::Loom => self.loom_targets(),
Kind::Beacon => self.beacon_targets(),
Kind::Enchanting => (0..3)
.map(|i| {
let (x, y, w, h) = enchant_button(i);
[x, y, w, h]
})
.collect(),
Kind::Stonecutter if s.inputs[0].is_some() => (s.start
..(s.start + 12).min(s.recipes.len()))
.map(|index| {
let p = index - s.start;
[
52.0 + (p % 4) as f32 * 16.0,
14.0 + (p / 4) as f32 * 18.0,
16.0,
18.0,
]
})
.collect(),
_ => Vec::new(),
}
}
pub(super) fn station_click(&mut self, right: bool) -> bool {
if self.station.is_none() && !self.brewing_open() {
return false;
+10
View File
@@ -507,6 +507,16 @@ impl Game<'_> {
}
false
}
/// The offer buttons a controller can focus (GUI origin relative).
pub(super) fn merchant_targets(&self) -> Vec<[f32; 4]> {
let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else {
return Vec::new();
};
(0..7)
.filter(|i| i + m.scroll < m.session.offers.len())
.map(|i| [5.0 + SHIFT, 18.0 + 20.0 * i as f32, 88.0, 20.0])
.collect()
}
pub(super) fn merchant_scroll(&mut self, d: f32) {
let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) else {
return;
@@ -0,0 +1,119 @@
//! Selection and hit testing for the debug game-mode switcher.
use crate::command::args::GameMode;
pub const MODES: [GameMode; 4] = [
GameMode::Creative,
GameMode::Survival,
GameMode::Adventure,
GameMode::Spectator,
];
pub const ICONS: [&str; 4] = [
"minecraft:grass_block",
"minecraft:iron_sword",
"minecraft:buried_treasure_map",
"minecraft:ender_eye",
];
pub const SLOT_SIZE: i32 = 26;
pub fn slot_origin(width: i32, height: i32, index: usize) -> (i32, i32) {
(width / 2 - 59 + index as i32 * 31, height / 2 - 31)
}
pub struct GameModeSwitcher {
pub selected: GameMode,
first_mouse: Option<(i32, i32)>,
}
impl GameModeSwitcher {
pub fn new(current: GameMode, previous: Option<GameMode>) -> Self {
Self {
selected: previous.unwrap_or(if current == GameMode::Creative {
GameMode::Survival
} else {
GameMode::Creative
}),
first_mouse: None,
}
}
pub fn cycle(&mut self) {
let index = MODES.iter().position(|m| *m == self.selected).unwrap();
self.selected = MODES[(index + 1) % MODES.len()];
self.first_mouse = None;
}
pub fn hover(&mut self, width: i32, height: i32, cursor: (i32, i32)) {
if *self.first_mouse.get_or_insert(cursor) == cursor {
return;
}
for (index, mode) in MODES.iter().enumerate() {
let (x, y) = slot_origin(width, height, index);
if cursor.0 >= x
&& cursor.0 < x + SLOT_SIZE
&& cursor.1 >= y
&& cursor.1 < y + SLOT_SIZE
{
self.selected = *mode;
return;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn initial_selection_and_cycle_follow_debug_order() {
assert_eq!(
GameModeSwitcher::new(GameMode::Creative, None).selected,
GameMode::Survival
);
for current in [GameMode::Survival, GameMode::Adventure, GameMode::Spectator] {
assert_eq!(
GameModeSwitcher::new(current, None).selected,
GameMode::Creative
);
}
let mut state = GameModeSwitcher::new(GameMode::Survival, Some(GameMode::Adventure));
for mode in [
GameMode::Adventure,
GameMode::Spectator,
GameMode::Creative,
GameMode::Survival,
] {
assert_eq!(state.selected, mode);
state.cycle();
}
}
#[test]
fn stationary_mouse_does_not_override_keyboard_selection() {
let mut state = GameModeSwitcher::new(GameMode::Creative, None);
let cursor = slot_origin(320, 240, 0);
state.hover(320, 240, cursor);
state.hover(320, 240, cursor);
assert_eq!(state.selected, GameMode::Survival);
state.hover(320, 240, (cursor.0 + 1, cursor.1));
assert_eq!(state.selected, GameMode::Creative);
state.cycle();
state.hover(320, 240, (cursor.0 + 1, cursor.1));
assert_eq!(state.selected, GameMode::Survival);
}
#[test]
fn hover_slots_exclude_gaps_and_right_and_bottom_edges() {
let mut state = GameModeSwitcher::new(GameMode::Creative, None);
state.hover(320, 240, (0, 0));
let (x, y) = slot_origin(320, 240, 2);
for cursor in [(x - 1, y), (x + 26, y), (x, y - 1), (x, y + 26)] {
state.hover(320, 240, cursor);
assert_eq!(state.selected, GameMode::Survival);
}
state.hover(320, 240, (x + 25, y + 25));
assert_eq!(state.selected, GameMode::Adventure);
}
}
+364 -1
View File
@@ -313,6 +313,73 @@ impl GlyphStyle {
}
}
/// How a controller drives menus (docs/controllers.md, "Menus and
/// inventories").
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum MenuNav {
/// A console-style highlight moved between widgets and slots.
#[default]
Focus,
/// A virtual mouse pointer.
Pointer,
}
impl MenuNav {
pub fn name(self) -> &'static str {
match self {
MenuNav::Focus => "focus",
MenuNav::Pointer => "pointer",
}
}
pub fn parse(name: &str) -> Self {
match name {
"pointer" => MenuNav::Pointer,
_ => MenuNav::Focus,
}
}
}
/// The on-screen keyboard A opens on a text field in focus mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum TextKeyboard {
/// Steam's on a Steam Deck under Steam, else Horizon's.
#[default]
Auto,
Horizon,
Steam,
}
impl TextKeyboard {
pub const ALL: [TextKeyboard; 3] = [
TextKeyboard::Auto,
TextKeyboard::Horizon,
TextKeyboard::Steam,
];
pub fn name(self) -> &'static str {
match self {
TextKeyboard::Auto => "auto",
TextKeyboard::Horizon => "horizon",
TextKeyboard::Steam => "steam",
}
}
pub fn parse(name: &str) -> Self {
match name {
"horizon" => TextKeyboard::Horizon,
"steam" => TextKeyboard::Steam,
_ => TextKeyboard::Auto,
}
}
}
/// Whether A on a text field asks Steam for its keyboard
/// (`steam://open/keyboard`) instead of opening Horizon's: chosen, or `Auto`
/// on a Steam Deck (Steam sets `SteamDeck=1` for the games it starts).
pub fn steam_keyboard(choice: TextKeyboard) -> bool {
match choice {
TextKeyboard::Steam => true,
TextKeyboard::Horizon => false,
TextKeyboard::Auto => std::env::var("SteamDeck").is_ok_and(|v| v == "1"),
}
}
/// The controller settings (`horizon-controller.txt`).
#[derive(Clone, Debug, PartialEq)]
pub struct PadSettings {
@@ -329,6 +396,9 @@ pub struct PadSettings {
/// holding it, unless vanilla's toggle crouch is on already.
pub toggle_sneak: bool,
pub glyphs: GlyphStyle,
/// How the pad drives menus: a focus highlight or a virtual pointer.
pub menu_nav: MenuNav,
pub keyboard: TextKeyboard,
/// Action name -> button, `None` for unbound; missing means the default.
bindings: BTreeMap<&'static str, Option<Button>>,
}
@@ -345,6 +415,8 @@ impl Default for PadSettings {
trigger_threshold: 0.4,
toggle_sneak: true,
glyphs: GlyphStyle::Auto,
menu_nav: MenuNav::Focus,
keyboard: TextKeyboard::Auto,
bindings: BTreeMap::new(),
}
}
@@ -398,6 +470,8 @@ impl PadSettings {
}
"toggleSneak" => s.toggle_sneak = flag(s.toggle_sneak),
"glyphs" => s.glyphs = GlyphStyle::parse(value),
"menuNavigation" => s.menu_nav = MenuNav::parse(value),
"keyboard" => s.keyboard = TextKeyboard::parse(value),
other => {
if let Some(action) = other.strip_prefix("bind_") {
let button = if value == "none" {
@@ -416,7 +490,7 @@ impl PadSettings {
}
pub fn serialize(&self) -> String {
let mut text = format!(
"enabled:{}\nvibration:{}\nlookSensitivity:{}\ninvertX:{}\ninvertY:{}\nmoveDeadzone:{}\nlookDeadzone:{}\ntriggerThreshold:{}\ntoggleSneak:{}\nglyphs:{}\n",
"enabled:{}\nvibration:{}\nlookSensitivity:{}\ninvertX:{}\ninvertY:{}\nmoveDeadzone:{}\nlookDeadzone:{}\ntriggerThreshold:{}\ntoggleSneak:{}\nglyphs:{}\nmenuNavigation:{}\nkeyboard:{}\n",
bool_text(self.enabled),
bool_text(self.vibration),
self.look_sensitivity,
@@ -427,6 +501,8 @@ impl PadSettings {
self.trigger_threshold,
bool_text(self.toggle_sneak),
self.glyphs.name(),
self.menu_nav.name(),
self.keyboard.name(),
);
for (action, button) in &self.bindings {
text.push_str(&format!(
@@ -577,6 +653,202 @@ pub fn focus_step(from: (f32, f32), button: Button, targets: &[(f32, f32)]) -> O
.map(|(i, _)| i)
}
/// A rectangle `[x, y, w, h]` in GUI pixels.
pub type Rect = [f32; 4];
/// The D-pad direction a stick points to, when pushed past `threshold`
/// mostly along one axis (focus steps like the D-pad).
pub fn stick_direction(stick: [f32; 2], threshold: f32) -> Option<Button> {
let [x, y] = stick;
if length(stick) < threshold {
return None;
}
Some(if x.abs() > y.abs() {
if x > 0.0 {
Button::DPadRight
} else {
Button::DPadLeft
}
} else if y > 0.0 {
Button::DPadUp
} else {
Button::DPadDown
})
}
/// Arrow-key focus navigation as vanilla does it
/// (`ContainerEventHandler.nextFocusPathInDirection`), over every target of
/// the screen at once: from a strip one pixel past the focused edge, the
/// nearest target overlapping it on the other axis wins (ties: leftmost or
/// topmost); without one, the target whose facing edge's centre is nearest
/// the focused edge's centre (`nextFocusPathVaguelyInDirection`). Bounds are
/// inclusive as in `ScreenRectangle` (a right edge is `x + w - 1`).
pub fn focus_step_rect(from: Rect, button: Button, targets: &[Rect]) -> Option<usize> {
focus_step_strict(from, button, targets).or_else(|| focus_step_vague(from, button, targets))
}
/// The direction as (axis: 0 = x, 1 = y; positive).
fn direction(button: Button) -> Option<(usize, bool)> {
match button {
Button::DPadUp => Some((1, false)),
Button::DPadDown => Some((1, true)),
Button::DPadLeft => Some((0, false)),
Button::DPadRight => Some((0, true)),
_ => None,
}
}
/// The first pass of [`focus_step_rect`]: targets overlapping the focused
/// one on the other axis (a row, a column).
pub fn focus_step_strict(from: Rect, button: Button, targets: &[Rect]) -> Option<usize> {
let (axis, positive) = direction(button)?;
let other = 1 - axis;
let lo = |r: &Rect, a: usize| r[a];
let hi = |r: &Rect, a: usize| r[a] + r[a + 2] - 1.0;
// Bound in a direction (`getBoundInDirection`).
let bound = |r: &Rect, a: usize, pos: bool| if pos { hi(r, a) } else { lo(r, a) };
let after = |a: f32, b: f32| if positive { a > b + 1e-3 } else { b > a + 1e-3 };
// `getBorder(direction)`: the strip one pixel past the focused edge.
let mut strip = from;
strip[axis] = bound(&from, axis, positive) + if positive { 1.0 } else { -1.0 };
strip[axis + 2] = 1.0;
let first = bound(&strip, axis, !positive);
let same = |a: &Rect, b: &Rect| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5);
let mut strict: Vec<(usize, f32, f32)> = targets
.iter()
.enumerate()
.filter(|(_, r)| !same(r, &from))
.filter(|(_, r)| lo(r, other).max(lo(&strip, other)) <= hi(r, other).min(hi(&strip, other)))
.filter(|(_, r)| {
let child_first = bound(r, axis, !positive);
after(child_first, first)
|| ((child_first - first).abs() < 1e-3
&& after(bound(r, axis, positive), bound(&strip, axis, positive)))
})
.map(|(i, r)| (i, bound(r, axis, !positive), lo(r, other)))
.collect();
strict.sort_by(|a, b| {
let primary = if positive {
a.1.total_cmp(&b.1)
} else {
b.1.total_cmp(&a.1)
};
primary.then(a.2.total_cmp(&b.2))
});
strict.first().map(|s| s.0)
}
/// The second pass of [`focus_step_rect`]: the target whose facing edge's
/// centre is nearest the focused edge's centre.
pub fn focus_step_vague(from: Rect, button: Button, targets: &[Rect]) -> Option<usize> {
let (axis, positive) = direction(button)?;
let other = 1 - axis;
let lo = |r: &Rect, a: usize| r[a];
let hi = |r: &Rect, a: usize| r[a] + r[a + 2] - 1.0;
let bound = |r: &Rect, a: usize, pos: bool| if pos { hi(r, a) } else { lo(r, a) };
let after = |a: f32, b: f32| if positive { a > b + 1e-3 } else { b > a + 1e-3 };
let same = |a: &Rect, b: &Rect| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5);
let mut strip = from;
strip[axis] = bound(&from, axis, positive) + if positive { 1.0 } else { -1.0 };
strip[axis + 2] = 1.0;
let centre = |r: &Rect, a: usize| (hi(r, a) + lo(r, a)) / 2.0;
let edge = bound(&strip, axis, positive);
let mid = centre(&strip, other);
targets
.iter()
.enumerate()
.filter(|(_, r)| !same(r, &from))
.filter_map(|(i, r)| {
let facing = bound(r, axis, !positive);
after(facing, edge).then(|| {
let (d1, d2) = (facing - edge, centre(r, other) - mid);
(i, d1 * d1 + d2 * d2)
})
})
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i)
}
/// How far a list scrolled between two frames' targets: the vertical shift
/// most targets of the same position and size agree on (targets that didn't
/// move, outside the list, don't count). `None` when nothing moved.
pub fn scroll_shift(before: &[Rect], after: &[Rect]) -> Option<f32> {
let same = |a: &Rect, b: &Rect| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5);
if before.len() == after.len() && before.iter().zip(after).all(|(a, b)| same(a, b)) {
return None;
}
let mut votes: Vec<(f32, usize)> = Vec::new();
for b in before {
for a in after {
let dy = a[1] - b[1];
if (a[0] - b[0]).abs() < 0.5
&& (a[2] - b[2]).abs() < 0.5
&& (a[3] - b[3]).abs() < 0.5
&& dy.abs() >= 0.5
{
match votes.iter_mut().find(|v| (v.0 - dy).abs() < 0.5) {
Some(v) => v.1 += 1,
None => votes.push((dy, 1)),
}
}
}
}
// Most votes; among equals the smallest move (the next row, not a far one).
votes
.into_iter()
.max_by(|a, b| a.1.cmp(&b.1).then(b.0.abs().total_cmp(&a.0.abs())))
.map(|v| v.0)
}
/// The target a remembered focus rectangle stands for in a new frame: the
/// same rectangle, else the nearest centre within `radius` (the screen
/// moved it a little: a scrolled list, a resized window).
pub fn refind(focus: Rect, targets: &[Rect], radius: f32) -> Option<usize> {
let same = |r: &Rect| r.iter().zip(&focus).all(|(a, b)| (a - b).abs() < 0.5);
if let Some(i) = targets.iter().position(same) {
return Some(i);
}
let c = |r: &Rect| (r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
let centres: Vec<(f32, f32)> = targets.iter().map(c).collect();
nearest(c(&focus), &centres, radius)
}
/// The next tab after a bumper among tab targets (left to right, then top
/// to bottom), wrapping; `None` with fewer than two tabs.
pub fn tab_step(tabs: &[(Rect, bool)], forward: bool) -> Option<usize> {
if tabs.len() < 2 {
return None;
}
let mut order: Vec<usize> = (0..tabs.len()).collect();
order.sort_by(|&a, &b| {
let (ra, rb) = (tabs[a].0, tabs[b].0);
// A vertical strip of tabs (a sidebar) reads top to bottom.
ra[1].total_cmp(&rb[1]).then(ra[0].total_cmp(&rb[0]))
});
let n = order.len();
let at = order.iter().position(|&i| tabs[i].1).unwrap_or(0);
Some(
order[if forward {
(at + 1) % n
} else {
(at + n - 1) % n
}],
)
}
/// A slider nudge: the pointer x that sets `value` (0..1) on a track
/// `[start, width]` (for vanilla's sliders `x + 4` and `w - 8`:
/// `AbstractSliderButton.setValueFromMouse` inverted).
pub fn slider_x(track: [f32; 2], value: f32) -> f32 {
track[0] + value.clamp(0.0, 1.0) * track[1]
}
/// Pixels a held left/right moves a slider handle per step: one pixel (a
/// vanilla arrow key press) at first, faster while held.
pub fn slider_step(repeats: u32) -> f32 {
[1.0, 1.0, 2.0, 2.0, 4.0, 4.0, 8.0][repeats.min(6) as usize]
}
/// The target within `radius` of `at`, nearest first (the cursor settles
/// onto a slot or button when the stick lets go).
pub fn nearest(at: (f32, f32), targets: &[(f32, f32)], radius: f32) -> Option<usize> {
@@ -819,6 +1091,97 @@ mod tests {
assert_eq!(cursor_delta([0.1, 0.0], 0.15, 0.1), (0.0, 0.0));
}
#[test]
fn focus_follows_vanilla_arrow_navigation() {
// An options screen: two columns of 150-wide buttons 20 high with
// 4 pixels between rows, a full-width Done button under them.
let mut rects: Vec<Rect> = (0..6)
.map(|i| {
let (col, row) = (i % 2, i / 2);
[
5.0 + col as f32 * 160.0,
40.0 + row as f32 * 24.0,
150.0,
20.0,
]
})
.collect();
rects.push([85.0, 120.0, 150.0, 20.0]);
assert_eq!(
focus_step_rect(rects[0], Button::DPadRight, &rects),
Some(1)
);
assert_eq!(focus_step_rect(rects[1], Button::DPadRight, &rects), None);
assert_eq!(focus_step_rect(rects[0], Button::DPadDown, &rects), Some(2));
assert_eq!(focus_step_rect(rects[3], Button::DPadUp, &rects), Some(1));
assert_eq!(focus_step_rect(rects[0], Button::DPadUp, &rects), None);
// Done overlaps both columns: down from either bottom button lands
// on it, up from it picks the leftmost overlapping one.
assert_eq!(focus_step_rect(rects[5], Button::DPadDown, &rects), Some(6));
assert_eq!(focus_step_rect(rects[4], Button::DPadDown, &rects), Some(6));
assert_eq!(focus_step_rect(rects[6], Button::DPadUp, &rects), Some(4));
// Nothing overlaps on the other axis: the vague pass takes the
// nearest facing edge (a crafting result right of the grid).
let grid: Vec<Rect> = vec![
[10.0, 10.0, 16.0, 16.0],
[28.0, 10.0, 16.0, 16.0],
[10.0, 28.0, 16.0, 16.0],
[28.0, 28.0, 16.0, 16.0],
[80.0, 50.0, 16.0, 16.0],
];
assert_eq!(focus_step_rect(grid[1], Button::DPadRight, &grid), Some(4));
assert_eq!(focus_step_rect(grid[4], Button::DPadLeft, &grid), Some(3));
assert_eq!(focus_step_rect(grid[0], Button::DPadDown, &grid), Some(2));
// The focused rectangle itself is never a step, even listed twice.
let dup = vec![grid[0], grid[0]];
assert_eq!(focus_step_rect(grid[0], Button::DPadRight, &dup), None);
assert_eq!(focus_step_rect(grid[0], Button::South, &grid), None);
}
#[test]
fn refind_tabs_sliders_and_stick_steps() {
let rects: Vec<Rect> = vec![[0.0, 0.0, 10.0, 10.0], [0.0, 20.0, 10.0, 10.0]];
assert_eq!(refind([0.0, 20.0, 10.0, 10.0], &rects, 8.0), Some(1));
// A list scrolled by 4 pixels keeps the row.
assert_eq!(refind([0.0, 24.0, 10.0, 10.0], &rects, 8.0), Some(1));
assert_eq!(refind([90.0, 90.0, 10.0, 10.0], &rects, 8.0), None);
// Rows 24 apart scrolled up by 24 under a fixed button.
let before: Vec<Rect> = (0..5)
.map(|i| [10.0, 40.0 + 24.0 * i as f32, 100.0, 20.0])
.chain([[10.0, 200.0, 50.0, 20.0]])
.collect();
let after: Vec<Rect> = (0..5)
.map(|i| [10.0, 16.0 + 24.0 * i as f32, 100.0, 20.0])
.chain([[10.0, 200.0, 50.0, 20.0]])
.collect();
assert_eq!(scroll_shift(&before, &after), Some(-24.0));
assert_eq!(scroll_shift(&before, &before), None);
let tabs = [
([60.0, 0.0, 26.0, 32.0], false),
([0.0, 0.0, 26.0, 32.0], true),
([30.0, 0.0, 26.0, 32.0], false),
];
assert_eq!(tab_step(&tabs, true), Some(2));
assert_eq!(tab_step(&tabs, false), Some(0), "wraps to the last");
assert_eq!(tab_step(&tabs[..1], true), None);
assert_eq!(slider_x([14.0, 142.0], 0.0), 14.0);
assert_eq!(slider_x([14.0, 142.0], 1.0), 156.0);
assert!(slider_step(0) == 1.0 && slider_step(99) == 8.0);
assert_eq!(stick_direction([0.9, 0.2], 0.5), Some(Button::DPadRight));
assert_eq!(stick_direction([-0.2, -0.8], 0.5), Some(Button::DPadDown));
assert_eq!(stick_direction([0.3, 0.3], 0.5), None);
let mut s = PadSettings::default();
assert_eq!(s.menu_nav, MenuNav::Focus);
s.menu_nav = MenuNav::Pointer;
s.keyboard = TextKeyboard::Horizon;
let back = PadSettings::parse(&s.serialize());
assert_eq!(
(back.menu_nav, back.keyboard),
(MenuNav::Pointer, TextKeyboard::Horizon)
);
assert!(steam_keyboard(TextKeyboard::Steam) && !steam_keyboard(TextKeyboard::Horizon));
}
#[test]
fn labels_and_conflicts() {
assert_eq!(Button::South.label(GlyphStyle::Xbox), "A");
+83 -51
View File
@@ -31,32 +31,8 @@ fn entity_shader() -> String {
crate::overlay::wgsl_constants() + include_str!("entity.wgsl")
}
// Separate special materials without changing entity order or their overlays.
fn batch_entities(
entities: &[Vertex],
additive: &[Vertex],
hand: &[Vertex],
) -> (Vec<Vertex>, [u32; 4]) {
let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len());
let mut counts = [0u32; 4];
for (i, layer) in [0, 11, 12, 4].into_iter().enumerate() {
for quad in entities.as_chunks::<4>().0 {
let material = match quad[0].layer {
11 => 11,
12 => 12,
4 => 4,
_ => 0,
};
if material == layer {
combined.extend_from_slice(quad);
counts[i] += 1;
}
}
}
combined.extend_from_slice(additive);
combined.extend_from_slice(hand);
(combined, counts)
}
mod entity_batch;
use entity_batch::EntityBatch;
/// Window.getAppropriateLineWidth, in framebuffer pixels.
pub fn outline_width(width: u32) -> f32 {
@@ -193,6 +169,9 @@ pub struct Frame<'a> {
pub block_flicker: f32,
/// Blur and grade the frame under a Horizon-style menu (`post`).
pub post: Option<crate::post::PostGrade>,
/// `Screen.extractBlurredBackground`: blur the frame by this radius
/// (`menuBackgroundBlurriness`) before the screen is drawn over it.
pub menu_blur: Option<f32>,
}
/// One frame of the world border wall (`WorldBorderRenderer.render`).
#[derive(Clone, Debug)]
@@ -221,6 +200,9 @@ pub struct Renderer {
gpu_timer: Option<timing::GpuTimer>,
/// GPU frame times (ms) read back since the caller last drained them.
pub gpu_times: Vec<f32>,
/// The last lightmap written, RGBA rows of sky level by block level
/// (F3+4 shows it).
pub lightmap_pixels: [u8; 16 * 16 * 4],
/// Time the last `render` spent blocked on the GPU or the display
/// (acquiring, presenting, offscreen pacing), excluded from CPU time.
pub last_wait: std::time::Duration,
@@ -263,6 +245,7 @@ pub struct Renderer {
hand_globals: wgpu::Buffer,
entity_buffer: wgpu::Buffer,
entity_capacity: u64,
entity_batch: EntityBatch,
group: wgpu::BindGroup,
globals: wgpu::Buffer,
lightmap: wgpu::Texture,
@@ -310,6 +293,8 @@ pub struct Renderer {
pub hud: HudRenderer,
/// The menus' backdrop blur, made on first use.
post: Option<crate::post::Post>,
/// Vanilla's menu background blur, made on first use.
menu_blur: Option<crate::menu_blur::MenuBlur>,
pub info: wgpu::AdapterInfo,
pub suspended: bool,
pub drawn_sections: usize,
@@ -432,6 +417,13 @@ impl Renderer {
info.backend,
info.device_type
);
crate::telemetry::set_gpu(
&info.name,
format!("{} {}", info.driver, info.driver_info)
.trim()
.to_owned(),
format!("{:?}", info.backend),
);
crate::crash::set_detail(
"Graphics Adapter",
format!(
@@ -612,7 +604,7 @@ impl Renderer {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(depth_write),
depth_compare: Some(if depth_test {
wgpu::CompareFunction::LessEqual
wgpu::CompareFunction::GreaterEqual
} else {
wgpu::CompareFunction::Always
}),
@@ -979,7 +971,7 @@ impl Renderer {
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(depth_write),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias,
}),
@@ -1003,8 +995,8 @@ impl Renderer {
Some(wgpu::Face::Back),
false,
wgpu::DepthBiasState {
constant: -10,
slope_scale: -1.0,
constant: 10,
slope_scale: 1.0,
clamp: 0.0,
},
CRUMBLING_BLEND,
@@ -1035,7 +1027,7 @@ impl Renderer {
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(false),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias: Default::default(),
}),
@@ -1243,11 +1235,11 @@ impl Renderer {
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias: wgpu::DepthBiasState {
constant: -3,
slope_scale: -3.0,
constant: 3,
slope_scale: 3.0,
clamp: 0.0,
},
}),
@@ -1379,6 +1371,7 @@ impl Renderer {
in_flight: std::collections::VecDeque::new(),
gpu_timer,
gpu_times: Vec::new(),
lightmap_pixels: [0; 16 * 16 * 4],
last_wait: std::time::Duration::ZERO,
last_encode: std::time::Duration::ZERO,
window,
@@ -1413,6 +1406,7 @@ impl Renderer {
hand_globals,
entity_buffer,
entity_capacity,
entity_batch: EntityBatch::default(),
group,
globals,
lightmap,
@@ -1447,6 +1441,7 @@ impl Renderer {
world_post,
hud,
post: None,
menu_blur: None,
info,
suspended: size.width == 0 || size.height == 0,
drawn_sections: 0,
@@ -1740,12 +1735,10 @@ impl Renderer {
}
fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, far: f32) -> Mat4 {
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
Mat4::perspective_rh(fov_degrees.to_radians(), aspect, 0.05, far)
* bob
* crate::camera::view_matrix(yaw, pitch)
world_projection(fov_degrees, aspect, far) * bob * crate::camera::view_matrix(yaw, pitch)
}
fn update_lightmap(
&self,
&mut self,
sky: &Sky,
darkness: f32,
gamma: f32,
@@ -1801,6 +1794,7 @@ impl Renderer {
depth_or_array_layers: 1,
},
);
self.lightmap_pixels = pixels;
}
fn animate(&mut self, tick: u64) {
animate_sprites(
@@ -2117,18 +2111,17 @@ impl Renderer {
self.queue
.write_buffer(&self.outline, 0, bytemuck::cast_slice(&lines));
}
let (
combined,
[
entity_quads,
crumbling_quads,
translucent_crumbling_quads,
cloud_quads,
],
) = batch_entities(frame.entities, frame.additive, frame.hand);
let [
entity_quads,
crumbling_quads,
translucent_crumbling_quads,
cloud_quads,
] = self
.entity_batch
.update(frame.entities, frame.additive, frame.hand);
let world_quads =
entity_quads + crumbling_quads + translucent_crumbling_quads + cloud_quads;
let all_entities = &combined;
let all_entities = &self.entity_batch.combined;
let hand_quads = (frame.hand.len() / 4) as u32;
let additive_quads = (frame.additive.len() / 4) as u32;
let entity_vertices = all_entities.len() as u64;
@@ -2225,7 +2218,7 @@ impl Renderer {
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: world_depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Discard,
}),
stencil_ops: None,
@@ -2355,7 +2348,7 @@ impl Renderer {
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Discard,
}),
stencil_ops: None,
@@ -2413,6 +2406,23 @@ impl Renderer {
pass.draw_indexed(0..6, (i * 4) as i32, 0..1);
}
}
if let Some(radius) = frame.menu_blur
&& self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
{
let format = self.config.format;
let device = &self.device;
self.menu_blur
.get_or_insert_with(|| crate::menu_blur::MenuBlur::new(device, format))
.apply(
&self.device,
&self.queue,
&mut encoder,
&target_texture,
&view_target,
[self.config.width, self.config.height],
radius,
);
}
if let Some(grade) = &frame.post
&& self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
{
@@ -2581,6 +2591,13 @@ impl Frustum {
})
}
}
/// Vanilla's `Projection`: reversed depth (near maps to 1, far to 0, tests
/// are GREATER_THAN_OR_EQUAL), which keeps far faces a hair apart, like
/// fire_side's 0.01 pixel in front of its block, from z-fighting.
fn world_projection(fov_degrees: f32, aspect: f32, far: f32) -> Mat4 {
Mat4::perspective_rh(fov_degrees.to_radians(), aspect, far, 0.05)
}
fn frustum(m: Mat4) -> [Vec4; 6] {
let r = |i| m.row(i);
let planes = [
@@ -2612,7 +2629,9 @@ mod tests {
.into_iter()
.flat_map(|(layer, id)| quad(layer, id))
.collect();
let (vertices, counts) = super::batch_entities(&entities, &quad(3, 5), &quad(0, 6));
let mut batch = super::EntityBatch::default();
let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6));
let vertices = &batch.combined;
assert_eq!(counts, [2, 1, 1, 2]);
assert_eq!(
vertices
@@ -2684,6 +2703,19 @@ mod tests {
assert_eq!(super::outline_width(3840), 5.0);
}
#[test]
fn far_faces_a_hair_apart_keep_their_depth_order() {
let m = super::world_projection(70.0, 16.0 / 9.0, 768.0);
let depth = |distance: f32| {
let clip = m * glam::Vec4::new(0.0, 0.0, -distance, 1.0);
clip.z / clip.w
};
// fire_side at 150 blocks, 0.01 pixel in front of the block it burns on.
let (block, fire) = (depth(150.0), depth(150.0 - 0.01 / 16.0));
assert!(fire > block, "{fire} {block}");
assert!((0.0..=1.0).contains(&block));
assert!((depth(0.05) - 1.0).abs() < 1e-6);
}
#[test]
fn selection_outline_has_vanilla_perspective_layering() {
assert_eq!(
super::outline_params(1280, 720),
@@ -0,0 +1,229 @@
//! Stable entity material grouping with renderer-owned, reusable CPU scratch.
use super::Vertex;
#[derive(Default)]
pub(super) struct EntityBatch {
// Quad indices avoid copying vertices twice while grouping materials.
// Keep initialized high-water storage; local counts delimit active entries.
// Each bucket can hold all quads, removing per-quad Vec growth checks.
buckets: [Vec<usize>; 4],
pub(super) combined: Vec<Vertex>,
}
impl EntityBatch {
pub(super) fn update(
&mut self,
entities: &[Vertex],
additive: &[Vertex],
hand: &[Vertex],
) -> [u32; 4] {
let quads = entities.as_chunks::<4>().0;
for bucket in &mut self.buckets {
if bucket.len() < quads.len() {
bucket.resize(quads.len(), 0);
}
}
let mut counts = [0usize; 4];
for (index, quad) in quads.iter().enumerate() {
let material = match quad[0].layer {
11 => 1,
12 => 2,
4 => 3,
_ => 0,
};
self.buckets[material][counts[material]] = index;
counts[material] += 1;
}
let entity_vertices = quads.len() * 4;
self.combined.reserve(
(entity_vertices + additive.len() + hand.len()).saturating_sub(self.combined.len()),
);
self.combined
.resize(entity_vertices, bytemuck::Zeroable::zeroed());
if counts.contains(&quads.len()) {
// Uniform materials are already ordered; copy the whole batch.
self.combined.copy_from_slice(&entities[..entity_vertices]);
} else {
let mut offset = 0;
for (bucket, &count) in self.buckets.iter().zip(&counts) {
let bucket = &bucket[..count];
let end = offset + count * 4;
for (output, &index) in self.combined[offset..end]
.as_chunks_mut::<4>()
.0
.iter_mut()
.zip(bucket)
{
*output = quads[index];
}
offset = end;
}
}
self.combined.extend_from_slice(additive);
self.combined.extend_from_slice(hand);
counts.map(|count| count as u32)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{hint::black_box, time::Instant};
// Retain the original implementation as the equivalence/benchmark oracle.
fn baseline(
entities: &[Vertex],
additive: &[Vertex],
hand: &[Vertex],
) -> (Vec<Vertex>, [u32; 4]) {
let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len());
let mut counts = [0; 4];
for (i, layer) in [0, 11, 12, 4].into_iter().enumerate() {
for quad in entities.as_chunks::<4>().0 {
let material = match quad[0].layer {
11 => 11,
12 => 12,
4 => 4,
_ => 0,
};
if material == layer {
combined.extend_from_slice(quad);
counts[i] += 1;
}
}
}
combined.extend_from_slice(additive);
combined.extend_from_slice(hand);
(combined, counts)
}
fn geometry(quads: usize, mixed: bool) -> Vec<Vertex> {
(0..quads * 4)
.map(|index| Vertex {
pos: [index as f32, 2.0, 3.0],
uv: [index as f32, 5.0],
layer: if mixed {
[7, 11, 12, 4, 0][index / 4 % 5]
} else {
0
},
color: index as u32,
light: (index * 3) as u32,
normal: [1, 2, 3, 4],
})
.collect()
}
fn equivalent(
batch: &mut EntityBatch,
entities: &[Vertex],
additive: &[Vertex],
hand: &[Vertex],
) {
let (expected, counts) = baseline(entities, additive, hand);
assert_eq!(batch.update(entities, additive, hand), counts);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&batch.combined),
bytemuck::cast_slice::<_, u8>(&expected)
);
}
#[test]
fn stable_material_order_tails_and_reuse() {
let mut batch = EntityBatch::default();
let mut entities = geometry(4096, true);
// Only the first vertex determines a quad's material.
entities[1].layer = 12;
let additive = geometry(3, true);
let hand = geometry(2, false);
// Warm every bucket and the combined buffer to their maximum sizes.
equivalent(&mut batch, &entities, &additive, &hand);
let capacities = batch.buckets.each_ref().map(|b| b.capacity());
let capacity = batch.combined.capacity();
let pointer = batch.combined.as_ptr();
for length in [0, 1, 3, 4, 511, entities.len(), 17, 0, entities.len()] {
equivalent(&mut batch, &entities[..length], &additive[..5], &hand[..3]);
assert_eq!(batch.buckets.each_ref().map(|b| b.capacity()), capacities);
assert_eq!(batch.combined.capacity(), capacity);
assert_eq!(batch.combined.as_ptr(), pointer);
}
equivalent(&mut batch, &[], &[], &[]);
assert!(batch.combined.is_empty());
// Grow again, then confirm empty/small frames retain the new storage.
let larger = geometry(8192, true);
equivalent(&mut batch, &larger, &additive, &hand);
let capacities = batch.buckets.each_ref().map(|b| b.capacity());
let capacity = batch.combined.capacity();
for entities in [&larger[..7], &larger[..], &[]] {
equivalent(&mut batch, entities, &[], &[]);
assert_eq!(batch.buckets.each_ref().map(|b| b.capacity()), capacities);
assert_eq!(batch.combined.capacity(), capacity);
}
}
#[test]
#[ignore = "manual production-helper microbenchmark"]
fn benchmark_entity_batch() {
let additive = geometry(16, false);
let hand = geometry(8, false);
for (name, mixed, quads) in [
("mixed", true, 65_536),
("single", false, 65_536),
("runs", true, 65_536),
("mixed", true, 262_144),
("single", false, 262_144),
] {
let mut entities = geometry(quads, mixed);
if name == "runs" {
// Model/material runs: normal 16, glint 4, overlay 4, shadow 2.
for (index, quad) in entities.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let layer = match index % 26 {
0..16 => 0,
16..20 => 11,
20..24 => 12,
_ => 4,
};
for vertex in quad {
vertex.layer = layer;
}
}
}
let mut batch = EntityBatch::default();
equivalent(&mut batch, &entities, &additive, &hand);
for _ in 0..50 {
black_box(baseline(black_box(&entities), &additive, &hand));
black_box(batch.update(black_box(&entities), &additive, &hand));
black_box(&batch.combined);
}
let mut before = Vec::new();
let mut after = Vec::new();
for _ in 0..15 {
let start = Instant::now();
for _ in 0..100 {
black_box(baseline(black_box(&entities), &additive, &hand));
}
before.push(start.elapsed().as_nanos() / 100);
let start = Instant::now();
for _ in 0..100 {
black_box(batch.update(black_box(&entities), &additive, &hand));
black_box(&batch.combined);
}
after.push(start.elapsed().as_nanos() / 100);
}
before.sort_unstable();
after.sort_unstable();
println!(
"{name}: {quads} quads, baseline={} ns/frame optimized={} ns/frame speedup={:.2}x scratch={} bytes",
before[7],
after[7],
before[7] as f64 / after[7] as f64,
batch.combined.capacity() * std::mem::size_of::<Vertex>()
+ batch
.buckets
.iter()
.map(|b| b.capacity() * std::mem::size_of::<usize>())
.sum::<usize>()
);
}
}
}
+35 -3
View File
@@ -136,6 +136,10 @@ pub struct Graphics {
pub fxaa: bool,
/// The settings level last shown: Advanced, or Simple.
pub advanced: bool,
/// Battery mode: at most 60 frames per second in a world and 30 in menus
/// or behind other windows, and half the worker threads. Off by default;
/// it changes when frames are drawn, never what they show or the ticks.
pub battery: bool,
}
impl Default for Graphics {
fn default() -> Self {
@@ -155,6 +159,7 @@ impl Default for Graphics {
resolution_scale: 100,
fxaa: false,
advanced: false,
battery: false,
}
}
}
@@ -201,6 +206,7 @@ impl Graphics {
"resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200),
"fxaa" => g.fxaa = flag(g.fxaa),
"level" => g.advanced = value == "advanced",
"batteryMode" => g.battery = flag(g.battery),
"overlay" => {
g.overlay = match value {
"fps" => Overlay::Fps,
@@ -215,7 +221,7 @@ impl Graphics {
}
pub fn serialize(&self) -> String {
format!(
"preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\n",
"preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\n",
self.preset.name(),
bool_text(self.cave_culling),
self.chunk_updates,
@@ -238,6 +244,7 @@ impl Graphics {
self.resolution_scale,
bool_text(self.fxaa),
if self.advanced { "advanced" } else { "simple" },
bool_text(self.battery),
)
}
pub fn save(&self, dir: &Path) {
@@ -248,10 +255,22 @@ impl Graphics {
if self.workers > 0 {
return self.workers as usize;
}
std::thread::available_parallelism()
let auto = std::thread::available_parallelism()
.map_or(2, |n| n.get())
.saturating_sub(1)
.max(1)
.max(1);
if self.battery { auto.div_ceil(2) } else { auto }
}
/// The frame cap battery mode adds: 60 in a world, 30 in menus without a
/// world or while another window has focus.
pub fn battery_limit(&self, limit: i32, in_world: bool, focused: bool) -> i32 {
if !self.battery {
limit
} else if in_world && focused {
limit.min(60)
} else {
limit.min(30)
}
}
}
@@ -309,6 +328,7 @@ mod tests {
resolution_scale: 75,
fxaa: true,
advanced: true,
battery: true,
};
assert_eq!(Graphics::parse(&g.serialize()), g);
assert_eq!(Graphics::parse(""), Graphics::default());
@@ -317,4 +337,16 @@ mod tests {
Graphics::default()
);
}
#[test]
fn battery_mode_only_lowers_the_frame_cap() {
let mut g = Graphics::default();
assert_eq!(g.battery_limit(260, true, true), 260);
g.battery = true;
assert_eq!(g.battery_limit(260, true, true), 60);
assert_eq!(g.battery_limit(30, true, true), 30);
assert_eq!(g.battery_limit(260, false, true), 30);
assert_eq!(g.battery_limit(260, true, false), 30);
assert_eq!(g.battery_limit(10, true, false), 10);
}
}
+25 -15
View File
@@ -34,6 +34,7 @@ pub enum H {
Overlay,
ResolutionScale,
Antialiasing,
BatteryMode,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -219,6 +220,11 @@ pub fn rows(level: Level) -> Vec<Row> {
v(Opt::Autosave, None, "Shows when the world saves."),
v(Opt::AttackIndicator, None, "Shows attack cooldown."),
Row::Header("Performance"),
h(
H::BatteryMode,
None,
"60 FPS cap (30 in menus or unfocused), half the workers: less power.",
),
h(
H::Workers,
None,
@@ -297,6 +303,7 @@ impl H {
},
H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)),
H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }),
H::BatteryMode => labelled("Battery Mode", on_off(g.battery)),
H::Overlay => labelled(
"Performance Overlay",
match g.overlay {
@@ -341,6 +348,7 @@ impl H {
H::AnimatedTextures => g.animated_textures = !g.animated_textures,
H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back),
H::Antialiasing => g.fxaa = !g.fxaa,
H::BatteryMode => g.battery = !g.battery,
H::Pacing => {
g.pacing = match g.pacing {
Pacing::Efficient => Pacing::Precise,
@@ -373,6 +381,7 @@ impl Item {
Item::Horizon(H::Weather) => g.weather,
Item::Horizon(H::AnimatedTextures) => g.animated_textures,
Item::Horizon(H::Antialiasing) => g.fxaa,
Item::Horizon(H::BatteryMode) => g.battery,
Item::Vanilla(Opt::ViewBobbing) => s.view_bobbing,
Item::Vanilla(Opt::Vsync) => s.vsync,
Item::Vanilla(Opt::Fullscreen) => s.fullscreen,
@@ -423,21 +432,22 @@ impl Item {
fn touched(self, s: &mut Settings) {
let presetless = matches!(
self,
Item::Horizon(H::Preset | H::Overlay | H::Pacing | H::PresentMode | H::Workers)
| Item::Vanilla(
Opt::GuiScale
| Opt::Fullscreen
| Opt::Vsync
| Opt::MaxFps
| Opt::Fov
| Opt::Gamma
| Opt::InactivityFps
| Opt::ViewBobbing
| Opt::ChunkFade
| Opt::Vignette
| Opt::Autosave
| Opt::AttackIndicator
)
Item::Horizon(
H::Preset | H::Overlay | H::Pacing | H::PresentMode | H::Workers | H::BatteryMode
) | Item::Vanilla(
Opt::GuiScale
| Opt::Fullscreen
| Opt::Vsync
| Opt::MaxFps
| Opt::Fov
| Opt::Gamma
| Opt::InactivityFps
| Opt::ViewBobbing
| Opt::ChunkFade
| Opt::Vignette
| Opt::Autosave
| Opt::AttackIndicator
)
);
if !presetless {
s.horizon.preset = Preset::Custom;
+3
View File
@@ -95,6 +95,8 @@ pub enum HealthEvent {
FreezeDamage(f32),
/// `SweetBerryBushBlock.entityInside` pricking a moving entity.
SweetBerryBushDamage(f32),
/// `LivingEntity.baseTick` drowning an entity out of air.
DrownDamage(f32),
Updated {
id: u8,
value: f32,
@@ -128,6 +130,7 @@ impl HealthEvent {
Self::SweetBerryBushDamage(amount) => {
format!("damage sweet_berry_bush {:08x}", amount.to_bits())
}
Self::DrownDamage(amount) => format!("damage drown {:08x}", amount.to_bits()),
Self::Updated { id, value, dirty } => {
format!("updated {id} {:08x} {dirty}", value.to_bits())
}
+69
View File
@@ -947,6 +947,75 @@ impl HudRenderer {
mod tests {
use super::*;
#[test]
fn effect_icons_are_painted_from_the_mob_effect_directory() {
use crate::{effects::EffectInstance, hud_layout, hud_overlays, inventory_effects};
// A synthetic resource tree exercises loading and painting together.
// No Minecraft installation or GPU is needed for this regression test.
let root =
std::env::temp_dir().join(format!("horizon-effect-icons-{}", std::process::id()));
for (name, size) in [
("mob_effect/levitation", 18),
("gui/sprites/hud/effect_background", 24),
("gui/sprites/container/inventory/effect_background", 32),
] {
let path = root.join(format!("assets/minecraft/textures/{name}.png"));
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut encoder = png::Encoder::new(fs::File::create(path).unwrap(), size, size);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.unwrap()
.write_image_data(&vec![255; (size * size * 4) as usize])
.unwrap();
}
let atlas = HudAtlas::build(&root).unwrap();
let effect = EffectInstance::new("levitation", -1, 0);
let icon = hud_overlays::EffectIcon::from(&effect);
let draws = hud_overlays::effects(320, false, &[icon]);
let mut batch = HudBatch::new([320, 240]);
hud_layout::paint(&mut batch, &atlas, &draws);
// Both the background and the 18x18 effect icon must reach the batch.
assert_eq!(batch.vertices.len(), 12);
let rect = atlas.sprites["mob_effect/levitation"];
assert_eq!(batch.vertices[6].pos, [298.0, 30.0]);
assert_eq!(batch.vertices[6].uv, [rect.u0, rect.v0]);
assert_eq!(batch.vertices[8].uv, [rect.u1, rect.v1]);
let panels = inventory_effects::panels(
320,
[72, 37],
176,
std::slice::from_ref(&effect),
20.0,
&|_| None,
&|_| 60,
);
batch.vertices.clear();
let tooltip = inventory_effects::paint(&mut batch, &atlas, &panels, [257, 44]);
assert_eq!(tooltip.unwrap()[0].0, "levitation");
assert_eq!(batch.vertices.len(), 24);
assert_eq!(batch.vertices[18].pos, [257.0, 44.0]);
assert_eq!(batch.vertices[18].uv, [rect.u0, rect.v0]);
assert_eq!(batch.vertices[20].uv, [rect.u1, rect.v1]);
// Wide panels retain the four-pixel border instead of stretching it.
let panels =
inventory_effects::panels(480, [72, 37], 176, &[effect], 20.0, &|_| None, &|_| 60);
batch.vertices.clear();
assert!(inventory_effects::paint(&mut batch, &atlas, &panels, [0, 0]).is_none());
assert!(batch.vertices.iter().any(|v| v.color == 0xff808080));
assert_eq!(batch.vertices[0].pos, [250.0, 37.0]);
assert_eq!(batch.vertices[1].pos, [254.0, 37.0]);
let background = atlas.sprites["gui/sprites/container/inventory/effect_background"];
assert!(
(batch.vertices[1].uv[0] - background.u0 - (background.u1 - background.u0) / 8.0).abs()
< 1e-6
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn hud_shader_validates_both_fragment_entries() {
let module = naga::front::wgsl::parse_str(include_str!("hud.wgsl")).unwrap();
+8 -2
View File
@@ -790,8 +790,14 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
color,
blend,
} => {
let Some(mut r) = atlas.sprites.get(&format!("gui/sprites/{sprite}")).copied()
else {
// Effect sprites belong to the mob_effect atlas directory;
// the other blitSprite ids refer to GUI sprites.
let name = if sprite.starts_with("mob_effect/") {
sprite.to_string()
} else {
format!("gui/sprites/{sprite}")
};
let Some(mut r) = atlas.sprites.get(&name).copied() else {
continue;
};
if let Some([sw, sh, u, v]) = *region {
+16 -1
View File
@@ -105,8 +105,23 @@ pub struct EffectIcon {
pub show_icon: bool,
}
impl From<&crate::effects::EffectInstance> for EffectIcon {
fn from(effect: &crate::effects::EffectInstance) -> Self {
let def = crate::brewing::effect(effect.id);
Self {
id: effect.id.to_owned(),
beneficial: def.is_some_and(|d| d.category == crate::brewing::Category::Beneficial),
color: def.map_or(0, |d| d.color as i32),
ambient: effect.ambient,
duration: effect.duration,
// Horizon keeps no showIcon flag: every effect shows its icon.
show_icon: true,
}
}
}
/// `MobEffectInstance.compareTo`.
fn compare_effects(a: &EffectIcon, o: &EffectIcon) -> Ordering {
pub(crate) fn compare_effects(a: &EffectIcon, o: &EffectIcon) -> Ordering {
if (a.duration <= 32147 || o.duration <= 32147) && !(a.ambient && o.ambient) {
a.ambient
.cmp(&o.ambient)
@@ -0,0 +1,255 @@
//! `EffectsInInventory`: active effect panels beside survival and creative
//! inventories, with compact icons when there is little room on the right.
use crate::{
effects::EffectInstance,
hud::{HudAtlas, HudBatch},
hud_overlays::{EffectIcon, compare_effects, java_sort},
};
#[derive(Debug, PartialEq)]
pub struct EffectPanel {
pub icon: EffectIcon,
pub name: String,
pub duration: String,
pub x: i32,
pub y: i32,
pub width: i32,
pub spacing: i32,
}
/// Lay out panels using the container's actual origin (including recipe book
/// shifts). Vanilla hides them when fewer than 32 GUI pixels remain.
pub fn panels(
screen_width: i32,
origin: [i32; 2],
image_width: i32,
effects: &[EffectInstance],
tick_rate: f32,
translate: &dyn Fn(&str) -> Option<String>,
text_width: &dyn Fn(&str) -> i32,
) -> Vec<EffectPanel> {
let x = origin[0] + image_width + 2;
let available = screen_width - x;
if effects.is_empty() || available < 32 {
return Vec::new();
}
let max_width = if available >= 120 { available - 7 } else { 32 };
let spacing = if effects.len() > 5 {
132 / (effects.len() as i32 - 1)
} else {
33
};
let mut sorted: Vec<_> = effects.iter().map(|e| (e, EffectIcon::from(e))).collect();
java_sort(&mut sorted, |a, b| compare_effects(&a.1, &b.1));
sorted
.into_iter()
.enumerate()
.map(|(i, (effect, icon))| {
let mut name = translate(&format!("effect.minecraft.{}", effect.id))
.unwrap_or_else(|| effect.id.to_owned());
if (1..=9).contains(&effect.amplifier) {
let level = effect.amplifier + 1;
let suffix = translate(&format!("enchantment.level.{level}"))
.unwrap_or_else(|| crate::enchant::level_name(level as u32));
name = format!("{name} {suffix}");
}
let duration = if effect.duration == -1 {
translate("effect.duration.infinite").unwrap_or_else(|| "∞".to_owned())
} else {
// StringUtil.formatTickDuration uses the level's current rate.
let seconds = (effect.duration as f32 / tick_rate) as i32;
let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
if hours > 0 {
format!("{hours:02}:{minutes:02}:{seconds:02}")
} else {
format!("{minutes:02}:{seconds:02}")
}
};
let width = max_width.min(39 + text_width(&name).max(text_width(&duration)));
EffectPanel {
icon,
name,
duration,
x,
y: origin[1] + i as i32 * spacing,
width,
spacing,
}
})
.collect()
}
/// The inventory effect background has a four-pixel nine-slice border. Since
/// its height stays 32, only horizontal slicing/tiling is needed.
fn background(batch: &mut HudBatch, atlas: &HudAtlas, panel: &EffectPanel) {
let name = if panel.icon.ambient {
"gui/sprites/container/inventory/effect_background_ambient"
} else {
"gui/sprites/container/inventory/effect_background"
};
let Some(rect) = atlas.sprites.get(name).copied() else {
return;
};
let mut strip = |dx: i32, sx: i32, width: i32| {
let mut r = rect;
let du = rect.u1 - rect.u0;
r.u0 = rect.u0 + du * sx as f32 / 32.0;
r.u1 = r.u0 + du * width as f32 / 32.0;
batch.rect_uv(
(panel.x + dx) as f32,
panel.y as f32,
width as f32,
32.0,
r,
u32::MAX,
);
};
strip(0, 0, 4);
let mut dx = 4;
while dx < panel.width - 4 {
let width = 24.min(panel.width - 4 - dx);
strip(dx, 4, width);
dx += width;
}
strip(panel.width - 4, 28, 4);
}
/// Paint panels and return the full name/duration tooltip for a hovered compact
/// or clipped panel. Its hover height follows the spacing of overlapping rows.
pub fn paint(
batch: &mut HudBatch,
atlas: &HudAtlas,
panels: &[EffectPanel],
cursor: [i32; 2],
) -> Option<[(String, u32); 2]> {
let mut tooltip = None;
for panel in panels {
background(batch, atlas, panel);
let text_width = panel.width - 39;
let clipped = atlas.font.width(&panel.name).ceil() as i32 > text_width;
if text_width > 0 {
let shown = if clipped {
let available = text_width as f32 - atlas.font.width("...");
let count = atlas.font.fit(&panel.name, available);
format!("{}...", panel.name.chars().take(count).collect::<String>())
} else {
panel.name.clone()
};
batch.text(
atlas,
&shown,
(panel.x + 32) as f32,
(panel.y + 7) as f32,
u32::MAX,
true,
);
batch.text(
atlas,
&panel.duration,
(panel.x + 32) as f32,
(panel.y + 16) as f32,
0xff808080,
true,
);
}
batch.sprite_scaled(
atlas,
&format!("mob_effect/{}", panel.icon.id),
(panel.x + 7) as f32,
(panel.y + 7) as f32,
18.0,
18.0,
u32::MAX,
);
if (text_width <= 0 || clipped)
&& cursor[0] >= panel.x
&& cursor[0] <= panel.x + panel.width
&& cursor[1] >= panel.y
&& cursor[1] <= panel.y + panel.spacing
{
tooltip = Some([
(panel.name.clone(), u32::MAX),
(panel.duration.clone(), u32::MAX),
]);
}
}
tooltip
}
#[cfg(test)]
mod tests {
use super::*;
fn layout(width: i32, effects: &[EffectInstance]) -> Vec<EffectPanel> {
panels(
width,
[72, 37],
176,
effects,
20.0,
&|key| match key {
"effect.minecraft.levitation" => Some("Levitation".into()),
"effect.minecraft.speed" => Some("Speed".into()),
_ => None,
},
&|text| text.chars().count() as i32 * 6,
)
}
#[test]
fn inventory_labels_levels_and_durations() {
let effects = [
EffectInstance::new("levitation", -1, 0),
EffectInstance::new("speed", 450, 1),
];
let p = layout(480, &effects);
assert_eq!(p.len(), 2);
// Natural order puts shorter durations before infinite effects.
assert_eq!(
(&p[0].name, &p[0].duration),
(&"Speed II".into(), &"00:22".into())
);
assert_eq!(
(&p[1].name, &p[1].duration),
(&"Levitation".into(), &"∞".into())
);
assert_eq!((p[0].x, p[0].y, p[0].width), (250, 37, 87));
assert_eq!((p[1].x, p[1].y, p[1].width), (250, 70, 99));
}
#[test]
fn narrow_windows_hide_or_compact_the_panels() {
let effects = [EffectInstance::new("levitation", -1, 0)];
assert!(layout(281, &effects).is_empty());
assert_eq!(layout(282, &effects)[0].width, 32);
assert_eq!(layout(369, &effects)[0].width, 32);
assert_eq!(layout(370, &effects)[0].width, 99);
assert!(layout(480, &[]).is_empty());
}
#[test]
fn crowded_effects_overlap_and_preserve_ambient_order() {
let mut effects: Vec<_> = (0..7)
.map(|i| EffectInstance::new("speed", (i + 1) * 100, 0))
.collect();
effects[0].ambient = true;
let p = layout(480, &effects);
assert_eq!(p[0].icon.duration, 200);
assert!(p.last().unwrap().icon.ambient);
assert_eq!(
p.iter().map(|p| p.y).collect::<Vec<_>>(),
[37, 59, 81, 103, 125, 147, 169]
);
}
#[test]
fn creative_origin_recipe_book_shift_and_tick_rate() {
let effects = [EffectInstance::new("speed", 72000, 10)];
let p = panels(640, [222, 43], 195, &effects, 10.0, &|_| None, &|_| 60);
assert_eq!((p[0].x, p[0].y), (419, 43));
assert_eq!(p[0].name, "speed");
assert_eq!(p[0].duration, "02:00:00");
let p = panels(480, [149, 37], 176, &effects, 20.0, &|_| None, &|_| 150);
assert_eq!((p[0].x, p[0].width), (327, 146));
}
}
+3 -1
View File
@@ -420,8 +420,10 @@ impl Hub {
}
fn admit(&mut self, j: super::Joined, ctx: &mut TickCtx) -> u32 {
let entity_id = *ctx.next_entity as i32;
// The game's ids are taken by incrementing first: the current value
// is the last id in use (the host's own, right after opening to LAN).
*ctx.next_entity += 1;
let entity_id = *ctx.next_entity as i32;
let conn = j.conn;
let mut guest = Guest::new(j, entity_id, ctx.spawn, self.config.view_distance);
guest.last_action_tick = self.ticks;
+10
View File
@@ -13,6 +13,8 @@ pub mod audio;
pub mod auth;
pub mod auto_jump;
pub mod banner;
pub mod beehive;
pub mod benchmark;
pub mod biome;
pub mod block_entity_anim;
pub mod block_entity_nbt;
@@ -27,6 +29,7 @@ pub mod camera;
pub mod cauldron;
pub mod chat;
pub mod chunk;
pub mod chunk_map;
pub mod clipboard;
pub mod clock;
pub mod clouds;
@@ -42,6 +45,7 @@ pub mod crash;
pub mod creative;
pub mod data_cmd;
pub mod datapack;
pub mod debug_chart;
pub mod debug_keys;
pub mod effects;
pub mod enchant;
@@ -59,6 +63,7 @@ pub mod flatgen;
pub mod fog;
pub mod font;
pub mod front;
pub mod game_mode_switcher;
pub mod gamepad;
pub mod gamerules;
pub mod gfx;
@@ -74,6 +79,7 @@ pub mod hud_layout;
pub mod hud_overlays;
pub mod hunger;
pub mod input;
pub mod inventory_effects;
pub mod item_data;
pub mod item_render;
pub mod item_tooltip;
@@ -88,6 +94,7 @@ pub mod lang;
pub mod light;
pub mod logging;
pub mod menu;
pub mod menu_blur;
pub mod merchant;
pub mod mesher;
pub mod minimap;
@@ -106,6 +113,7 @@ pub mod options_file;
pub mod options_fixes;
pub mod options_horizon;
pub mod options_ui;
pub mod osk;
pub mod overlay;
pub mod pack_screen;
pub mod packs;
@@ -144,8 +152,10 @@ pub mod stopwatches;
pub mod streaming;
pub mod structure_blocks;
pub mod tab_list;
pub mod telemetry;
pub mod testgen;
pub mod text;
pub mod tick_chunk_membership;
pub mod title;
pub mod title_edition;
pub mod ui;
+219 -21
View File
@@ -16,7 +16,7 @@
//! directly to resident chunks after a block change.
use crate::{
blocks::BlockFacts,
chunk::{Chunk, HEIGHT, Light, MIN_Y, SECTIONS, Section, index},
chunk::{Chunk, HEIGHT, Light, MIN_Y, SECTIONS, index},
};
use horizon_core::geometry::{Direction, ShapeOp, VoxelShape};
use horizon_world::registry::{BlockRegistry, BlockStateId};
@@ -195,8 +195,8 @@ pub fn light_chunk(
region: &[[Option<&Chunk>; 3]; 3],
tables: &LightTables,
sky_light: bool,
) -> Vec<Arc<Section>> {
let center = region[1][1].expect("centre chunk");
) -> Vec<Light> {
region[1][1].expect("centre chunk");
// Highest occupied section in the region bounds the work.
let mut top_section = 0;
for chunk in region.iter().flatten().flatten() {
@@ -321,20 +321,22 @@ pub fn light_chunk(
};
spread(&mut sky, &mut sky_queue);
spread(&mut block, &mut queue);
let mut sections = Vec::with_capacity(SECTIONS);
for (si, section) in center.sections.iter().enumerate() {
let mut out = (**section).clone();
let open = if sky_light { 0xF0 } else { 0x00 };
if si * 16 >= h {
out.light = Light::Uniform(open);
} else {
let mut data = Box::new([0u8; 4096]);
pack_lighting(h, &sky, &block, sky_light)
}
/// Extract just the centre column's light; never copy worker snapshot sections.
fn pack_lighting(h: usize, sky: &[u8], block: &[u8], sky_light: bool) -> Vec<Light> {
let at = |x: usize, y: usize, z: usize| (y * W + z) * W + x;
let open = if sky_light { 0xF0 } else { 0x00 };
(0..SECTIONS)
.map(|si| {
if si * 16 >= h {
return Light::Uniform(open);
}
let mut data = Box::new([open; 4096]);
for ly in 0..16 {
let y = si * 16 + ly;
if y >= h {
for i in 0..256 {
data[ly << 8 | i] = open;
}
continue;
}
for lz in 0..16 {
@@ -344,12 +346,21 @@ pub fn light_chunk(
}
}
}
out.light = Light::Full(data);
}
out.compact();
sections.push(Arc::new(out));
if data.iter().all(|&v| v == data[0]) {
Light::Uniform(data[0])
} else {
Light::Full(data)
}
})
.collect()
}
/// Move a worker's light into current sections, preserving later block/biome
/// edits and immutable snapshots retained by other workers.
pub fn apply_lighting(chunk: &mut Chunk, lights: Vec<Light>) {
for (section, light) in chunk.sections.iter_mut().zip(lights) {
Arc::make_mut(section).light = light;
}
sections
}
/// Resident chunks the incremental relighter reads and writes.
@@ -622,7 +633,7 @@ mod tests {
std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1)))
});
let mut c = chunks[&(x, z)].clone();
c.sections = light_chunk(&region, &tables(), true);
apply_lighting(&mut c, light_chunk(&region, &tables(), true));
c.lit = true;
((x, z), Arc::new(c))
})
@@ -691,11 +702,198 @@ mod tests {
for (si, s) in full.iter().enumerate() {
for i in 0..4096 {
assert_eq!(
s.light(i),
s.get(i),
w[&(0, 0)].sections[si].light(i),
"section {si} index {i}"
);
}
}
}
#[test]
fn lighting_result_preserves_current_edits_and_snapshots() {
let mut current = Chunk::empty(0, 0);
current.set(8, MIN_Y, 8, TORCH);
let region = [[None; 3], [None, Some(&current), None], [None; 3]];
let lights = light_chunk(&region, &tables(), true);
let Light::Full(data) = &lights[0] else {
panic!("torch light varies");
};
let result_storage = data.as_ptr();
let snapshot = current.clone();
current.set(8, MIN_Y, 8, STONE);
Arc::make_mut(&mut current.sections[0]).biomes.set(0, 3);
let edited_snapshot = current.clone();
apply_lighting(&mut current, lights);
let Light::Full(data) = &current.sections[0].light else {
panic!("torch light varies");
};
assert_eq!(
result_storage,
data.as_ptr(),
"returned light storage moves without cloning"
);
current.lit = true;
assert_eq!(current.get(8, MIN_Y, 8), STONE);
assert_eq!(current.sections[0].biomes.get(0), 3);
assert_eq!(snapshot.get(8, MIN_Y, 8), TORCH);
assert_eq!(edited_snapshot.sections[0].light(index(8, MIN_Y, 8)), 0xF0);
let mut world = HashMap::from([((0, 0), Arc::new(current))]);
// Streaming replays edits made after the job snapshot with force=true.
relight(&mut world, &tables(), true, &[(8, MIN_Y, 8)], true);
let region = [[None; 3], [None, Some(&*world[&(0, 0)]), None], [None; 3]];
let fresh = light_chunk(&region, &tables(), true);
for (section, light) in world[&(0, 0)].sections.iter().zip(fresh) {
for i in 0..4096 {
assert_eq!(section.light(i), light.get(i));
}
}
}
#[test]
fn empty_chunk_missing_neighbours_and_no_sky() {
let mut chunk = Chunk::empty(0, 0);
for sky in [false, true] {
let region = [[None; 3], [None, Some(&chunk), None], [None; 3]];
let lights = light_chunk(&region, &tables(), sky);
assert_eq!(lights.len(), SECTIONS);
assert!(
lights
.iter()
.all(|v| matches!(v, Light::Uniform(n) if *n == if sky { 0xF0 } else { 0 }))
);
let section = Arc::as_ptr(&chunk.sections[0]);
apply_lighting(&mut chunk, lights);
assert_eq!(section, Arc::as_ptr(&chunk.sections[0]));
}
}
// Original main's worker packaging and streaming application. Kept here
// so the benchmark compares the real former copy/compaction work.
fn baseline_pack(
center: &Chunk,
h: usize,
sky: &[u8],
block: &[u8],
) -> Vec<Arc<crate::chunk::Section>> {
let at = |x: usize, y: usize, z: usize| (y * W + z) * W + x;
let mut sections = Vec::with_capacity(SECTIONS);
for (si, section) in center.sections.iter().enumerate() {
let mut out = (**section).clone();
if si * 16 >= h {
out.light = Light::Uniform(0xF0);
} else {
let mut data = Box::new([0u8; 4096]);
for ly in 0..16 {
let y = si * 16 + ly;
if y >= h {
for i in 0..256 {
data[ly << 8 | i] = 0xF0;
}
continue;
}
for lz in 0..16 {
for lx in 0..16 {
let p = at(16 + lx, y, 16 + lz);
data[index(lx as i32, ly as i32, lz as i32)] = sky[p] << 4 | block[p];
}
}
}
out.light = Light::Full(data);
}
out.compact();
sections.push(Arc::new(out));
}
sections
}
fn baseline_apply(chunk: &mut Chunk, sections: Vec<Arc<crate::chunk::Section>>) {
for (target, lit) in chunk.sections.iter_mut().zip(sections) {
let mut section = (**target).clone();
section.light = lit.light.clone();
*target = Arc::new(section);
}
}
#[test]
#[ignore = "microbenchmark; run with --ignored --nocapture"]
fn benchmark_worker_light_results() {
use std::{hint::black_box, time::Instant};
let mut fixture = Chunk::empty(0, 0);
for (si, s) in fixture.sections.iter_mut().enumerate() {
let section = Arc::make_mut(s);
for i in 0..4096 {
section.set(i, ((i + si) % 16) as u16);
}
for i in 0..64 {
section.biomes.set(i, (i % 4) as u32);
}
section.light = Light::Full(Box::new([0x87; 4096]));
}
let h = HEIGHT as usize;
let sky: Vec<_> = (0..W * W * h).map(|i| (i % 16) as u8).collect();
let block: Vec<_> = (0..W * W * h).map(|i| ((i / 16) % 16) as u8).collect();
let mut old = fixture.clone();
let mut new = fixture.clone();
baseline_apply(&mut old, baseline_pack(&fixture, h, &sky, &block));
apply_lighting(&mut new, pack_lighting(h, &sky, &block, true));
for (a, b) in old.sections.iter().zip(&new.sections) {
for i in 0..4096 {
assert_eq!(a.light(i), b.light(i));
assert_eq!(a.get(i), b.get(i));
}
for i in 0..64 {
assert_eq!(a.biomes.get(i), b.biomes.get(i));
}
}
for shared in [false, true] {
let mut times = [Vec::new(), Vec::new()];
for round in 0..11 {
for optimized in [round % 2 == 0, round % 2 != 0] {
let mut current = fixture.clone();
let held = shared.then(|| current.clone());
// Warm up and detach for the uniquely-owned scenario.
apply_lighting(&mut current, pack_lighting(h, &sky, &block, true));
let started = Instant::now();
for _ in 0..500 {
let retained = shared.then(|| current.clone());
if optimized {
apply_lighting(
black_box(&mut current),
pack_lighting(h, black_box(&sky), black_box(&block), true),
);
} else {
baseline_apply(
black_box(&mut current),
baseline_pack(
black_box(&fixture),
h,
black_box(&sky),
black_box(&block),
),
);
}
black_box(retained);
black_box(&current);
}
if round > 0 {
times[usize::from(optimized)]
.push(started.elapsed().as_secs_f64() * 1e6 / 500.0);
}
black_box(held);
}
}
for values in &mut times {
values.sort_by(f64::total_cmp);
}
println!(
"pack+apply shared={shared}: baseline {:.3} us optimized {:.3} us speedup {:.2}x",
times[0][5],
times[1][5],
times[0][5] / times[1][5]
);
}
let payload: usize = fixture.sections.iter().map(|s| s.heap_bytes()).sum();
println!(
"fixture heap payload {payload} bytes; old worker clones it plus 24 section Arcs; old application clones current payload and 98304 returned light bytes. New worker clones zero section payload; new application clones current payload only when shared."
);
}
}
+1
View File
@@ -5,6 +5,7 @@ mod game;
use horizon_client::{crash, logging};
fn main() {
horizon_client::telemetry::mark_start();
let args: Vec<String> = std::env::args().skip(1).collect();
let game_args = args.iter().take_while(|a| *a != "--dedicated");
let help = game_args.clone().any(|a| a == "--help" || a == "-h");
+249
View File
@@ -0,0 +1,249 @@
//! Vanilla's menu background blur (`GameRenderer.processBlurEffect`, the
//! `minecraft:blur` post chain): three rounds of a horizontal then a vertical
//! `post/box_blur` pass over the frame drawn so far, `menuBackgroundBlurriness`
//! framebuffer pixels wide, before the screen is drawn over it. Works in the
//! frame's own (gamma) values, as vanilla's main target does, and needs a
//! swapchain that can be copied from.
/// `blur.json`: the passes' directions, ping-ponging between the copied
/// frame and a swap texture; the last one writes the frame.
const PASSES: [[f32; 2]; 6] = [
[1.0, 0.0],
[0.0, 1.0],
[1.0, 0.0],
[0.0, 1.0],
[1.0, 0.0],
[0.0, 1.0],
];
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Uniform {
size_dir: [f32; 4],
radius: [f32; 4],
}
pub struct MenuBlur {
layout: wgpu::BindGroupLayout,
pipeline: wgpu::RenderPipeline,
sampler: wgpu::Sampler,
uniforms: Vec<wgpu::Buffer>,
/// The copied frame (`minecraft:main`) and `swap`.
targets: Vec<(wgpu::Texture, wgpu::TextureView)>,
size: [u32; 2],
format: wgpu::TextureFormat,
}
impl MenuBlur {
/// `format` is the swapchain's; the blur works in its non-sRGB view.
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
let format = format.remove_srgb_suffix();
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Menu blur"),
source: wgpu::ShaderSource::Wgsl(include_str!("menu_blur.wgsl").into()),
});
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Menu blur bindings"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Menu blur"),
bind_group_layouts: &[Some(&layout)],
..Default::default()
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Menu blur pass"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
multiview_mask: None,
cache: None,
});
// The post chain's "bilinear": true inputs, clamped like render targets.
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Menu blur"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
..Default::default()
});
let uniforms = PASSES
.iter()
.map(|_| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Menu blur pass"),
size: std::mem::size_of::<Uniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
})
.collect();
Self {
layout,
pipeline,
sampler,
uniforms,
targets: Vec::new(),
size: [0, 0],
format,
}
}
fn ensure(&mut self, device: &wgpu::Device, size: [u32; 2]) {
if self.size == size && !self.targets.is_empty() {
return;
}
self.size = size;
self.targets = (0..2)
.map(|_| {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Menu blur target"),
size: wgpu::Extent3d {
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.format,
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let view = texture.create_view(&Default::default());
(texture, view)
})
.collect();
}
/// Blur `frame` (the swapchain texture) in place through `target`, its
/// non-sRGB view, by `radius` pixels (`menuBackgroundBlurriness`).
#[allow(clippy::too_many_arguments)]
pub fn apply(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
frame: &wgpu::Texture,
target: &wgpu::TextureView,
size: [u32; 2],
radius: f32,
) {
self.ensure(device, size);
encoder.copy_texture_to_texture(
frame.as_image_copy(),
self.targets[0].0.as_image_copy(),
wgpu::Extent3d {
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
);
for (i, dir) in PASSES.iter().enumerate() {
let data = Uniform {
size_dir: [size[0] as f32, size[1] as f32, dir[0], dir[1]],
radius: [radius, 0.0, 0.0, 0.0],
};
queue.write_buffer(&self.uniforms[i], 0, bytemuck::bytes_of(&data));
let source = &self.targets[i % 2].1;
let output = if i + 1 == PASSES.len() {
target
} else {
&self.targets[(i + 1) % 2].1
};
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Menu blur pass"),
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(source),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.uniforms[i].as_entire_binding(),
},
],
});
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: output,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Menu blur pass"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &group, &[]);
pass.draw(0..3, 0..1);
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn box_blur_shader_validates() {
let module = naga::front::wgsl::parse_str(include_str!("menu_blur.wgsl")).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
}
}
+32
View File
@@ -0,0 +1,32 @@
// Vanilla's post/box_blur.fsh: one direction of a box blur of 2·Radius + 1
// pixels, reading two pixels per linear sample.
struct Blur {
// InSize (pixels), BlurDir.
size_dir: vec4<f32>,
// Radius, unused, unused, unused.
radius: vec4<f32>,
}
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;
@group(0) @binding(2) var<uniform> blur: Blur;
struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
}
@vertex fn vs_main(@builtin(vertex_index) i: u32) -> Out {
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
var out: Out;
out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
out.uv = vec2(p.x, 1.0 - p.y);
return out;
}
@fragment fn fs_main(in: Out) -> @location(0) vec4<f32> {
let step = blur.size_dir.zw / blur.size_dir.xy;
let radius = round(blur.radius.x);
var blurred = vec4(0.0);
for (var a = -radius + 0.5; a <= radius; a += 2.0) {
blurred += textureSampleLevel(src, samp, in.uv + step * a, 0.0);
}
blurred += textureSampleLevel(src, samp, in.uv + step * radius, 0.0) / 2.0;
return blurred / (radius + 0.5);
}
+53 -7
View File
@@ -11,6 +11,8 @@ pub mod anim;
pub mod animal_brain;
pub mod aquatic;
pub mod axolotl;
pub mod bat;
pub mod bee;
pub mod body_anim;
pub mod brain;
pub mod breeze;
@@ -58,6 +60,7 @@ pub mod spawn_selection;
pub mod spawner;
pub mod spawning;
pub mod species;
pub mod strider;
pub mod sulfur_cube;
pub mod tame;
pub mod trader;
@@ -293,7 +296,7 @@ pub struct Flags {
pub climber: bool,
/// Striders stand on lava.
pub lava_walker: bool,
/// LivingEntity.omnidirectionalAirMover (bees, parrots, bats, allays).
/// LivingEntity.omnidirectionalAirMover (bees and parrots).
pub omnidirectional: bool,
pub fire_immune: bool,
/// EntityTypeTags.BURN_IN_DAYLIGHT
@@ -753,6 +756,8 @@ pub struct Extra {
pub lone: bool,
/// A breeze's or creaking's brain (`monster_brain`).
pub brain: Option<Box<monster_brain::Brain>>,
/// A bee's nectar, anger, flower and hive state.
pub bee: Option<Box<bee::Bee>>,
}
#[derive(Clone, Debug)]
pub struct Mob {
@@ -798,6 +803,9 @@ pub struct Mob {
/// update (`isUnderWater` reads it).
pub was_eye_in_water: bool,
pub no_gravity: bool,
/// `Entity.mainSupportingBlockPos`: the block it stood on after its last
/// move.
pub supporting: Option<[i32; 3]>,
/// `NoAI`: no goals and no movement.
pub no_ai: bool,
/// `Silent`.
@@ -839,6 +847,12 @@ pub enum MobEvent {
chest: [i32; 3],
open: bool,
},
/// `BeeEnterHiveGoal.start`: the bee goes into its hive (the host stores
/// its tag with `BeehiveBlockEntity.addOccupant` and discards it).
EnterHive {
mob: u32,
hive: [i32; 3],
},
/// `CopperGolem.turnToStatue`.
BecomeStatue {
mob: u32,
@@ -1174,6 +1188,8 @@ pub struct Seen {
pub player_rep: i32,
/// `isPushable` and pushed by others (`Entity.push(Entity)` moves it).
pub pushable: bool,
/// A cold strider (`Strider.isSuffocating`).
pub cold_strider: bool,
/// `MobCategory` (`monster`, `creature`, ...).
pub category: &'static str,
/// A villager's `POTENTIAL_JOB_SITE` and `MEETING_POINT`.
@@ -1248,6 +1264,7 @@ impl Mob {
_ => 0,
},
pushable: m.pushable(),
cold_strider: strider::suffocating(m),
category: m.category(),
potential_job: villager_brain::potential_job_site(m),
meeting: villager.then_some(m.extra.meeting).flatten(),
@@ -1461,6 +1478,7 @@ impl Mob {
fluids: living::Fluids::default(),
was_eye_in_water: false,
no_gravity: false,
supporting: None,
no_ai: false,
silent: false,
invulnerable_flag: false,
@@ -1707,7 +1725,7 @@ impl Mob {
/// Movement speed attribute bonus (baby zombies, sprinting modifiers).
/// MOVEMENT_SPEED including effects (speed +20%/level, slowness -15%/level).
pub fn movement_speed(&self) -> f64 {
let mut v = self.attrs.speed * self.speed_bonus();
let mut v = strider::movement_speed(self, self.attrs.speed) * self.speed_bonus();
for (e, _, amp) in &self.extra.effects {
match *e {
"minecraft:speed" => v *= 1.0 + 0.2 * f64::from(amp + 1),
@@ -1744,8 +1762,14 @@ impl Mob {
}
/// LivingEntity.getVoicePitch.
pub fn voice_pitch(&mut self) -> f32 {
(self.random.next_float() - self.random.next_float()) * 0.2
+ if self.is_baby() { 1.5 } else { 1.0 }
let pitch = (self.random.next_float() - self.random.next_float()) * 0.2
+ if self.is_baby() { 1.5 } else { 1.0 };
// Bat.getVoicePitch: a little lower.
if self.species() == Species::Bat {
pitch * 0.95
} else {
pitch
}
}
/// Mob.playSound with LivingEntity.getVoicePitch.
pub fn voice(&mut self, event: &'static str, events: &mut Vec<MobEvent>) {
@@ -1767,11 +1791,33 @@ pub fn render(
) {
render::render_single(mob, alpha, camera, uv, light, out);
}
/// A parsed `entity-models.json` document, shared while loading model batches.
/// Each lookup still constructs an independent part tree for the caller.
pub struct EntityModelDocument(Value);
impl EntityModelDocument {
pub fn load(root: &Path) -> crate::Result<Self> {
Ok(Self(serde_json::from_slice(&fs::read(
root.join("entity-models.json"),
)?)?))
}
pub fn model(&self, key: &str) -> Option<Part> {
self.0.get(key).map(|m| Part::parse("root", m))
}
pub fn keys(&self) -> impl Iterator<Item = &str> {
self.0
.as_object()
.into_iter()
.flat_map(|all| all.keys().map(String::as_str))
}
}
/// Load one baked model layer from `entity-models.json` (e.g. `minecraft:chest#main`).
/// Batch loaders should share an `EntityModelDocument` instead.
pub fn load_model(root: &Path, key: &str) -> Option<Part> {
let models: Value =
serde_json::from_slice(&fs::read(root.join("entity-models.json")).ok()?).ok()?;
models.get(key).map(|m| Part::parse("root", m))
EntityModelDocument::load(root).ok()?.model(key)
}
/// ModelPart.render: translate, rotate ZYX, scale, then children.
pub fn render_model(
+56 -2
View File
@@ -103,6 +103,9 @@ pub enum Family {
Creaking,
/// Nautili and zombie nautili.
Nautilus,
Strider,
Bat,
Bee,
}
pub fn family(s: Species) -> Family {
use Species as S;
@@ -161,6 +164,9 @@ pub fn family(s: Species) -> Family {
S::Guardian | S::ElderGuardian => Family::Guardian,
S::Warden => Family::Warden,
S::Shulker => Family::Shulker,
S::Strider => Family::Strider,
S::Bat => Family::Bat,
S::Bee => Family::Bee,
_ => Family::Generic,
}
}
@@ -215,6 +221,9 @@ pub fn register(m: &mut Mob) {
Family::Warden => super::warden::register(m),
Family::Creaking => super::creaking::register(m),
Family::Nautilus => super::nautilus::register(m),
Family::Strider => super::strider::register(m),
Family::Bat => super::bat::register(m),
Family::Bee => super::bee::register(m),
}
}
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
@@ -358,6 +367,9 @@ pub fn tick(
return false;
}
super::warden::pre_tick(m, w, events);
if m.species() == Species::Strider {
super::strider::pre_tick(m, w, events);
}
base_tick(m, w, events);
if m.species() == Species::Rabbit {
super::rabbit::base_tick(m);
@@ -389,6 +401,15 @@ pub fn tick(
// CopperGolem.tick: updateWeathering after the living tick.
super::copper_golem::update_weathering(m, w, level_random, events);
}
if m.species() == Species::Strider {
super::strider::float(m, w);
}
if m.species() == Species::Bat {
super::bat::tick(m);
}
if m.species() == Species::Bee {
super::bee::tick(m, level_random);
}
true
}
/// LivingEntity.updateSwingTime (6-tick swing duration).
@@ -555,6 +576,8 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::Axolotl if !m.fluids.in_water => "entity.axolotl.idle_air",
Species::Bat if m.extra.flag && m.random.next_int_bound(4).unwrap_or(1) != 0 => return,
Species::Allay if m.extra.main_hand.is_some() => "entity.allay.ambient_with_item",
// Strider.getAmbientSound: quiet while panicking or tempted.
Species::Strider if m.ai.panicking || m.ai.goals.is_running("Tempt") => return,
// HappyGhast: its own voice, never pitched up.
Species::HappyGhast => {
let sound = super::happy_ghast::sounds(m)[0];
@@ -842,7 +865,8 @@ fn server_ai_step(
// A creaking looked at stands still: its navigation, move, look and jump
// controls wait (CreakingPathNavigation and the Creaking*Control).
let frozen = super::creaking::is_creaking(m) && !super::creaking::can_move(m);
if !frozen {
// The bee's navigation waits while it pollinates.
if !frozen && !super::bee::pollinating(m) {
m.nav_tick(w);
}
if super::monster_brain::has_brain(m.species()) {
@@ -877,7 +901,10 @@ fn server_ai_step(
}
if !super::axolotl::is_playing_dead(m) {
m.move_control_tick(w, events);
m.look_control_tick();
// BeeLookControl: still while angry.
if !(m.species() == Species::Bee && super::bee::angry(m, w)) {
m.look_control_tick();
}
}
m.jump_control_tick();
}
@@ -901,6 +928,8 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
Species::Wither if m.alive() => super::wither::custom_server_ai_step(m, cx.w, cx.events),
// SpellcasterIllager.customServerAiStep.
Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1,
Species::Bat => super::bat::server_ai_step(m, cx.w, cx.events),
Species::Bee => super::bee::server_ai_step(m, cx),
_ => {}
}
}
@@ -926,6 +955,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::Ravager => super::ravager::ai_step(m, w, events),
Species::Wither => super::wither::ai_step(m, w, events),
Species::Allay => super::allay::ai_step(m),
Species::Bee => super::bee::ai_step(m, w),
Species::Breeze => super::breeze::ai_step(m),
Species::Sniffer => super::sniffer::ai_step(m, events),
Species::HappyGhast => super::happy_ghast::ai_step(m, w),
@@ -1162,6 +1192,17 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 {
5.0
};
}
if m.species() == Species::Strider {
return super::strider::walk_target_value(m, w, p);
}
// Bee.getWalkTargetValue: any air block.
if m.species() == Species::Bee {
return if w.facts.is_air(w.world.block(p[0], p[1], p[2])) {
10.0
} else {
0.0
};
}
// AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike.
if matches!(
m.species(),
@@ -1195,6 +1236,15 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
Species::Warden => super::warden::accepts_damage(m, source),
Species::Shulker => super::shulker::accepts(m, source),
Species::SulfurCube => super::sulfur_cube::accepts_damage(m, source, _amount),
// Bat.hurtServer: a hit wakes it.
Species::Bat => {
super::bat::hurt(m);
true
}
Species::Bee => {
super::bee::hurt(m);
true
}
Species::Enderman => super::enderman::on_damage(m, source),
Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider
if source.is_fire() =>
@@ -1232,6 +1282,9 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
if m.species() == Species::IronGolem {
return super::golem::iron_hurt_target(m, who, cx);
}
if m.species() == Species::Bee {
return super::bee::sting(m, who, cx);
}
if matches!(m.species(), Species::Hoglin | Species::Zoglin) {
return super::piglin::hoglin_hurt_target(m, who, cx);
}
@@ -1400,6 +1453,7 @@ pub fn step_sound(
match m.species() {
// Silent footsteps, or only movement events.
S::Allay
| S::Bat
| S::Bee
| S::Cod
| S::Salmon
+143
View File
@@ -0,0 +1,143 @@
//! Bats (`Bat`): hanging upside down under a solid block until a player comes
//! near, then fluttering about towards random nearby air (`customServerAiStep`),
//! and `BatModel`'s flying and resting keyframe animations. `extra.flag` is
//! `isResting`, `extra.positions[0]` the `targetPosition`; animation states:
//! flying, resting.
use super::{Mob, MobEvent, MobWorld, data::REDSTONE_CONDUCTOR, living::wrap};
use horizon_core::{
geometry::{Vec3, trig},
random::RandomSource,
};
/// `Bat(EntityType, Level)`: a new bat hangs.
pub fn register(m: &mut Mob) {
m.extra.flag = true;
}
pub fn resting(m: &Mob) -> bool {
m.extra.flag
}
/// `Bat.setResting`.
pub fn set_resting(m: &mut Mob, value: bool) {
m.extra.flag = value;
}
/// `Bat.hurtServer`: a hit wakes it.
pub fn hurt(m: &mut Mob) {
set_resting(m, false);
}
/// `levelEvent(1025)`: the take-off flutter, unless silent.
fn take_off(m: &Mob, p: [i32; 3], events: &mut Vec<MobEvent>) {
if !m.silent {
events.push(MobEvent::LevelEventSound {
sound: "entity.bat.takeoff",
at: [
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
],
volume: 0.05,
spread: 0.2,
});
}
}
/// `Bat.customServerAiStep`.
pub fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let pos = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let above = [pos[0], pos[1] + 1, pos[2]];
let conductor =
|p: [i32; 3]| w.data.state(w.world.block(p[0], p[1], p[2])).flags & REDSTONE_CONDUCTOR != 0;
if resting(m) {
if conductor(above) {
if m.random.next_int_bound(200).unwrap_or(1) == 0 {
m.head_yaw = m.random.next_int_bound(360).unwrap_or(0) as f32;
}
// getNearestPlayer(forNonCombat().range(4.0)).
if m.can_see_player(w, 4.0) {
set_resting(m, false);
take_off(m, pos, events);
}
} else {
set_resting(m, false);
take_off(m, pos, events);
}
return;
}
if let Some(&t) = m.extra.positions.first()
&& (!w.facts.is_air(w.world.block(t[0], t[1], t[2])) || t[1] <= crate::chunk::MIN_Y)
{
m.extra.positions.clear();
}
let near = |t: [i32; 3]| {
let d = |a: i32, b: f64| f64::from(a) + 0.5 - b;
let (dx, dy, dz) = (
d(t[0], m.position.x),
d(t[1], m.position.y),
d(t[2], m.position.z),
);
dx * dx + dy * dy + dz * dz < 4.0
};
let current = m.extra.positions.first().copied();
if current.is_none()
|| m.random.next_int_bound(30).unwrap_or(1) == 0
|| current.is_some_and(near)
{
let r = &mut m.random;
let mut offset = |bound: i32| r.next_int_bound(bound).unwrap_or(0);
let x = m.position.x + f64::from(offset(7)) - f64::from(offset(7));
let y = m.position.y + f64::from(offset(6)) - 2.0;
let z = m.position.z + f64::from(offset(7)) - f64::from(offset(7));
m.extra.positions.clear();
m.extra
.positions
.push([x.floor() as i32, y.floor() as i32, z.floor() as i32]);
}
let t = m.extra.positions[0];
let dx = f64::from(t[0]) + 0.5 - m.position.x;
let dy = f64::from(t[1]) + 0.1 - m.position.y;
let dz = f64::from(t[2]) + 0.5 - m.position.z;
let v = m.velocity;
let tenth = f64::from(0.1_f32);
let v = Vec3::new(
v.x + (signum(dx) * 0.5 - v.x) * tenth,
v.y + (signum(dy) * f64::from(0.7_f32) - v.y) * tenth,
v.z + (signum(dz) * 0.5 - v.z) * tenth,
);
m.velocity = v;
let y_rot = trig::atan2_degrees(v.z, v.x) - 90.0;
let diff = wrap(y_rot - m.yaw);
m.ai.zza = 0.5;
m.yaw += diff;
if m.random.next_int_bound(100).unwrap_or(1) == 0 && conductor(above) {
set_resting(m, true);
}
}
/// `Math.signum`: zero stays zero (Rust's `signum` gives 1).
fn signum(v: f64) -> f64 {
if v == 0.0 || v.is_nan() {
v
} else {
v.signum()
}
}
/// `Bat.tick` after `super.tick()`: a hanging bat stays put, hooked to the
/// block above; a flying one loses 40% of its vertical speed. Then
/// `setupAnimationStates`.
pub fn tick(m: &mut Mob) {
if resting(m) {
m.velocity = Vec3::ZERO;
m.position.y = m.position.y.floor() + 1.0 - f64::from(m.height());
} else {
m.velocity.y *= 0.6;
}
let age = m.age as f32;
if resting(m) {
m.anim.states[0].stop();
m.anim.states[1].start_if_stopped(age);
} else {
m.anim.states[1].stop();
m.anim.states[0].start_if_stopped(age);
}
}
File diff suppressed because it is too large Load Diff
+7 -4
View File
@@ -993,10 +993,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
p,
s,
&Bee {
has_stinger: true,
on_ground: m.on_ground,
angry: m.extra.anger > 0,
roll_amount: 0.0,
has_stinger: !super::bee::has_stung(m),
on_ground: m.on_ground && m.velocity.length_squared() < 1.0e-7,
// The anger end time is cleared the tick after it passes.
angry: super::bee::get(m).is_some_and(|b| b.anger_end > 0),
// Bee.getRollAmount(partialTick).
roll_amount: super::bee::get(m)
.map_or(0.0, |b| b.roll_o + (b.roll - b.roll_o) * s.partial),
},
),
Species::Bat => bat(p, s, m.extra.flag, &st[0], &st[1], a),
+3 -1
View File
@@ -167,7 +167,9 @@ impl Mob {
let sd = (xd * xd + zd * zd).sqrt();
if yd.abs() > EPSILON || sd.abs() > EPSILON {
let x_rot = -trig::atan2_degrees(yd, sd);
self.head_pitch = rotlerp(self.head_pitch, x_rot, max_turn);
// Entity.setXRot clamps: a pitch rotlerp wraps to 359 becomes 90.
self.head_pitch =
(rotlerp(self.head_pitch, x_rot, max_turn) % 360.0).clamp(-90.0, 90.0);
self.ai.yya = if yd > 0.0 { speed } else { -speed };
}
} else {
+134 -21
View File
@@ -174,6 +174,26 @@ impl GoalSelector {
// --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) -------
/// RandomPos.moveUpToAboveSolid: out of the solid blocks, then up to
/// `above` more blocks of air.
fn move_up_to_above_solid(w: &MobWorld, mut p: [i32; 3], above: i32) -> [i32; 3] {
if !w.solid(p[0], p[1], p[2]) {
return p;
}
p[1] += 1;
while p[1] <= 319 && w.solid(p[0], p[1], p[2]) {
p[1] += 1;
}
let first = p[1];
while p[1] <= 319 && p[1] - first < above {
p[1] += 1;
if w.solid(p[0], p[1], p[2]) {
p[1] -= 1;
break;
}
}
p
}
/// `Mob.isWithinHome(BlockPos)`.
pub fn within_home(c: [i32; 3], r: i32, p: [i32; 3]) -> bool {
let d = |i: usize| i64::from(c[i] - p[i]);
@@ -371,29 +391,89 @@ impl Mob {
xd: f64,
zd: f64,
) -> Option<[f64; 3]> {
// Every caller passes `(float) (Math.PI / 2)`.
let max_rad = f64::from(std::f32::consts::FRAC_PI_2);
self.pick_best(w, |m| {
let d = m.random_direction_within(
0.0,
f64::from(h),
v,
fly_height,
xd,
zd,
// Every caller passes `(float) (Math.PI / 2)`.
f64::from(std::f32::consts::FRAC_PI_2),
)?;
let mut p = m.toward(f64::from(h), d);
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || m.restricted(f64::from(h), p) {
m.air_and_water_pos(w, h, v, fly_height, xd, zd, max_rad)
})
}
/// AirAndWaterRandomPos.generateRandomPos.
#[allow(clippy::too_many_arguments)]
fn air_and_water_pos(
&mut self,
w: &MobWorld,
h: i32,
v: i32,
fly_height: i32,
xd: f64,
zd: f64,
max_rad: f64,
) -> Option<[i32; 3]> {
let d = self.random_direction_within(0.0, f64::from(h), v, fly_height, xd, zd, max_rad)?;
let mut p = self.toward(f64::from(h), d);
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || self.restricted(f64::from(h), p) {
return None;
}
// RandomPos.moveUpOutOfSolid
if w.solid(p[0], p[1], p[2]) {
p[1] += 1;
while p[1] <= 319 && w.solid(p[0], p[1], p[2]) {
p[1] += 1;
}
}
(self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p)
}
/// AirRandomPos.getPosTowards: an AirAndWaterRandomPos towards a point,
/// out of water.
pub fn air_random_pos_towards(
&mut self,
w: &MobWorld,
h: i32,
v: i32,
fly_height: i32,
to: [f64; 3],
max_rad: f64,
) -> Option<[f64; 3]> {
let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z);
self.pick_best(w, |m| {
let p = m.air_and_water_pos(w, h, v, fly_height, xd, zd, max_rad)?;
(w.fluid(p[0], p[1], p[2]) != crate::blocks::Fluid::Water).then_some(p)
})
}
/// HoverRandomPos.getPos: a stable spot within the radians of a
/// direction, raised a random `hover_min..=hover_max` blocks above the
/// solid ground it is in, out of water and free of path maluses.
#[allow(clippy::too_many_arguments)]
pub fn hover_random_pos(
&mut self,
w: &MobWorld,
h: i32,
v: i32,
xd: f64,
zd: f64,
max_rad: f64,
hover_max: i32,
hover_min: i32,
) -> Option<[f64; 3]> {
self.pick_best(w, |m| {
let d = m.random_direction_within(0.0, f64::from(h), v, 0, xd, zd, max_rad)?;
// LandRandomPos.generateRandomPosTowardDirection
let p = m.toward(f64::from(h), d);
if p[1] < crate::chunk::MIN_Y
|| p[1] >= 320
|| m.restricted(f64::from(h), p)
|| !m.stable_destination(w, p)
{
return None;
}
// RandomPos.moveUpOutOfSolid
if w.solid(p[0], p[1], p[2]) {
p[1] += 1;
while p[1] <= 319 && w.solid(p[0], p[1], p[2]) {
p[1] += 1;
}
}
(m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p)
let above = m
.random
.next_int_bound(hover_max - hover_min + 1)
.unwrap_or(0)
+ hover_min;
let p = move_up_to_above_solid(w, p, above);
let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water;
(!water && m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p)
})
}
/// LandRandomPos.getPos
@@ -796,6 +876,8 @@ pub struct LookAtPlayer {
pub only_horizontal: bool,
/// `LookAtPlayerGoal(Mob.class, ...)`: the nearest mob, not the player.
pub mobs: bool,
/// `LookAtPlayerGoal(Strider.class, ...)`: only mobs of this species.
pub only: Option<Species>,
/// InteractGoal: LOOK and MOVE.
pub interact: bool,
look_at: Option<Who>,
@@ -808,6 +890,7 @@ impl LookAtPlayer {
probability: 0.02,
only_horizontal: false,
mobs: false,
only: None,
interact: false,
look_at: None,
look_time: 0,
@@ -820,6 +903,13 @@ impl LookAtPlayer {
..Self::new(range)
}
}
/// `LookAtPlayerGoal(this, <species class>, range)`.
pub fn species(species: Species, range: f32) -> Self {
Self {
only: Some(species),
..Self::mobs(range)
}
}
/// `InteractGoal(this, Player.class, range, probability)`.
pub fn interact(range: f32, probability: f32) -> Self {
Self {
@@ -873,12 +963,13 @@ impl Goal for LookAtPlayer {
}
// level.getNearestEntity(mobs in the box inflated by (range, 3, range)).
let area = m.bounds().inflate(Vec3::new(range, 3.0, range));
let id = m.id;
let (id, only) = (m.id, self.only);
let at = Vec3::new(m.position.x, m.eye_y(), m.position.z);
let candidates: Vec<(u32, Vec3)> =
cx.w.others
.iter()
.filter(|s| s.id != id && s.alive && s.bounds.intersects(area))
.filter(|s| only.is_none_or(|o| s.species == o))
.map(|s| (s.id, s.position))
.collect();
let mut best: Option<(u32, f64)> = None;
@@ -1329,6 +1420,9 @@ pub struct HurtByTarget {
pub alert_except: Vec<Species>,
/// Attackers ignored (e.g. zombified piglins ignore other zombified piglins).
pub ignore: Vec<Species>,
/// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others
/// only when the attacker is in sight.
pub bee: bool,
timestamp: i32,
st: TargetState,
}
@@ -1338,6 +1432,7 @@ impl HurtByTarget {
alert: false,
alert_except: vec![],
ignore: vec![],
bee: false,
timestamp: 0,
st: TargetState {
unseen_memory: 300,
@@ -1353,6 +1448,10 @@ impl HurtByTarget {
self.ignore = s.to_vec();
self
}
pub fn bee(mut self) -> Self {
self.bee = true;
self
}
}
impl Default for HurtByTarget {
fn default() -> Self {
@@ -1361,6 +1460,13 @@ impl Default for HurtByTarget {
}
impl Goal for HurtByTarget {
goal_clone!();
fn name(&self) -> &'static str {
if self.bee {
"BeeHurtByOtherGoal"
} else {
"HurtByTarget"
}
}
fn flags(&self) -> u8 {
TARGET
}
@@ -1385,6 +1491,9 @@ impl Goal for HurtByTarget {
t.alive && t.can_be_seen_as_enemy && !(t.is_player && t.creative)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if self.bee && !super::bee::angry(m, cx.w) {
return false;
}
target_continue(&mut self.st, true, m, cx)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
@@ -1415,6 +1524,10 @@ impl Goal for HurtByTarget {
.filter(|s| Who::Mob(s.id) != by)
.map(|s| s.id)
.collect();
// Bee.BeeHurtByOtherGoal.alertOther: only with the attacker in sight.
if self.bee && !ids.is_empty() && !m.sees(cx.w, by) {
return;
}
for other in ids {
cx.events.push(MobEvent::SetTarget {
mob: other,
+59 -23
View File
@@ -3,7 +3,10 @@
//! fluid slowdown and falling adjustment), fluid immersion heights, fall
//! damage, fire and the walk animation.
use super::{Mob, MobEvent, MobWorld};
use crate::{blocks::Fluid, collisions::SceneCollisions};
use crate::{
blocks::Fluid,
collisions::{PowderSnowSubject, SceneCollisions},
};
use horizon_core::{
geometry::{Aabb, Vec3, trig},
random::RandomSource,
@@ -313,7 +316,11 @@ impl Mob {
let mut scene = SceneCollisions {
world: w.world,
binding: w.collision,
subject: None,
subject: self.kind.flags.lava_walker.then(|| PowderSnowSubject {
fall_distance: self.fall_distance,
lava_walker: true,
..Default::default()
}),
};
let moved = scene
.resolve(self.bounds(), wanted, step, self.on_ground)
@@ -338,23 +345,12 @@ impl Mob {
let vertical = wanted.y != moved.y;
self.vertical_collision_below = vertical && wanted.y < 0.0;
self.on_ground = self.vertical_collision_below;
// LivingEntity.checkFallDamage refreshes the fluid state out of water
// (touching water resets the fall).
if !self.fluids.in_water {
self.fluids = w.fluids(self.bounds(), self.eye_y());
if self.fluids.in_water {
self.fall_distance = 0.0;
}
}
// Entity.checkFallDamage
if !self.fluids.in_water && moved.y < 0.0 {
self.fall_distance -= f64::from(moved.y as f32);
}
if self.on_ground {
if self.fall_distance > 0.0 {
self.cause_fall_damage(events);
}
// Strider.checkFallDamage: lava breaks any fall, and the fluid state
// waits for the next baseTick; Bat and Bee.checkFallDamage do nothing.
if self.kind.flags.lava_walker && self.fluids.in_lava {
self.fall_distance = 0.0;
} else if !matches!(self.kind.species, super::Species::Bat | super::Species::Bee) {
self.check_fall_damage(w, moved, events);
}
// restituteMovementAfterCollisions with no bounciness: the colliding
// components become (signed) zero.
@@ -370,8 +366,29 @@ impl Mob {
self.velocity.y = (0.0 - v.y) * 1.0 * 0.0;
}
}
// Entity.checkSupportingBlock
self.supporting = self.supporting_block(w, moved);
self.movement_emission(w, moved, events);
}
/// LivingEntity.checkFallDamage: the fluid state refreshed out of water
/// (touching water resets the fall), then Entity.checkFallDamage.
fn check_fall_damage(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec<MobEvent>) {
if !self.fluids.in_water {
self.fluids = w.fluids(self.bounds(), self.eye_y());
if self.fluids.in_water {
self.fall_distance = 0.0;
}
}
if !self.fluids.in_water && moved.y < 0.0 {
self.fall_distance -= f64::from(moved.y as f32);
}
if self.on_ground {
if self.fall_distance > 0.0 {
self.cause_fall_damage(events);
}
self.fall_distance = 0.0;
}
}
/// Entity.applyMovementEmissionAndPlaySound: walked distance, footsteps
/// and swimming sounds.
fn movement_emission(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec<MobEvent>) {
@@ -381,7 +398,7 @@ impl Mob {
let full = (moved.length() * f64::from(0.6_f32)) as f32;
let horizontal =
((moved.x * moved.x + moved.z * moved.z).sqrt() * f64::from(0.6_f32)) as f32;
let supporting = self.supporting_block(w, moved);
let supporting = self.supporting;
let on = self.supported_on_pos(w, supporting, 1.0e-5);
let state = w.world.block(on[0], on[1], on[2]);
let climbable = w.facts.get(state).name.as_ref() == "minecraft:powder_snow"
@@ -439,11 +456,13 @@ impl Mob {
}
}
/// `Entity.nextStep`: the next whole metre walked; a warden's steps come
/// every 0.55.
/// every 0.55, a strider's every 0.6.
fn next_step(&self) -> f32 {
let walked = self.ai.steps.move_dist;
if self.kind.species == super::Species::Warden {
walked + 0.55
} else if self.kind.species == super::Species::Strider {
walked + 0.6
} else {
(walked as i32).wrapping_add(1) as f32
}
@@ -482,6 +501,11 @@ impl Mob {
w.supporting_block(shifted, self.position)
})
}
/// `Entity.getBlockStateOnLegacy`'s position: 0.2 below the feet, or the
/// supporting block.
pub(super) fn block_on_legacy(&self, w: &MobWorld) -> [i32; 3] {
self.supported_on_pos(w, self.supporting, 0.2)
}
/// `Entity.getOnPos(offset)` with a supporting block: its column (its
/// own position for fences, walls and gates up to half a block down).
fn supported_on_pos(
@@ -575,7 +599,13 @@ impl Mob {
if self.kind.flags.flying {
return self.travel_flying(w, input, events);
}
let stands_on_fluid = self.kind.flags.lava_walker && self.fluids.in_lava;
// shouldTravelInFluid: not where the fluid at its feet holds it up.
let (x, y, z) = (
self.position.x.floor() as i32,
self.position.y.floor() as i32,
self.position.z.floor() as i32,
);
let stands_on_fluid = self.kind.flags.lava_walker && w.fluid(x, y, z) == Fluid::Lava;
if self.is_in_liquid() && self.affected_by_fluids() && !stands_on_fluid {
self.travel_in_fluid(w, input, events);
} else {
@@ -752,9 +782,15 @@ impl Mob {
self.ai.no_jump_delay = 0;
}
}
/// Mob.jumpInLiquid: floaters rise 0.04 per tick, others 0.3.
/// Mob.jumpInLiquid: floaters rise 0.04 per tick, others 0.3; bees 0.01.
fn jump_in_liquid(&mut self) {
self.velocity.y += if self.ai.nav.can_float { 0.04 } else { 0.3 };
self.velocity.y += if self.species() == super::Species::Bee {
0.01
} else if self.ai.nav.can_float {
0.04
} else {
0.3
};
}
pub fn jump_from_ground(&mut self, w: &MobWorld) {
if self.species() == super::Species::Rabbit {
+7
View File
@@ -562,6 +562,13 @@ impl Mob {
}
/// PathNavigation.isStableDestination for the mob's navigation.
pub fn stable_destination(&self, w: &MobWorld, p: [i32; 3]) -> bool {
if self.species() == super::Species::Bee {
return super::bee::stable_destination(w, p);
}
// StriderPathNavigation: lava too.
if self.kind.flags.lava_walker && w.block_name(p[0], p[1], p[2]) == "minecraft:lava" {
return true;
}
match self.ai.nav.kind {
NavKind::Ground | NavKind::WallClimber => {
w.facts

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