Merge upstream/main into fix/iron-golem-toss

Upstream's UUID bridge (#10304) now writes a mob anger target's UUID
through mob_to_nbt's uuid_of. The branch keeps its two additions on top:
a target read from the save that is not in the world keeps the loaded
UUID, and the loaded angry_at goes once the anger is over.

A mob only gets its UUID when it is first saved, so an anger target
not saved yet came out with no angry_at (wolves too). mob_tree_nbt now
gives a target that is still in the world its UUID first; the new
anger_at_a_mob_not_saved_yet_names_it test failed without that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Evrim CicekandClaude Opus 5.5 committed 2026-11-06 14:37:40 +03:00
commit d1ce5ddfd9
961 files changed
+83448 -7925

No files matched your search

+2 -1
View File
@@ -276,7 +276,7 @@ jobs:
run: |
changed=$(git diff --name-only "$(git merge-base "$BASE_SHA" HEAD)" HEAD)
harness=$(grep -E '^(tools/test_[a-z0-9_]+_parity\.py|tools/(parity[a-z_]*|lab)\.py|tools/parity_hosts\.json|mods/horizon/src/test/|crates/[^/]+/examples/|crates/horizon-client/src/game/[a-z_]*(fixture|harness)\.rs|\.github/workflows/parity[a-z-]*\.yml)' <<< "$changed" || true)
if [ -n "$harness" ] || [[ " $LABELS " == *" run-parity "* ]]; then
if [ -n "$harness" ] || [[ " $LABELS " == *" run-parity "* ]] || [[ " $LABELS " == *" frame-identity "* ]]; then
echo "run=true" >> "$GITHUB_OUTPUT"
echo "The pull request runs its harnesses: ${harness:-label run-parity}"
else
@@ -291,6 +291,7 @@ jobs:
base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }}
full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
frame_identity: ${{ contains(github.event.pull_request.labels.*.name, 'frame-identity') }}
# Horizon never downloads the game. These jobs need a self-hosted Linux runner
# (label horizon-game) holding the maintainer's own copy: the official launcher's
# game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
+12
View File
@@ -20,6 +20,12 @@ on:
busy the job waits for it.
type: boolean
default: false
frame_identity:
description: >-
The pull request carries the frame-identity label: it must leave the picture alone (HDR, shader packs), so
the frame_identity harness, which no automatic selection picks, runs too.
type: boolean
default: false
permissions:
contents: read
env:
@@ -87,6 +93,12 @@ jobs:
PARITY_HOSTS: ''
BASE_SHA: ${{ steps.merge.outputs.base }}
run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner
- name: The pictures this change must leave alone
if: ${{ !cancelled() && inputs.frame_identity }}
env:
PARITY_HOSTS: ''
BASE_SHA: ${{ steps.merge.outputs.base }}
run: python3 tools/parity.py frame_identity --timeout 2400
- name: Logs of the failed harnesses
if: failure()
uses: actions/upload-artifact@v7
+1
View File
@@ -27,3 +27,4 @@ jobs:
base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }}
full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
frame_identity: ${{ contains(github.event.pull_request.labels.*.name, 'frame-identity') }}
+1
View File
@@ -35,6 +35,7 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
- **No hardcoded user-facing strings.** Keep UI translation-ready from the start. In the launcher (`launcher/`), wrap visible text with `tr("...")` or `trf("... {arg} ...", &[("arg", &val)])` from `crate::i18n` instead of raw string literals or `format!`. In the game, use translation keys (`Text::tr`, `lang::get`), never hardcoded English strings.
- **Claim before you start**: comment `/claim` on the issue (no issue yet: open one, then claim it). An assigned
issue is taken: pick another. `/unclaim` when you stop; a claim with no open PR linking it is released after 5 days.
- **Controllers reach what registers.** Draw controls with a registering helper (`ui::button`, `settings_shell::foot_button`); `graphics_style::button` and `screen_draw::button` only paint, and registering one part of a screen ends its crosshair, so register all of it.
## Crates
Generated
+247
View File
@@ -147,6 +147,12 @@ dependencies = [
"x11rb",
]
[[package]]
name = "arcstr"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d"
[[package]]
name = "arrayref"
version = "0.3.9"
@@ -303,6 +309,21 @@ dependencies = [
"objc2 0.6.5",
]
[[package]]
name = "btoi"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b5ab9db53bcda568284df0fd39f6eac24ad6f7ba7ff1168b9e76eba6576b976"
dependencies = [
"num-traits",
]
[[package]]
name = "bufstream"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8"
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -329,6 +350,12 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
@@ -651,6 +678,15 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-queue"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
@@ -768,6 +804,17 @@ version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "derive_utils"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc05a5d33db20c784f873e84934ad94bb209a090987ac5f62fede2c178234f23"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "des"
version = "0.8.1"
@@ -1318,6 +1365,7 @@ dependencies = [
"ab_glyph",
"bytemuck",
"chrono",
"dunce",
"flate2",
"fs4",
"gilrs",
@@ -1363,6 +1411,7 @@ dependencies = [
"serde_json",
"sha1",
"sha2",
"toml",
"unicode-bidi",
"ureq",
"wgpu",
@@ -1412,6 +1461,7 @@ dependencies = [
"horizon-client-render",
"horizon-command",
"horizon-core",
"horizon-cosmetics",
"horizon-dualsense",
"horizon-friends",
"horizon-hdr",
@@ -1606,6 +1656,16 @@ dependencies = [
"serde_json",
]
[[package]]
name = "horizon-mod-deps"
version = "0.1.0"
dependencies = [
"mysql",
"redis",
"rusty-opus",
"tungstenite",
]
[[package]]
name = "horizon-mods"
version = "0.1.0"
@@ -1716,6 +1776,7 @@ dependencies = [
"horizon-mcp",
"horizon-release-sign",
"horizon-server-files",
"horizon-world",
"libc",
"p12-keystore",
"png",
@@ -2000,6 +2061,15 @@ dependencies = [
"generic-array",
]
[[package]]
name = "io-enum"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f859dc81e05e585e93cfc84dffa4fd068d0651ca229c51bca6101c056b63b93a"
dependencies = [
"derive_utils",
]
[[package]]
name = "ipconfig"
version = "0.3.4"
@@ -2247,6 +2317,12 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lru"
version = "0.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"
[[package]]
name = "lz4_flex"
version = "0.14.0"
@@ -2336,6 +2412,59 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "mysql"
version = "27.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "090068bc0a24762663338da78414148333d1ee246a7293c10a517ddf1548b291"
dependencies = [
"bufstream",
"bytes",
"crossbeam-queue",
"crossbeam-utils",
"flate2",
"io-enum",
"libc",
"lru",
"mysql_common",
"named_pipe",
"pem",
"percent-encoding",
"rustls",
"rustls-pemfile",
"socket2 0.6.5",
"twox-hash",
"url",
"webpki",
"webpki-roots 1.0.10",
]
[[package]]
name = "mysql_common"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20e7f6a15265801679ddf1ddb38fd74b4555a677a78378d4561fbe5f0b1d4d72"
dependencies = [
"base64",
"bitflags 2.13.2",
"btoi",
"byteorder",
"bytes",
"crc32fast",
"flate2",
"getrandom 0.3.4",
"num-bigint",
"num-traits",
"regex",
"saturating",
"serde",
"serde_json",
"sha1",
"sha2",
"thiserror 2.0.21",
"uuid",
]
[[package]]
name = "naga"
version = "30.0.1"
@@ -2373,6 +2502,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "named_pipe"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad9c443cce91fc3e12f017290db75dde490d685cdaaf508d7159d7cf41f0eb2b"
dependencies = [
"winapi",
]
[[package]]
name = "ndk"
version = "0.9.0"
@@ -2972,6 +3110,16 @@ dependencies = [
"hmac",
]
[[package]]
name = "pem"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
dependencies = [
"base64",
"serde_core",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
@@ -3299,6 +3447,22 @@ dependencies = [
"yasna",
]
[[package]]
name = "redis"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db7f3d75b5a3301746bff39a767bf4c5c42506b08513527308b3875bfb64a031"
dependencies = [
"arcstr",
"combine",
"itoa",
"percent-encoding",
"ryu",
"socket2 0.6.5",
"url",
"xxhash-rust",
]
[[package]]
name = "redox_syscall"
version = "0.4.1"
@@ -3440,6 +3604,15 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rustls-pemfile"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
@@ -3466,6 +3639,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "rusty-opus"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46604e6809c06441da1cfdde1f0cc25a4f2bf42c7d005aa387c2875c02d78762"
[[package]]
name = "ruzstd"
version = "0.9.1"
@@ -3475,6 +3654,12 @@ dependencies = [
"twox-hash",
]
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "salsa20"
version = "0.10.2"
@@ -3493,6 +3678,12 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "saturating"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71"
[[package]]
name = "scoped-tls"
version = "1.0.1"
@@ -3712,6 +3903,17 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "socks"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0c3dbbd9ae980613c6dd8e28a9407b50509d3803b57624d5dfe8315218cd58b"
dependencies = [
"byteorder",
"libc",
"winapi",
]
[[package]]
name = "spake2"
version = "0.4.0"
@@ -4090,6 +4292,18 @@ version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
[[package]]
name = "tungstenite"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22"
dependencies = [
"bytes",
"log",
"rand",
"thiserror 2.0.21",
]
[[package]]
name = "twox-hash"
version = "2.1.5"
@@ -4165,6 +4379,7 @@ dependencies = [
"once_cell",
"rustls",
"rustls-pki-types",
"socks",
"url",
"webpki-roots 0.26.11",
]
@@ -4432,6 +4647,16 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webpki"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed63aea5ce73d0ff405984102c42de94fc55a6b75765d621c65262469b3c9b53"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
@@ -4627,6 +4852,22 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -4636,6 +4877,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows"
version = "0.54.0"
+1
View File
@@ -39,6 +39,7 @@ members = [
"crates/horizon-optifine",
"crates/horizon-shader-api",
"crates/horizon-release-sign",
"crates/horizon-mod-deps",
"xtask",
]
resolver = "2"
+5
View File
@@ -184,6 +184,11 @@ ported to Rust; the pack_uniforms.rs functions drop JOML's property flags, and
`pack_projection` works the formula in doubles. The copyright line and license notice also head
both files.
`camera.rs` also adapts `Quaternionf.rotationX`, `rotationY` and `rotationZ`,
`Matrix4f.rotateAffine` and `Vector4f.mulAffine` (`joml::Quat::rotation_x`/`_y`/`_z`,
`joml::Mat4::rotate_affine`, `transform_affine`), for the sky's positions shader packs read.
Changes: ported to Rust; `rotate_affine` keeps only the affine case.
```
The MIT License
+5
View File
@@ -0,0 +1,5 @@
# `keys.contains(&KeyCode::ShiftLeft)` reads a mapping by its default key: ask by `Action`, so the
# mapping is named and every device that can hold it counts.
disallowed-methods = [
{ path = "horizon_client_input::held::HeldKeys::contains", reason = "use `held(Action::..)`, or `raw` for a key that is no mapping's default", allow-invalid = true },
]
+1 -1
View File
@@ -394,7 +394,7 @@ pub fn apply_deprecated(map: &mut HashMap<String, String>, json: &[u8]) {
/// characters in strings, `=` or `=>` and `;`), which vanilla reads lang files with (expected
/// from `Language.loadFromJson`, Gson). A file that is not JSON even so adds nothing; a value
/// that is not a string, number or boolean (`GsonHelper.convertToString`) ends the file there.
fn read_lang_file(bytes: &[u8], map: &mut HashMap<String, String>) {
pub fn read_lang_file(bytes: &[u8], map: &mut HashMap<String, String>) {
use horizon_world::datafix::json::{Json, parse_lenient};
if let Ok(entries) = serde_json::from_slice::<HashMap<String, String>>(bytes) {
map.extend(entries);
+1 -1
View File
@@ -81,7 +81,7 @@ fn elements(tag: &Tag) -> Option<Vec<Tag>> {
}
/// `DoubleTag.intValue` / `FloatTag.intValue` floor before the i32 conversion;
/// integral tags use their intValue narrowing. Byte arrays then keep the low byte.
fn int_value(t: &Tag) -> Option<i32> {
pub fn int_value(t: &Tag) -> Option<i32> {
Some(match t {
Tag::Byte(v) => i32::from(*v),
Tag::Short(v) => i32::from(*v),
+146
View File
@@ -0,0 +1,146 @@
//! Every input the game names: vanilla's key mappings (`Options.keyMappings`) and Horizon's
//! pad-only actions. Held state is asked by [`Action`] ([`crate::held::HeldKeys::held`]), not by a
//! key: code that wants a mapping says which one, and every device that can hold it counts.
use winit::keyboard::KeyCode;
macro_rules! actions {
($($variant:ident, $name:literal, $key:expr;)*) => {
/// A key mapping, or a pad-only action.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Action {
$($variant,)*
}
impl Action {
/// In `Options.keyMappings` order, then Horizon's own mappings, the pad-only actions last.
pub const ALL: &[Action] = &[$(Action::$variant,)*];
/// The saved name: vanilla's for a mapping, `pad.*` for Horizon's own.
pub fn name(self) -> &'static str {
match self {
$(Action::$variant => $name,)*
}
}
/// The default key the game's held state keeps this action under. `None` for what
/// isn't held as a key there: a mouse mapping, one with no default, a pad-only action,
/// and the debug keys, which act on the physical key (`debug_keys.rs`) and whose
/// defaults are other mappings' keys.
pub fn key(self) -> Option<KeyCode> {
match self {
$(Action::$variant => $key,)*
}
}
}
};
}
actions! {
Attack, "key.attack", None;
Use, "key.use", None;
Forward, "key.forward", Some(KeyCode::KeyW);
Left, "key.left", Some(KeyCode::KeyA);
Back, "key.back", Some(KeyCode::KeyS);
Right, "key.right", Some(KeyCode::KeyD);
Jump, "key.jump", Some(KeyCode::Space);
Sneak, "key.sneak", Some(KeyCode::ShiftLeft);
Sprint, "key.sprint", Some(KeyCode::ControlLeft);
Drop, "key.drop", Some(KeyCode::KeyQ);
Inventory, "key.inventory", Some(KeyCode::KeyE);
Chat, "key.chat", Some(KeyCode::KeyT);
Playerlist, "key.playerlist", Some(KeyCode::Tab);
PickItem, "key.pickItem", None;
Command, "key.command", Some(KeyCode::Slash);
Friends, "key.friends", Some(KeyCode::KeyO);
SocialInteractions, "key.socialInteractions", Some(KeyCode::KeyP);
ToggleGui, "key.toggleGui", Some(KeyCode::F1);
ToggleSpectatorShaderEffects, "key.toggleSpectatorShaderEffects", Some(KeyCode::F4);
Screenshot, "key.screenshot", Some(KeyCode::F2);
TogglePerspective, "key.togglePerspective", Some(KeyCode::F5);
SmoothCamera, "key.smoothCamera", None;
Fullscreen, "key.fullscreen", Some(KeyCode::F11);
SpectatorOutlines, "key.spectatorOutlines", None;
SpectatorHotbar, "key.spectatorHotbar", None;
SwapOffhand, "key.swapOffhand", Some(KeyCode::KeyF);
SaveToolbarActivator, "key.saveToolbarActivator", Some(KeyCode::KeyC);
LoadToolbarActivator, "key.loadToolbarActivator", Some(KeyCode::KeyX);
Advancements, "key.advancements", Some(KeyCode::KeyL);
QuickActions, "key.quickActions", Some(KeyCode::KeyG);
DebugOverlay, "key.debug.overlay", None;
DebugModifier, "key.debug.modifier", None;
Hotbar1, "key.hotbar.1", Some(KeyCode::Digit1);
Hotbar2, "key.hotbar.2", Some(KeyCode::Digit2);
Hotbar3, "key.hotbar.3", Some(KeyCode::Digit3);
Hotbar4, "key.hotbar.4", Some(KeyCode::Digit4);
Hotbar5, "key.hotbar.5", Some(KeyCode::Digit5);
Hotbar6, "key.hotbar.6", Some(KeyCode::Digit6);
Hotbar7, "key.hotbar.7", Some(KeyCode::Digit7);
Hotbar8, "key.hotbar.8", Some(KeyCode::Digit8);
Hotbar9, "key.hotbar.9", Some(KeyCode::Digit9);
DebugReloadChunk, "key.debug.reloadChunk", None;
DebugShowHitboxes, "key.debug.showHitboxes", None;
DebugClearChat, "key.debug.clearChat", None;
DebugCrash, "key.debug.crash", None;
DebugShowChunkBorders, "key.debug.showChunkBorders", None;
DebugShowAdvancedTooltips, "key.debug.showAdvancedTooltips", None;
DebugCopyRecreateCommand, "key.debug.copyRecreateCommand", None;
DebugSpectate, "key.debug.spectate", None;
DebugSwitchGameMode, "key.debug.switchGameMode", None;
DebugDebugOptions, "key.debug.debugOptions", None;
DebugFocusPause, "key.debug.focusPause", None;
DebugDumpDynamicTextures, "key.debug.dumpDynamicTextures", None;
DebugReloadResourcePacks, "key.debug.reloadResourcePacks", None;
DebugProfiling, "key.debug.profiling", None;
DebugCopyLocation, "key.debug.copyLocation", None;
DebugDumpVersion, "key.debug.dumpVersion", None;
DebugProfilingChart, "key.debug.profilingChart", None;
DebugFpsCharts, "key.debug.fpsCharts", None;
DebugNetworkCharts, "key.debug.networkCharts", None;
DebugLightmapTexture, "key.debug.lightmapTexture", None;
DebugImprovedTransparency, "key.debug.improvedTransparency", None;
Emote, "key.emote", Some(KeyCode::KeyB);
HotbarPrevious, "pad.hotbarPrevious", None;
HotbarNext, "pad.hotbarNext", None;
}
impl Action {
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.iter().copied().find(|a| a.name() == name)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::keybinds::{self, HORIZON_MAPPINGS, KeyBinds, MAPPINGS, all_mappings};
#[test]
fn every_mapping_is_an_action_in_order() {
let names: Vec<&str> = Action::ALL.iter().map(|a| a.name()).collect();
let mappings: Vec<&str> = MAPPINGS.iter().map(|m| m.0).collect();
assert_eq!(names[..mappings.len()], mappings[..]);
let horizon: Vec<&str> = HORIZON_MAPPINGS.iter().map(|m| m.0).collect();
let end = mappings.len() + horizon.len();
assert_eq!(names[mappings.len()..end], horizon[..]);
for action in &names[end..] {
assert!(action.starts_with("pad."), "{action}");
}
}
#[test]
fn an_actions_key_is_its_mappings_default_key() {
for (name, _, category) in all_mappings() {
let action = Action::parse(name).unwrap();
let want = if *category == "debug" {
None
} else {
keybinds::key_code(KeyBinds::default_of(name))
};
assert_eq!(action.key(), want, "{name}");
}
}
#[test]
fn every_bindable_action_is_an_action() {
for (name, _) in crate::gamepad::ACTIONS {
assert!(Action::parse(name).is_some(), "{name}");
}
}
}
+293 -35
View File
@@ -1,11 +1,17 @@
//! Controllers: Horizon's own feature (vanilla 26.3 has no gamepad input).
//! The default layout is Bedrock Edition's; see docs/controllers.md.
//! Its default buttons are Horizon's own; analog walking and toggle sneak follow Bedrock Edition on
//! consoles. See docs/controllers.md.
//!
//! This module is the backend-free part: positional buttons, the action
//! bindings, deadzones and the look curve, button edges from successive pad
//! states, and `horizon-controller.txt`, kept next to `options.txt` so that
//! file stays exactly vanilla's. The game reads the pads with gilrs.
use std::{collections::BTreeMap, fs, path::Path};
use std::{
collections::BTreeMap,
fs,
path::Path,
time::{Duration, Instant},
};
pub const FILE: &str = "horizon-controller.txt";
@@ -296,7 +302,7 @@ pub const HOTBAR_NEXT: &str = "pad.hotbarNext";
/// always pause / back and isn't listed.
pub const ACTIONS: &[(&str, Option<Button>)] = &[
("key.jump", Some(Button::South)),
("key.drop", Some(Button::East)),
("key.drop", Some(Button::DPadDown)),
("key.swapOffhand", Some(Button::West)),
("key.inventory", Some(Button::North)),
(HOTBAR_PREVIOUS, Some(Button::LeftBumper)),
@@ -305,15 +311,31 @@ pub const ACTIONS: &[(&str, Option<Button>)] = &[
("key.attack", Some(Button::RightTrigger)),
("key.sprint", Some(Button::LeftStick)),
("key.sneak", Some(Button::RightStick)),
("key.togglePerspective", Some(Button::DPadUp)),
("key.togglePerspective", Some(Button::Select)),
("key.pickItem", Some(Button::DPadLeft)),
("key.chat", Some(Button::DPadRight)),
("key.advancements", Some(Button::DPadDown)),
("key.playerlist", Some(Button::Select)),
("key.chat", Some(Button::DPadUp)),
("key.advancements", None),
("key.playerlist", None),
("key.command", None),
("key.screenshot", None),
("key.toggleGui", None),
("key.smoothCamera", None),
// Horizon's emote wheel: no button is free by default; the stick's cursor picks.
("key.emote", None),
("key.fullscreen", None),
("key.socialInteractions", None),
("key.quickActions", None),
("key.saveToolbarActivator", None),
("key.loadToolbarActivator", None),
("key.hotbar.1", None),
("key.hotbar.2", None),
("key.hotbar.3", None),
("key.hotbar.4", None),
("key.hotbar.5", None),
("key.hotbar.6", None),
("key.hotbar.7", None),
("key.hotbar.8", None),
("key.hotbar.9", None),
];
/// How a bindable action reaches the game: one of its own handlers, shared
@@ -328,6 +350,10 @@ pub enum Route {
Sneak,
Screenshot,
SmoothCamera,
Fullscreen,
/// Does nothing by itself: what reads it asks whether the button is held
/// (`Minecraft.handleKeybinds`' toolbar keys, held with a hotbar key).
Held,
Key(winit::keyboard::KeyCode),
Mouse(winit::event::MouseButton),
}
@@ -340,6 +366,8 @@ pub fn route(action: &str) -> Option<Route> {
"key.sneak" => Some(Route::Sneak),
"key.screenshot" => Some(Route::Screenshot),
"key.smoothCamera" => Some(Route::SmoothCamera),
"key.fullscreen" => Some(Route::Fullscreen),
"key.saveToolbarActivator" | "key.loadToolbarActivator" => Some(Route::Held),
_ => {
let default = crate::keybinds::KeyBinds::default_of(action);
crate::keybinds::mouse_button(default)
@@ -359,6 +387,46 @@ pub fn action_caption(action: &str) -> &str {
}
}
/// How long a held drop button throws single items before it throws the rest of the stack.
pub const DROP_STACK_HOLD: Duration = Duration::from_secs(1);
/// What a held drop button does now, past its press.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DropStep {
/// Held key.drop (a repeat reaches `KeyMapping.click` as a press).
One,
/// Control + key.drop: a pad has no Control to hold, so holding on is how it asks.
Stack,
}
/// A held drop button's repeats: a tap throws one item, as Q does; held, it repeats at the pad's
/// repeat delay and interval; and held for [`DROP_STACK_HOLD`] it throws what's left.
#[derive(Clone, Copy, Debug)]
pub struct HeldDrop {
since: Instant,
next: Instant,
}
impl HeldDrop {
pub fn new(now: Instant, delay: Duration) -> Self {
Self {
since: now,
next: now + delay,
}
}
/// The step due at `now`, if any; at most one per call.
pub fn due(&mut self, now: Instant, interval: Duration) -> Option<DropStep> {
if now < self.next {
return None;
}
self.next = now + interval;
Some(if now.duration_since(self.since) >= DROP_STACK_HOLD {
DropStep::Stack
} else {
DropStep::One
})
}
}
/// Which button pictures prompts use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum GlyphStyle {
@@ -402,13 +470,21 @@ impl GlyphStyle {
GlyphStyle::PlayStation,
GlyphStyle::Nintendo,
];
/// The style for a pad by its USB vendor (Sony, Nintendo; Microsoft,
/// Valve's Steam Deck and Steam Input's virtual pad, and everything else
/// look like Xbox).
pub fn of_vendor(vendor: Option<u16>) -> Self {
match vendor {
Some(0x054c) => GlyphStyle::PlayStation,
Some(0x057e) => GlyphStyle::Nintendo,
/// The style for a pad by its USB ids: Sony's and Nintendo's own, and a few officially licensed
/// third-party pads made for their consoles. Microsoft, Valve's Steam Deck and Steam Input's
/// virtual pad, and everything else look like Xbox.
pub fn of_device(vendor: Option<u16>, product: Option<u16>) -> Self {
match (vendor, product) {
(Some(0x054c), _) => GlyphStyle::PlayStation,
(Some(0x057e), _) => GlyphStyle::Nintendo,
// HORIPAD 4 FPS and FPS Plus; Razer Raiju; Nacon Revolution Pro.
(Some(0x0f0d), Some(0x0055 | 0x0066))
| (Some(0x1532), Some(0x1000))
| (Some(0x146b), Some(0x0d01)) => GlyphStyle::PlayStation,
// HORIPAD for Nintendo Switch; PowerA Wired Plus; PDP Faceoff Wired Pro.
(Some(0x0f0d), Some(0x00c1))
| (Some(0x20d6), Some(0xa711))
| (Some(0x0e6f), Some(0x0180)) => GlyphStyle::Nintendo,
_ => GlyphStyle::Xbox,
}
}
@@ -591,6 +667,24 @@ impl PadSettings {
}
}
}
// A file from before these defaults: its player's buttons stay where they were.
if !text.is_empty() && !text.lines().any(|line| line.starts_with("bindLayout:")) {
for (action, button) in [
("key.drop", Button::East),
("key.togglePerspective", Button::DPadUp),
("key.chat", Button::DPadRight),
("key.playerlist", Button::Select),
("key.advancements", Button::DPadDown),
] {
// A button saved by hand stays, even one that's now this action's default.
if !text
.lines()
.any(|line| line.starts_with(&format!("bind_{action}:")))
{
s.bindings.entry(action).or_insert(Some(button));
}
}
}
s
}
pub fn serialize(&self) -> String {
@@ -621,6 +715,7 @@ impl PadSettings {
button.map_or("none", Button::name)
));
}
text.push_str("bindLayout:1\n");
text
}
pub fn default_of(action: &str) -> Option<Button> {
@@ -697,6 +792,29 @@ pub fn stick_axes(
}
}
/// The tilt from which a stick holds a key in [`eight_direction_keys`]: holding one is full speed,
/// so the small tilts past the deadzone stay still.
const KEY_TILT: f32 = 0.3;
/// tan(22.5 degrees): where one of the 8 sectors meets the next.
const SECTOR_EDGE: f32 = 0.414_213_57;
/// The movement keys (forward, backward, left, right) a move vector (`[left, forward]`) holds: the
/// one of the 8 headings it is nearest, so it is at most 22.5 degrees off. An edge goes to the
/// straight heading.
pub fn eight_direction_keys([left, forward]: [f32; 2]) -> [bool; 4] {
if length([left, forward]) < KEY_TILT {
return [false; 4];
}
let along = forward.abs() > SECTOR_EDGE * left.abs();
let across = left.abs() > SECTOR_EDGE * forward.abs();
[
along && forward > 0.0,
along && forward < 0.0,
across && left > 0.0,
across && left < 0.0,
]
}
/// A radial deadzone: inside it the stick is centred; beyond it the rest of
/// the travel is rescaled to 0..1 in the same direction, so diagonals aren't
/// clipped and the first movement past the deadzone is small.
@@ -745,15 +863,6 @@ pub fn look_delta(
)
}
/// The hotbar slot after a bumper: one step with wrap-around.
pub fn hotbar_step(selected: usize, forward: bool) -> usize {
if forward {
(selected + 1) % 9
} else {
(selected + 8) % 9
}
}
/// Menu cursor speed in GUI pixels per second at full tilt.
pub const CURSOR_SPEED: f32 = 300.0;
@@ -1460,6 +1569,52 @@ mod tests {
}
}
#[test]
fn a_held_drop_repeats_then_throws_the_stack() {
let t = Instant::now();
let at = |ms: u64| t + Duration::from_millis(ms);
let (delay, interval) = (Duration::from_millis(350), Duration::from_millis(90));
let mut held = HeldDrop::new(t, delay);
assert_eq!(held.due(at(100), interval), None, "a tap is one item");
assert_eq!(held.due(at(349), interval), None);
assert_eq!(held.due(at(350), interval), Some(DropStep::One));
assert_eq!(held.due(at(400), interval), None, "not before the interval");
assert_eq!(held.due(at(440), interval), Some(DropStep::One));
assert_eq!(held.due(at(999), interval), Some(DropStep::One));
assert_eq!(held.due(at(1000), interval), None);
assert_eq!(held.due(at(1100), interval), Some(DropStep::Stack));
assert_eq!(held.due(at(1200), interval), Some(DropStep::Stack));
assert_eq!(held.due(at(1201), interval), None);
}
#[test]
fn the_later_actions_have_no_default_button_and_leave_saved_bindings() {
let defaults = PadSettings::default();
for action in [
"key.fullscreen",
"key.socialInteractions",
"key.quickActions",
"key.saveToolbarActivator",
"key.loadToolbarActivator",
"key.hotbar.1",
"key.hotbar.9",
] {
assert_eq!(defaults.binding(action), None, "{action}");
}
let read = PadSettings::parse(
"bindLayout:1
bind_key.jump:east
bind_key.hotbar.2:north
",
);
assert_eq!(read.binding("key.jump"), Some(Button::East));
assert_eq!(read.binding("key.inventory"), Some(Button::North));
assert_eq!(
read.actions_of(Button::North),
["key.inventory", "key.hotbar.2"]
);
}
#[test]
fn navigation_preferences_migrate_and_stay_with_each_player() {
let dir = std::env::temp_dir().join(format!(
@@ -1579,7 +1734,7 @@ mod tests {
}
#[test]
fn defaults_follow_bedrock() {
fn every_action_has_its_default() {
let s = PadSettings::default();
assert_eq!(s.actions_of(Button::South), ["key.jump"]);
assert_eq!(s.actions_of(Button::RightTrigger), ["key.attack"]);
@@ -1587,16 +1742,46 @@ mod tests {
assert_eq!(s.actions_of(Button::North), ["key.inventory"]);
assert_eq!(s.actions_of(Button::RightBumper), [HOTBAR_NEXT]);
assert!(s.actions_of(Button::Start).is_empty());
// Every default action names a vanilla mapping or a pad action.
// Every default action names a key mapping or a pad action.
for (action, _) in ACTIONS {
assert!(
action.starts_with("pad.")
|| crate::keybinds::MAPPINGS.iter().any(|m| m.0 == *action),
|| crate::keybinds::all_mappings().any(|m| m.0 == *action),
"{action}"
);
}
}
#[test]
fn a_file_from_before_these_defaults_keeps_its_buttons() {
// Saved settings that never bound D-pad down: it stays on the advancements.
let s = PadSettings::parse("vibration:false\nbind_key.chat:up\n");
assert_eq!(s.binding("key.advancements"), Some(Button::DPadDown));
assert_eq!(s.binding("key.chat"), Some(Button::DPadUp));
assert_eq!(s.binding("key.drop"), Some(Button::East));
assert_eq!(s.binding("key.togglePerspective"), Some(Button::DPadUp));
assert_eq!(s.binding("key.playerlist"), Some(Button::Select));
assert!(!s.conflicts("key.advancements"));
// Advancements moved by hand stays moved, and the file stays this way from then on.
let s = PadSettings::parse("bind_key.advancements:left\nbind_key.drop:down\n");
assert_eq!(s.binding("key.advancements"), Some(Button::DPadLeft));
assert_eq!(s.binding("key.drop"), Some(Button::DPadDown));
assert_eq!(PadSettings::parse(&s.serialize()), s);
}
#[test]
fn a_new_player_drops_on_d_pad_down_and_chats_on_d_pad_up() {
for s in [PadSettings::default(), PadSettings::parse("")] {
assert_eq!(s.binding("key.drop"), Some(Button::DPadDown));
assert_eq!(s.binding("key.chat"), Some(Button::DPadUp));
assert_eq!(s.binding("key.togglePerspective"), Some(Button::Select));
assert_eq!(s.binding("key.playerlist"), None);
assert_eq!(s.binding("key.advancements"), None);
}
let s = PadSettings::parse(&PadSettings::default().serialize());
assert_eq!(s, PadSettings::default());
}
#[test]
fn settings_round_trip_and_store_only_changes() {
let mut s = PadSettings::default();
@@ -1618,8 +1803,9 @@ mod tests {
assert_eq!(back.binding("key.drop"), None);
assert_eq!(back.actions_of(Button::East), ["key.jump"]);
// Garbage keeps the defaults.
let odd =
PadSettings::parse("lookSensitivity:NaN\nbind_key.nope:south\nbind_key.jump:x9\n");
let odd = PadSettings::parse(
"lookSensitivity:NaN\nbind_key.nope:south\nbind_key.jump:x9\nbindLayout:1\n",
);
assert_eq!(odd, PadSettings::default());
}
@@ -1676,6 +1862,63 @@ mod tests {
assert_eq!(Button::North.by_letter().label(GlyphStyle::Nintendo), "Y");
}
#[test]
fn a_stick_holds_the_keys_of_its_nearest_heading() {
// Forward, backward, left, right, by the heading counted from forward toward left.
let headings = [
[true, false, false, false],
[true, false, true, false],
[false, false, true, false],
[false, true, true, false],
[false, true, false, false],
[false, true, false, true],
[false, false, false, true],
[true, false, false, true],
];
for tenth in 0..3600 {
let degrees = tenth as f32 / 10.0;
if degrees % 45.0 == 22.5 {
continue;
}
for tilt in [0.31, 0.5, 1.0] {
let (s, c) = degrees.to_radians().sin_cos();
let keys = eight_direction_keys([tilt * s, tilt * c]);
let sector = ((degrees / 45.0).round() as usize) % 8;
assert_eq!(keys, headings[sector], "{degrees} at {tilt}");
let [left, forward] =
crate::input::keyboard_direction(keys[0], keys[1], keys[2], keys[3]);
let off = (left.atan2(forward).to_degrees() - degrees).rem_euclid(360.0);
assert!(off.min(360.0 - off) <= 22.5 + 1e-3, "{degrees}: {off}");
}
}
}
#[test]
fn a_sector_edge_goes_to_the_straight_heading() {
assert_eq!(
eight_direction_keys([0.414_213_57, 1.0]),
[true, false, false, false]
);
assert_eq!(
eight_direction_keys([0.4143, 1.0]),
[true, false, true, false]
);
assert_eq!(
eight_direction_keys([1.0, 0.414_213_57]),
[false, false, true, false]
);
}
#[test]
fn a_small_tilt_holds_no_key() {
assert_eq!(eight_direction_keys([0.0, 0.0]), [false; 4]);
assert_eq!(eight_direction_keys([0.2, 0.2]), [false; 4]);
assert_eq!(
eight_direction_keys([0.0, 0.31]),
[true, false, false, false]
);
}
#[test]
fn radial_deadzone_rescales() {
assert_eq!(radial([0.1, 0.05], 0.15), [0.0, 0.0]);
@@ -2206,12 +2449,27 @@ mod tests {
}
#[test]
fn hotbar_wraps_and_glyphs_follow_the_vendor() {
assert_eq!(hotbar_step(8, true), 0);
assert_eq!(hotbar_step(0, false), 8);
assert_eq!(hotbar_step(3, true), 4);
assert_eq!(GlyphStyle::of_vendor(Some(0x054c)), GlyphStyle::PlayStation);
assert_eq!(GlyphStyle::of_vendor(Some(0x28de)), GlyphStyle::Xbox);
assert_eq!(GlyphStyle::of_vendor(None), GlyphStyle::Xbox);
fn glyphs_follow_the_vendor() {
let of = |vendor, product| GlyphStyle::of_device(Some(vendor), Some(product));
// Any product of the consoles' makers.
assert_eq!(of(0x054c, 0x0ce6), GlyphStyle::PlayStation);
assert_eq!(of(0x054c, 0x0001), GlyphStyle::PlayStation);
assert_eq!(of(0x057e, 0x2009), GlyphStyle::Nintendo);
// A pad made for a console by another maker, and that maker's others.
assert_eq!(of(0x0f0d, 0x0066), GlyphStyle::PlayStation);
assert_eq!(of(0x0f0d, 0x00c1), GlyphStyle::Nintendo);
assert_eq!(of(0x0f0d, 0x0067), GlyphStyle::Xbox);
assert_eq!(of(0x20d6, 0xa711), GlyphStyle::Nintendo);
// Valve's virtual pad, Microsoft's, nothing known, nothing reported.
assert_eq!(of(0x28de, 0x11ff), GlyphStyle::Xbox);
assert_eq!(of(0x045e, 0x0b12), GlyphStyle::Xbox);
assert_eq!(of(0x1234, 0x5678), GlyphStyle::Xbox);
assert_eq!(GlyphStyle::of_device(None, None), GlyphStyle::Xbox);
// A vendor alone is enough only for the consoles' makers.
assert_eq!(
GlyphStyle::of_device(Some(0x054c), None),
GlyphStyle::PlayStation
);
assert_eq!(GlyphStyle::of_device(Some(0x0f0d), None), GlyphStyle::Xbox);
}
}
+32 -5
View File
@@ -3,15 +3,18 @@
//! device letting go (splitscreen moving the keyboard to another player, say)
//! can't release what another still presses.
use crate::actions::Action;
use std::collections::HashMap;
use winit::keyboard::KeyCode;
/// Where a press came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Source {
/// The keyboard and mouse, and the scripting socket acting as them.
/// The keyboard and mouse.
Keyboard,
Pad,
/// `horizon-ctl`'s `key` and `mouse` and the agent commands that walk and click.
Agent,
}
impl Source {
@@ -19,6 +22,7 @@ impl Source {
match self {
Source::Keyboard => 1,
Source::Pad => 2,
Source::Agent => 4,
}
}
}
@@ -29,9 +33,20 @@ pub struct HeldKeys {
}
impl HeldKeys {
pub fn contains(&self, key: &KeyCode) -> bool {
/// Whether anything holds this mapping: every device, whatever the mapping is bound to.
pub fn held(&self, action: Action) -> bool {
action.key().is_some_and(|key| self.raw(&key))
}
/// Whether a key that is no mapping's default is held (Right Shift, the arrows, Alt, the system
/// key), or the key a caller already holds as a key: most code wants [`HeldKeys::held`].
pub fn raw(&self, key: &KeyCode) -> bool {
self.held.contains_key(key)
}
/// The old way of asking, by a mapping's default key; clippy refuses it (`clippy.toml`). It
/// stays so that a change written against it says what to use instead.
pub fn contains(&self, key: &KeyCode) -> bool {
self.raw(key)
}
/// `source` holds `key`. True when nothing held it before.
pub fn press(&mut self, key: KeyCode, source: Source) -> bool {
let sources = self.held.entry(key).or_insert(0);
@@ -72,7 +87,7 @@ impl HeldKeys {
/// Held, by the keyboard unless a device already holds it: for callers
/// that don't say where the press came from.
pub fn insert(&mut self, key: KeyCode) -> bool {
if self.contains(&key) {
if self.raw(&key) {
return false;
}
self.press(key, Source::Keyboard)
@@ -132,13 +147,25 @@ mod tests {
assert!(!keys.press(KeyCode::Space, Source::Keyboard));
assert!(keys.press(KeyCode::KeyW, Source::Keyboard));
assert_eq!(keys.release_source(Source::Keyboard), vec![KeyCode::KeyW]);
assert!(keys.contains(&KeyCode::Space) && !keys.contains(&KeyCode::KeyW));
assert!(keys.held(Action::Jump) && !keys.held(Action::Forward));
assert!(keys.held_by(&KeyCode::Space, Source::Pad));
assert!(!keys.held_by(&KeyCode::Space, Source::Keyboard));
assert!(keys.release(&KeyCode::Space, Source::Pad));
assert!(keys.is_empty());
}
#[test]
fn a_script_holds_a_key_by_itself() {
let mut keys = HeldKeys::default();
keys.press(KeyCode::KeyW, Source::Agent);
keys.press(KeyCode::KeyW, Source::Keyboard);
assert!(!keys.release(&KeyCode::KeyW, Source::Keyboard));
assert!(keys.held(Action::Forward));
assert!(keys.release_source(Source::Pad).is_empty());
assert_eq!(keys.release_source(Source::Agent), vec![KeyCode::KeyW]);
assert!(!keys.held(Action::Forward));
}
#[test]
fn untagged_inserts_and_removes_act_as_before() {
let mut keys = HeldKeys::default();
@@ -149,7 +176,7 @@ mod tests {
keys.remove(&KeyCode::ShiftLeft),
"remove lets go for everyone"
);
assert!(!keys.contains(&KeyCode::ShiftLeft));
assert!(!keys.held(Action::Sneak));
assert!(keys.release(&KeyCode::KeyA, Source::Keyboard), "never held");
}
}
@@ -51,11 +51,6 @@ impl InteractionInput {
pub fn press(&mut self, button: Button) {
self.clicks[button as usize] += 1;
}
/// Whether a click waits for the next tick.
pub fn has_clicks(&self) -> bool {
self.clicks.iter().any(|&c| c > 0)
}
pub fn tick(&mut self, world: &mut impl InteractionWorld, attack_down: bool, use_down: bool) {
let [attack, use_item, pick] = std::mem::take(&mut self.clicks);
world.pick_hit_result();
+59 -14
View File
@@ -74,6 +74,17 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[
("key.debug.lightmapTexture", "key.keyboard.4", "debug"),
("key.debug.improvedTransparency", "key.keyboard.x", "debug"),
];
/// Horizon's own key mappings: bound in Controls like the vanilla ones, but kept in
/// `horizon-extras.txt` (`emoteKey`), never in `options.txt`, which stays exactly vanilla's
/// (`MAPPINGS` is what the options parity harness compares with the pinned client).
pub const HORIZON_MAPPINGS: &[(&str, &str, &str)] = &[
// The emote wheel (docs/cosmetics.md), on a key vanilla leaves free.
("key.emote", "key.keyboard.b", "multiplayer"),
];
/// Every mapping the game binds: vanilla's in `Options.keyMappings` order, then Horizon's.
pub fn all_mappings() -> impl Iterator<Item = &'static (&'static str, &'static str, &'static str)> {
MAPPINGS.iter().chain(HORIZON_MAPPINGS)
}
/// Mappings Options builds as `ToggleKeyMapping` (hold or toggle by option).
pub fn is_toggle(name: &str) -> bool {
matches!(name, "key.sneak" | "key.sprint" | "key.use" | "key.attack")
@@ -312,8 +323,7 @@ pub struct KeyBinds {
impl Default for KeyBinds {
fn default() -> Self {
Self {
keys: MAPPINGS
.iter()
keys: all_mappings()
.map(|(n, d, _)| (*n, (*d).to_owned()))
.collect(),
}
@@ -339,8 +349,7 @@ impl KeyBinds {
.map_or("key.keyboard.unknown", String::as_str)
}
pub fn default_of(name: &str) -> &'static str {
MAPPINGS
.iter()
all_mappings()
.find(|m| m.0 == name)
.map_or("key.keyboard.unknown", |m| m.1)
}
@@ -348,16 +357,24 @@ impl KeyBinds {
self.get(name) == Self::default_of(name)
}
pub fn set(&mut self, name: &str, key: &str) {
if let Some((n, _, _)) = MAPPINGS.iter().find(|m| m.0 == name) {
if let Some((n, _, _)) = all_mappings().find(|m| m.0 == name) {
self.keys.insert(n, key.to_owned());
}
}
/// The bindings `options.txt` holds: vanilla's mappings only.
pub fn saved(&self) -> Vec<(&'static str, String)> {
MAPPINGS
.iter()
.map(|(n, _, _)| (*n, self.get(n).to_owned()))
.collect()
}
/// Horizon's own bindings, for `horizon-extras.txt`.
pub fn horizon_saved(&self) -> Vec<(&'static str, String)> {
HORIZON_MAPPINGS
.iter()
.map(|(n, _, _)| (*n, self.get(n).to_owned()))
.collect()
}
pub fn reset_all(&mut self) {
*self = Self::default();
}
@@ -367,8 +384,7 @@ impl KeyBinds {
if key == "key.keyboard.unknown" {
return Vec::new();
}
MAPPINGS
.iter()
all_mappings()
.filter(|(n, _, _)| {
*n != name && self.get(n) == key && (!self.is_default(n) || !self.is_default(name))
})
@@ -382,8 +398,7 @@ impl KeyBinds {
/// Every mapping a physical input triggers, in list order: like
/// `KeyMapping.set`/`click`, one key drives all the mappings bound to it.
pub fn mappings_for<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'static str> + 'a {
MAPPINGS
.iter()
all_mappings()
.map(|m| m.0)
.filter(move |n| self.get(n) == key)
}
@@ -393,8 +408,7 @@ impl KeyBinds {
/// key and the binding itself); their defaults (A, S, D, T, L, 1 to 4...)
/// would otherwise turn the key back into its old gameplay meaning.
fn translated_mappings<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'static str> + 'a {
MAPPINGS
.iter()
all_mappings()
.filter(|m| m.2 != "debug")
.map(|m| m.0)
.filter(move |n| self.get(n) == key)
@@ -402,9 +416,7 @@ impl KeyBinds {
/// Whether a mapping (other than a debug key) whose default is `key` was
/// bound elsewhere.
fn default_moved(&self, key: &str) -> bool {
MAPPINGS
.iter()
.any(|(n, d, c)| *d == key && *c != "debug" && !self.is_default(n))
all_mappings().any(|(n, d, c)| *d == key && *c != "debug" && !self.is_default(n))
}
/// Translate a physical key into the default key of the mapping it is
/// bound to, so game code written against vanilla defaults follows the
@@ -440,6 +452,18 @@ impl KeyBinds {
}
vec![Ok(key)]
}
/// `Minecraft.handleKeybinds`: key.pickItem and key.spectatorHotbar share the middle button by
/// default and are separate mappings, so a press of what `input` is bound to acts only as the
/// one this player can use: the spectator hotbar for a spectator, pick block otherwise. (Pick
/// block does nothing a spectator would see.)
pub fn middle_acts(&self, input: &str, spectator: bool) -> bool {
let mapping = if spectator {
"key.spectatorHotbar"
} else {
"key.pickItem"
};
self.get(mapping) == input
}
/// Translate a mouse button the same way (keys bound to mouse buttons).
pub fn translate_mouse(&self, button: MouseButton) -> Option<Result<KeyCode, MouseButton>> {
self.translate_mouse_all(button).into_iter().next()
@@ -503,6 +527,27 @@ impl KeyBinds {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mappings_sharing_the_middle_button_act_as_themselves() {
let middle = "key.mouse.middle";
let z = "key.keyboard.z";
let mut keys = KeyBinds::default();
assert!(keys.middle_acts(middle, false) && keys.middle_acts(middle, true));
// The spectator hotbar on Z: the middle button only picks, and Z never picks.
keys.set("key.spectatorHotbar", z);
assert!(keys.middle_acts(middle, false));
assert!(!keys.middle_acts(middle, true));
assert!(keys.middle_acts(z, true));
assert!(!keys.middle_acts(z, false));
// Pick block on Z instead: the other way round.
keys.reset_all();
keys.set("key.pickItem", z);
assert!(keys.middle_acts(z, false));
assert!(!keys.middle_acts(z, true));
assert!(keys.middle_acts(middle, true));
assert!(!keys.middle_acts(middle, false));
}
#[test]
fn container_mouse_hotkeys_follow_slot_bindings_and_pick_item_priority() {
for button in [MouseButton::Back, MouseButton::Forward, MouseButton::Middle] {
+1
View File
@@ -3,6 +3,7 @@
//! options. horizon-client re-exports each module under its old path
//! (`horizon_client::keybinds`, ...).
#![forbid(unsafe_code)]
pub mod actions;
pub mod clipboard;
pub mod gamepad;
pub mod held;
+16
View File
@@ -628,6 +628,22 @@ pub fn icon() -> Option<winit::window::Icon> {
winit::window::Icon::from_rgba(bytes, info.width, info.height).ok()
}
/// Apply Horizon's icon to every window. Windows has a separate taskbar icon slot from the small
/// window icon; requiring the decoded icon there prevents a generic taskbar icon from appearing.
pub fn with_horizon_icon(
attributes: winit::window::WindowAttributes,
) -> winit::window::WindowAttributes {
let icon = icon();
#[cfg(target_os = "windows")]
let icon = Some(icon.expect("Horizon's icon must be available on Windows"));
let attributes = attributes.with_window_icon(icon.clone());
#[cfg(target_os = "windows")]
let attributes =
winit::platform::windows::WindowAttributesExtWindows::with_taskbar_icon(attributes, icon);
attributes
}
#[cfg(test)]
mod tests {
use super::*;
+2
View File
@@ -18,6 +18,8 @@ horizon-client-core = { path = "../horizon-client-core" }
horizon-client-input = { path = "../horizon-client-input" }
horizon-client-render = { path = "../horizon-client-render" }
horizon-command = { path = "../horizon-command" }
# Emotes pose the player model (`Mob::emote`, `mobs::anim::setup`).
horizon-cosmetics = { path = "../horizon-cosmetics" }
horizon-items = { path = "../horizon-items" }
horizon-core = { path = "../horizon-core" }
# `horizon-ctl mcp`: the Model Context Protocol, shared with the launcher and the server.
@@ -648,6 +648,7 @@ fn remesh(
nether_shading: false,
shader_pack_lighting: false,
separate_ao: false,
shader_pack: false,
assets,
render,
tables: &tables,
+3 -12
View File
@@ -6,13 +6,7 @@ use horizon_world::{
worldgen::{tags::TagDefinitions, terrain::TerrainBlockStates},
};
use serde_json::Value;
use std::{
collections::BTreeSet,
fs::File,
io::{self, BufReader},
path::Path,
sync::Arc,
};
use std::{collections::BTreeSet, io, path::Path, sync::Arc};
pub const MATERIALS: [&str; 6] = ["bedrock", "dirt", "stone", "sand", "oak_planks", "bricks"];
#[derive(Clone, Copy)]
@@ -190,15 +184,12 @@ fn invalid(message: &str) -> io::Error {
}
impl Assets {
pub fn load(root: &Path) -> Result<Self> {
let manifest: Value = serde_json::from_reader(BufReader::new(File::open(
root.join("horizon-resources.json"),
)?))?;
let manifest: Value = horizon_world::json_file::read(&root.join("horizon-resources.json"))?;
if manifest["data_version"].as_i64() != Some(i64::from(DATA_VERSION)) {
return Err(invalid("resources do not match Horizon's pinned data version").into());
}
let (registry, flags) = horizon_world::level::data::load_registry_with_flags(root)?;
let bundle: Value =
serde_json::from_reader(BufReader::new(File::open(root.join("block-tags.json"))?))?;
let bundle: Value = horizon_world::json_file::read(&root.join("block-tags.json"))?;
let mut definitions = TagDefinitions::default();
for (name, text) in bundle
.as_object()
+127 -40
View File
@@ -2,7 +2,9 @@
//! small mixer standing in for OpenAL: one channel per source with its gain,
//! pitch, linear distance attenuation (`AL_LINEAR_DISTANCE`, reference 0,
//! rolloff 1), looping, relative flag and source state, Ogg/Vorbis decoding
//! (streams on a worker thread) and OpenAL Soft's stereo panning.
//! (streams on a worker thread) and OpenAL Soft's mixing: mono sources panned
//! and attenuated, multi-channel buffers (stereo music and records) played
//! direct as OpenAL does.
use crate::Result;
use crate::sound_engine::{
Attenuation, Backend, Bound, ChannelId, InstanceId, PlayResult, SoundEngine, SoundInstance,
@@ -29,7 +31,7 @@ enum State {
}
/// An OpenAL source.
struct Channel {
samples: Option<(Arc<Vec<f32>>, u32)>,
samples: Option<(Arc<Vec<f32>>, u32, u16)>,
position: f64,
state: State,
gain: f32,
@@ -135,8 +137,8 @@ impl Drop for MixerBackend {
static SHARED_CHANNELS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Two players' copies of one sound: started within this of each other.
const SAME_SOUND: std::time::Duration = std::time::Duration::from_millis(150);
/// Decoded samples and their rate (`None`: the file did not load).
type Samples = Option<(Arc<Vec<f32>>, u32)>;
/// Decoded interleaved samples, their rate and channel count (`None`: the file did not load).
type Samples = Option<(Arc<Vec<f32>>, u32, u16)>;
/// Decoded static sounds (`SoundBufferLibrary`'s buffers), dropped least
/// recently used first past `CACHE_BYTES`: kept forever, every sound heard in
/// a session stayed (up to 1.4 GiB of samples, villages playing hundreds).
@@ -177,7 +179,7 @@ impl SoundCache {
fn size(samples: &Samples) -> usize {
samples
.as_ref()
.map_or(0, |(s, _)| s.len() * std::mem::size_of::<f32>())
.map_or(0, |(s, _, _)| s.len() * std::mem::size_of::<f32>())
}
}
/// A static sound to decode for a channel waiting on it.
@@ -260,7 +262,7 @@ pub struct Audio {
#[cfg(feature = "audio")]
device_ticks: u32,
}
fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
fn decode(path: &Path) -> Option<(Vec<f32>, u32, u16)> {
use symphonia::core::{
audio::SampleBuffer, codecs::DecoderOptions, formats::FormatOptions, io::MediaSourceStream,
meta::MetadataOptions, probe::Hint,
@@ -284,7 +286,8 @@ fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
let mut decoder = symphonia::default::get_codecs()
.make(&track.codec_params, &DecoderOptions::default())
.ok()?;
let mut mono = Vec::new();
let mut samples = Vec::new();
let mut channels = 0u16;
while let Ok(packet) = format.next_packet() {
if packet.track_id() != id {
continue;
@@ -293,14 +296,34 @@ fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
continue;
};
let spec = *buffer.spec();
let channels = spec.channels.count().max(1);
let mut samples = SampleBuffer::<f32>::new(buffer.capacity() as u64, spec);
samples.copy_interleaved_ref(buffer);
for frame in samples.samples().chunks(channels) {
mono.push(frame.iter().sum::<f32>() / channels as f32);
let frame_channels = spec.channels.count().max(1);
let mut decoded = SampleBuffer::<f32>::new(buffer.capacity() as u64, spec);
decoded.copy_interleaved_ref(buffer);
if channels == 0 {
channels = frame_channels.min(2) as u16;
}
if frame_channels <= 2 {
samples.extend_from_slice(decoded.samples());
} else {
// OpenAL plays multi-channel buffers direct; a stereo output hears the odd/even split.
for frame in decoded.samples().chunks(frame_channels) {
let (mut left, mut right) = (0.0, 0.0);
let (mut lefts, mut rights) = (0.0f32, 0.0f32);
for (i, sample) in frame.iter().enumerate() {
if i % 2 == 0 {
left += sample;
lefts += 1.0;
} else {
right += sample;
rights += 1.0;
}
}
samples.push(left / lefts.max(1.0));
samples.push(right / rights.max(1.0));
}
}
}
Some((mono, rate))
(channels != 0).then_some((samples, rate, channels))
}
/// A sound file without its variant number (`mob/creeper/say2.ogg` is `mob/creeper/say`): each
/// player's game picks its own variant of the same event.
@@ -427,7 +450,7 @@ impl Backend for MixerBackend {
// A streamed sound loops by restarting its stream.
let mixer = self.mixer.clone();
std::thread::spawn(move || {
let samples = decode(&file).map(|(s, r)| (Arc::new(s), r));
let samples = decode(&file).map(|(s, r, c)| (Arc::new(s), r, c));
attach(&mixer, channel, samples, looping);
});
return;
@@ -448,7 +471,7 @@ impl Backend for MixerBackend {
// Queued twice before the first decode finished.
let cached = cache.lock().ok().and_then(|mut c| c.get(&job.key));
let samples = cached.unwrap_or_else(|| {
let samples = decode(&job.file).map(|(s, r)| (Arc::new(s), r));
let samples = decode(&job.file).map(|(s, r, c)| (Arc::new(s), r, c));
if let Ok(mut c) = cache.lock() {
c.insert(job.key, samples.clone());
}
@@ -584,9 +607,13 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
let mut voices = std::mem::take(&mut mixer.voices);
voices.clear();
for (id, c) in &mixer.channels {
let Some((_, source_rate)) = &c.samples else {
let Some((_, source_rate, source_channels)) = &c.samples else {
continue;
};
// OpenAL plays a multi-channel buffer direct: no panning and no distance attenuation
// (`CalcVoiceParams`' non-spatialized path, vanilla's HRTF-off stereo context). Vanilla's
// music and records are stereo. A mono buffer is the positional one.
let direct = *source_channels > 1;
if c.state != State::Playing {
continue;
}
@@ -611,24 +638,33 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
let d = if c.relative { at } else { away(listener) };
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32;
let gain = if camera.is_some() {
c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance)
c.gain.clamp(0.0, 1.0)
* if direct {
1.0
} else {
distance_gain(c.linear, distance)
}
} else {
0.0
};
// Relative sources are already in OpenAL's listener space (-Z ahead).
let [mut left, mut right] = if c.relative {
stereo_gains(d[0] as f32, d[1] as f32, -d[2] as f32)
let [left, right] = if direct {
[gain, gain]
} else {
stereo_gains(dot(d, right), dot(d, up), dot(d, forward))
// Relative sources are already in OpenAL's listener space (-Z ahead).
let [mut left, mut right] = if c.relative {
stereo_gains(d[0] as f32, d[1] as f32, -d[2] as f32)
} else {
stereo_gains(dot(d, right), dot(d, up), dot(d, forward))
};
if shared {
// Several players on the speakers: half the stereo width, as left and right are
// nobody's in particular.
let middle = (left + right) / 2.0;
left = middle + (left - middle) / 2.0;
right = middle + (right - middle) / 2.0;
}
[left * gain, right * gain]
};
if shared {
// Several players on the speakers: half the stereo width, as left and right are
// nobody's in particular.
let middle = (left + right) / 2.0;
left = middle + (left - middle) / 2.0;
right = middle + (right - middle) / 2.0;
}
let [left, right] = [left, right].map(|pan| gain * pan);
let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0));
voices.push((*id, [left, right, gain], step));
}
@@ -636,13 +672,15 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
let Some(c) = mixer.channels.get_mut(&id) else {
continue;
};
let Some((samples, _)) = c.samples.clone() else {
let Some((samples, _, source_channels)) = c.samples.clone() else {
continue;
};
let source_channels = source_channels as usize;
let frames = samples.len() / source_channels;
for frame in data.chunks_mut(channels) {
let mut i = c.position as usize;
if i + 1 >= samples.len() {
if c.looping && samples.len() > 1 {
if i + 1 >= frames {
if c.looping && frames > 1 {
c.position = 0.0;
i = 0;
} else {
@@ -651,13 +689,24 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
}
}
let t = (c.position - i as f64) as f32;
let s = samples[i] * (1.0 - t) + samples[i + 1] * t;
if channels >= 2 {
frame[0] += s * left;
frame[1] += s * right;
if source_channels > 1 {
let l = samples[i * 2] * (1.0 - t) + samples[(i + 1) * 2] * t;
let r = samples[i * 2 + 1] * (1.0 - t) + samples[(i + 1) * 2 + 1] * t;
if channels >= 2 {
frame[0] += l * left;
frame[1] += r * right;
} else {
frame[0] += (l + r) * 0.5 * gain;
}
} else {
// A mono output has no panning: the source's own gain.
frame[0] += s * gain;
let s = samples[i] * (1.0 - t) + samples[i + 1] * t;
if channels >= 2 {
frame[0] += s * left;
frame[1] += s * right;
} else {
// A mono output has no panning: the source's own gain.
frame[0] += s * gain;
}
}
c.position += step;
}
@@ -1687,7 +1736,7 @@ mod tests {
fn channel(samples: Vec<f32>, linear: Option<f32>, at: [f32; 3], looping: bool) -> Channel {
Channel {
samples: Some((Arc::new(samples), 48_000)),
samples: Some((Arc::new(samples), 48_000, 1)),
position: 0.0,
state: State::Playing,
gain: 1.0,
@@ -1702,11 +1751,23 @@ mod tests {
}
}
/// A channel whose buffer is interleaved stereo.
fn stereo_channel(
samples: Vec<f32>,
linear: Option<f32>,
at: [f32; 3],
looping: bool,
) -> Channel {
let mut c = channel(Vec::new(), linear, at, looping);
c.samples = Some((Arc::new(samples), 48_000, 2));
c
}
#[test]
fn decoded_sounds_stay_within_the_budget_least_recently_used_out() {
let mut cache = SoundCache::default();
let quarter = CACHE_BYTES / 4 / std::mem::size_of::<f32>();
let sound = || Some((Arc::new(vec![0.0f32; quarter]), 44100));
let sound = || Some((Arc::new(vec![0.0f32; quarter]), 44100, 1));
for key in ["a", "b", "c", "d"] {
cache.insert(key.into(), sound());
}
@@ -1833,6 +1894,32 @@ mod tests {
}
}
#[test]
fn stereo_sounds_play_direct_without_panning_or_distance() {
// OpenAL Soft plays a multi-channel buffer direct (its non-spatialized path), so vanilla's
// stereo music and records keep their own left/right mix at full volume whichever way the
// camera faces and however far it is. Only mono buffers are panned and attenuated.
let wave = [0.1, -0.2, 0.3, -0.4, 0.5, -0.6]; // three stereo frames
let expected = [wave[0], wave[1], wave[2], wave[3]];
for (yaw, at, linear, listener) in [
(0.0, [100.0, 0.0, 0.0], Some(16.0), [0.0; 3]),
(180.0, [0.0, 0.0, -100.0], Some(16.0), [0.0; 3]),
(90.0, [2.0, 1.0, -3.0], Some(16.0), [5.0, 60.0, 5.0]),
(0.0, [0.0, 0.0, 0.0], None, [0.0; 3]),
] {
let mut m = Mixer {
listener,
listener_yaw: yaw,
..Mixer::default()
};
m.channels
.insert(1, stereo_channel(wave.to_vec(), linear, at, false));
let mut data = [0.0; 4];
mix(&mut m, &mut data, 2, 48_000);
assert_eq!(data, expected, "yaw {yaw}, source {at:?}");
}
}
#[test]
fn panning_follows_the_camera_rotation() {
let gains = |yaw: f32, pitch: f32, at: [f32; 3]| {
+1 -1
View File
@@ -288,7 +288,7 @@ impl Biomes {
.collect();
files.sort_by_cached_key(|f| format!("{}.json", f.name));
for file in files {
let v: Value = serde_json::from_slice(file.bytes()?)?;
let v: Value = horizon_world::json_file::parse(&file.path, file.bytes()?)?;
list.push(BiomeInfo::from_json(
format!("minecraft:{}", file.name),
&v,
+88 -2
View File
@@ -1,5 +1,6 @@
// `joml::Mat4::rotation` and `invert_orthonormal` in this file are adapted from JOML 1.10.9's
// `Matrix4f` (https://github.com/JOML-CI/JOML, MIT; see THIRD_PARTY_NOTICES.md).
// `joml::Mat4::rotation`, `rotate_affine`, `transform_affine` and `invert_orthonormal`, and
// `joml::Quat::rotation_x`/`_y`/`_z`, in this file are adapted from JOML 1.10.9's `Matrix4f`,
// `Quaternionf` and `Vector4f` (https://github.com/JOML-CI/JOML, MIT; see THIRD_PARTY_NOTICES.md).
//
// Copyright (c) 2015-2026 Richard Greenlees
//
@@ -142,6 +143,40 @@ pub mod joml {
w: w * cz + z * sz,
}
}
/// `Quaternionf.rotationX(angle)`.
pub fn rotation_x(angle: f32) -> Self {
let (x, w) = Self::half_turn(angle);
Self {
x,
y: 0.0,
z: 0.0,
w,
}
}
/// `Quaternionf.rotationY(angle)`.
pub fn rotation_y(angle: f32) -> Self {
let (y, w) = Self::half_turn(angle);
Self {
x: 0.0,
y,
z: 0.0,
w,
}
}
/// `Quaternionf.rotationZ(angle)`.
pub fn rotation_z(angle: f32) -> Self {
let (z, w) = Self::half_turn(angle);
Self {
x: 0.0,
y: 0.0,
z,
w,
}
}
fn half_turn(angle: f32) -> (f32, f32) {
let sin = sin(angle * 0.5);
(sin, cos_from_sin(sin, angle * 0.5))
}
/// `Quaternionf.transform(x, y, z, dest)` (`Vector3f.rotate`).
pub fn transform(&self, v: [f32; 3]) -> [f32; 3] {
let [x, y, z] = v;
@@ -336,6 +371,57 @@ pub mod joml {
self.set(2, 2, z2 - y2 - x2 + w2);
self.properties = AFFINE | ORTHONORMAL;
}
/// An affine matrix of no more specific kind, as JOML's property flags have it.
pub fn affine(m: glam::Mat4) -> Self {
Self {
m: m.to_cols_array(),
properties: AFFINE,
}
}
/// `Matrix4f.rotate(Quaternionfc)` of an affine matrix that is neither the identity nor
/// a pure translation (`rotateAffine`).
pub fn rotate_affine(&mut self, q: Quat) {
debug_assert!(
self.properties & AFFINE != 0 && self.properties & (IDENTITY | TRANSLATION) == 0
);
let (w2, x2, y2, z2) = (q.w * q.w, q.x * q.x, q.y * q.y, q.z * q.z);
let zw = q.z * q.w;
let dzw = zw + zw;
let xy = q.x * q.y;
let dxy = xy + xy;
let xz = q.x * q.z;
let dxz = xz + xz;
let yw = q.y * q.w;
let dyw = yw + yw;
let yz = q.y * q.z;
let dyz = yz + yz;
let xw = q.x * q.w;
let dxw = xw + xw;
let r = [
[w2 + x2 - z2 - y2, dxy + dzw, dxz - dyw],
[-dzw + dxy, y2 - z2 + w2 - x2, dyz + dxw],
[dyw + dxz, dyz - dxw, z2 - y2 - x2 + w2],
];
let s = *self;
for (column, r) in r.iter().enumerate() {
for row in 0..3 {
let v = s.get(0, row) * r[0] + s.get(1, row) * r[1] + s.get(2, row) * r[2];
self.set(column, row, v);
}
self.set(column, 3, 0.0);
}
self.properties &= !(PERSPECTIVE | IDENTITY | TRANSLATION);
}
/// `Vector4f.mul(Matrix4fc)` of an affine matrix (`mulAffine`, JOML's `Math.fma`
/// unfused): the matrix times `v`, `w` kept.
pub fn transform_affine(&self, v: [f32; 4]) -> [f32; 3] {
debug_assert!(self.properties & AFFINE != 0);
let [x, y, z, w] = v;
std::array::from_fn(|row| {
self.get(0, row) * x
+ (self.get(1, row) * y + (self.get(2, row) * z + self.get(3, row) * w))
})
}
/// `Matrix4f.invert()` of a rotation and translation (`invertOrthonormal`; with the
/// identity and pure-translation shortcuts). `None` for any other matrix, which JOML
/// inverts by other code paths.
+35
View File
@@ -225,6 +225,8 @@ pub const BIOME_STRATEGY: Strategy = Strategy::biomes(8);
/// (what vanilla servers and clients send), more when content mods add states
/// past 65,536 (docs/modpacks.md). Set once, before the first chunk.
static BLOCK_BITS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(16);
/// States in the registry, set with [`BLOCK_BITS`].
static BLOCK_STATES: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(u32::MAX);
/// Block states are `PalettedContainer`s over the registry: vanilla's 16-bit
/// global palette, wider with enough content mods.
@@ -232,6 +234,35 @@ pub fn block_strategy() -> Strategy {
Strategy::blocks(BLOCK_BITS.load(std::sync::atomic::Ordering::Relaxed))
}
/// Whether the registry has this state. Every id is known until the registry is loaded.
pub fn known_block_state(id: u32) -> bool {
id < BLOCK_STATES.load(std::sync::atomic::Ordering::Relaxed)
}
/// A server's block container in our palette width. Ids past our registry (a
/// server or host with mods we lack) read as air: every per-state table is
/// indexed by them, and a palette's unused entries are scanned too.
pub fn known_blocks_only(blocks: PalettedContainer) -> PalettedContainer {
let ours = block_strategy();
let unknown = |id: u32| !known_block_state(id) || u64::from(id) >> ours.global_bits != 0;
let any_unknown = if blocks.is_global() {
blocks.has(unknown)
} else {
blocks.maybe_has(unknown)
};
if !any_unknown && blocks.strategy().global_bits == ours.global_bits {
return blocks;
}
let mut values = [0u32; 4096];
blocks.unpack(&mut values);
for value in &mut values {
if unknown(*value) {
*value = 0;
}
}
PalettedContainer::from_values(ours, &values)
}
/// Frees `columns` (`count` of them) on a short-lived thread of its own
/// when there are many: a teleport or a dimension change drops a few
/// thousand columns at once, and freeing their sections took the frame
@@ -250,6 +281,10 @@ pub fn free_columns<T: Send + 'static>(columns: T, count: usize) {
pub fn set_block_states(states: usize) {
let bits = horizon_core::paletted::ceil_log2(states).max(16);
BLOCK_BITS.store(bits, std::sync::atomic::Ordering::Relaxed);
BLOCK_STATES.store(
u32::try_from(states).unwrap_or(u32::MAX),
std::sync::atomic::Ordering::Relaxed,
);
forget_shared();
}
File diff suppressed because it is too large. Load diff
@@ -896,6 +896,13 @@ pub fn worldgen_overrides(
let mut warnings = Vec::new();
for pack in packs {
for file in pack.list_kinds(&overrides::PACK_KINDS) {
if let Some(id) = overrides::template_id(&file) {
match pack.read(&file) {
Some(nbt) => out.set_template(&id, nbt),
None => warnings.push(format!("{}: {file}: unreadable", pack.id)),
}
continue;
}
let read = || String::from_utf8(pack.read(&file)?).ok();
match out.add_file(&pack.id, &file, read) {
PackFile::Read | PackFile::Other => {}
@@ -956,6 +963,7 @@ mod tests {
for pack in ["a", "b", "off"] {
write(pack, "pack.mcmeta", "{}");
write(pack, "data/minecraft/worldgen/noise/cave.json", pack);
write(pack, "data/p/structure/room/a.nbt", pack);
write(
pack,
"data/minecraft/tags/worldgen/biome/is_hill.json",
@@ -992,6 +1000,8 @@ mod tests {
o.entries("noises").collect::<Vec<_>>(),
[("minecraft:cave", "a")]
);
assert_eq!(o.templates().len(), 1);
assert_eq!(&*o.templates()["p:room/a"], b"a");
assert_eq!(
o.entries("biomes").collect::<Vec<_>>(),
[("minecraft:plains", "{}")]
@@ -3,7 +3,7 @@
//! celestial angles and star brightness for the overworld day cycle.
use crate::Result;
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
use std::{collections::HashMap, path::Path};
#[derive(Clone, Copy, Debug)]
enum Easing {
@@ -151,13 +151,13 @@ impl Environment {
/// A dimension's base attributes, optionally driven by the day timeline.
pub fn load_dimension(root: &Path, dimension: &str, day_cycle: bool) -> Result<Self> {
let timeline: Value = if day_cycle {
serde_json::from_slice(&fs::read(root.join("data/minecraft/timeline/day.json"))?)?
horizon_world::json_file::read(&root.join("data/minecraft/timeline/day.json"))?
} else {
serde_json::json!({"period_ticks": 24000, "tracks": {}})
};
let dimension: Value = serde_json::from_slice(&fs::read(
root.join(format!("data/minecraft/dimension_type/{dimension}.json")),
)?)?;
let dimension: Value = horizon_world::json_file::read(
&root.join(format!("data/minecraft/dimension_type/{dimension}.json")),
)?;
let mut tracks = HashMap::new();
for (name, track) in timeline["tracks"].as_object().ok_or("invalid timeline")? {
let easing = match &track["ease"] {
+88 -34
View File
@@ -10,6 +10,9 @@ pub const FILE: &str = "horizon-extras.txt";
pub const SORT_KEY: &str = "horizon.sort";
/// The 3D skin layers line, here and in the `options.txt` that held it first.
const SKIN_LAYERS_KEY: &str = "threeDSkinLayers";
/// The emote wheel's key, here and in the `key_key.emote` line #10092 wrote to `options.txt`.
const EMOTE_KEY: &str = "emoteKey";
const OLD_EMOTE_LINE: &str = "key_key.emote";
/// The minimap's sizes in GUI pixels, and its zooms in blocks per pixel.
pub const MINIMAP_SIZES: [(u8, &str); 3] = [(64, "Small"), (96, "Medium"), (128, "Large")];
@@ -66,6 +69,8 @@ pub struct Extras {
/// Modrinth. Off by default: it is Horizon's own and the screen is
/// otherwise vanilla's (tools/test_pack_screen_parity.py).
pub pack_browser: bool,
/// Make /pregen available in single-player and hosted LAN worlds.
pub pregen: bool,
pub fullbright: bool,
/// Held, dropped and burning light sources light their surroundings (`dynamic_light`).
pub dynamic_lights: bool,
@@ -124,6 +129,10 @@ pub struct Extras {
pub sort: bool,
/// A vanilla key name: sorts the part under the cursor.
pub sort_key: String,
/// The emote wheel's key (`key.emote`), as the game last saved it. The live binding is
/// `Settings::keys`, bound in Controls with the vanilla ones; it is only kept in this file
/// so that `options.txt` stays vanilla's (`Settings::load` hands it over, `save` takes it back).
pub emote_key: String,
/// A new chat line slides in from the left while it fades in (`Chat::layout`).
pub chat_animation: bool,
/// The indicator bar at the left of a chat line (on by default, as vanilla).
@@ -162,10 +171,10 @@ pub struct Extras {
/// Cosmetics (`horizon_cosmetics`, off unless enabled), the lines `horizon_cosmetics::prefs`
/// shares with the launcher's Wardrobe: Show my cosmetics (the account's, sent to the service;
/// on by default), how much of other players' to show (no line until chosen:
/// `effective_others`), and their auras and trails (off by default).
/// `effective_others`), and whether their trails and auras are hidden (off by default).
pub cosmetics_mine: bool,
pub cosmetics_others: Option<horizon_cosmetics::prefs::Others>,
pub cosmetics_auras: bool,
pub cosmetics_hide_fx: bool,
/// My cosmetics in single player too (`cosmeticsSolo`, off by default): the window's own server
/// names the player by their offline profile, which the service doesn't know, so their own
/// cosmetics and name tag style show only with this on.
@@ -188,6 +197,7 @@ impl Default for Extras {
fn default() -> Self {
Self {
pack_browser: false,
pregen: false,
fullbright: false,
dynamic_lights: false,
zoom: false,
@@ -217,6 +227,7 @@ impl Default for Extras {
mouse_tweaks_wheel: true,
sort: false,
sort_key: "key.keyboard.unknown".into(),
emote_key: crate::keybinds::KeyBinds::default_of("key.emote").into(),
chat_animation: false,
chat_indicator: true,
no_ai: false,
@@ -227,12 +238,12 @@ impl Default for Extras {
splitscreen_two: 0,
splitscreen_three: 0,
splitscreen_names: true,
wheel_cycles_settings: true,
wheel_cycles_settings: false,
music_off: Vec::new(),
music_page: false,
cosmetics_mine: true,
cosmetics_others: None,
cosmetics_auras: false,
cosmetics_hide_fx: false,
cosmetics_solo: false,
cosmetics_owner: false,
horizon_marks: true,
@@ -270,6 +281,7 @@ impl Extras {
};
match key.trim() {
"packBrowser" => e.pack_browser = flag(e.pack_browser),
"pregen" => e.pregen = flag(e.pregen),
"fullbright" => e.fullbright = flag(e.fullbright),
"dynamicLights" => e.dynamic_lights = flag(e.dynamic_lights),
"zoom" => e.zoom = flag(e.zoom),
@@ -320,6 +332,7 @@ impl Extras {
"mouseTweaksWheel" => e.mouse_tweaks_wheel = flag(e.mouse_tweaks_wheel),
"sort" => e.sort = flag(e.sort),
"sortKey" if value.starts_with("key.") => e.sort_key = value.to_owned(),
EMOTE_KEY if value.starts_with("key.") => e.emote_key = value.to_owned(),
"chatAnimation" => e.chat_animation = flag(e.chat_animation),
"chatIndicator" => e.chat_indicator = flag(e.chat_indicator),
horizon_core::no_ai::KEY => e.no_ai = flag(e.no_ai),
@@ -330,7 +343,11 @@ impl Extras {
"splitscreenTwo" => e.splitscreen_two = value.parse().unwrap_or(0).min(2),
"splitscreenThree" => e.splitscreen_three = value.parse().unwrap_or(0).min(2),
"splitscreenNames" => e.splitscreen_names = flag(e.splitscreen_names),
"wheelCyclesSettings" => e.wheel_cycles_settings = flag(e.wheel_cycles_settings),
// A new name: `wheelCyclesSettings` was written as true by every
// install while it was the default, so it says nothing of a choice.
"wheelCyclesListSettings" => {
e.wheel_cycles_settings = flag(e.wheel_cycles_settings)
}
"musicOff" => {
e.music_off = value
.split(',')
@@ -345,7 +362,7 @@ impl Extras {
e.cosmetics_others =
horizon_cosmetics::prefs::Others::parse(value).or(e.cosmetics_others)
}
"cosmeticsAuras" => e.cosmetics_auras = flag(e.cosmetics_auras),
"cosmeticsHideFx" => e.cosmetics_hide_fx = flag(e.cosmetics_hide_fx),
"cosmeticsSolo" => e.cosmetics_solo = flag(e.cosmetics_solo),
horizon_cosmetics::prefs::MARKS => e.horizon_marks = flag(e.horizon_marks),
horizon_cosmetics::prefs::LISTED => e.horizon_listed = flag(e.horizon_listed),
@@ -359,8 +376,9 @@ impl Extras {
}
pub fn serialize(&self) -> String {
let mut text = format!(
"packBrowser:{}\nfullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nlodZoomDetail:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nmovedToMods:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nuiSoundReserve:{}\nownNameTag:{}\nhideBlockParticles:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\nchatAnimation:{}\nchatIndicator:{}\n{}:{}\nagentControl:{}\nreproKeys:{}\ndiscordPresence:{}\nsplitscreen:{}\nsplitscreenTwo:{}\nsplitscreenThree:{}\nsplitscreenNames:{}\nwheelCyclesSettings:{}\nmusicOff:{}\nmusicPage:{}\ncosmeticsMine:{}\n{}cosmeticsAuras:{}\ncosmeticsSolo:{}\n{}:{}\n{}:{}\n{}:{}\n",
"packBrowser:{}\npregen:{}\nfullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nlodZoomDetail:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nmovedToMods:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nuiSoundReserve:{}\nownNameTag:{}\nhideBlockParticles:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\nchatAnimation:{}\nchatIndicator:{}\n{}:{}\nagentControl:{}\nreproKeys:{}\ndiscordPresence:{}\nsplitscreen:{}\nsplitscreenTwo:{}\nsplitscreenThree:{}\nsplitscreenNames:{}\nwheelCyclesListSettings:{}\nmusicOff:{}\nmusicPage:{}\ncosmeticsMine:{}\n{}cosmeticsHideFx:{}\ncosmeticsSolo:{}\n{}:{}\n{}:{}\n{}:{}\n",
bool_text(self.pack_browser),
bool_text(self.pregen),
bool_text(self.fullbright),
bool_text(self.dynamic_lights),
bool_text(self.zoom),
@@ -412,7 +430,7 @@ impl Extras {
// Written once the player chose.
self.cosmetics_others
.map_or(String::new(), |o| format!("cosmeticsOthers:{}\n", o.name())),
bool_text(self.cosmetics_auras),
bool_text(self.cosmetics_hide_fx),
bool_text(self.cosmetics_solo),
horizon_cosmetics::prefs::MARKS,
bool_text(self.horizon_marks),
@@ -421,32 +439,44 @@ impl Extras {
SKIN_LAYERS_KEY,
bool_text(self.three_d_skin_layers),
);
text.push_str(&format!("{EMOTE_KEY}:{}\n", self.emote_key));
self.pvp.serialize(&mut text);
text
}
/// Adopts the settings `options.txt` held before they moved here, while
/// this file (`own`) has no line of its own: 3D skin layers was an
/// `options.txt` line. Vanilla's `Options.save` drops lines it doesn't
/// this file (`own`) has no line of its own: 3D skin layers and the emote key were
/// `options.txt` lines. Vanilla's `Options.save` drops lines it doesn't
/// know, so it is read there once, the first start after the update.
pub fn read_old_options(&mut self, own: &str, options_txt: &str) {
fn line(text: &str) -> Option<&str> {
fn line<'a>(text: &'a str, name: &str) -> Option<&'a str> {
text.lines().find_map(|l| {
l.split_once(':')
.filter(|(key, _)| *key == SKIN_LAYERS_KEY)
.filter(|(key, _)| *key == name)
.map(|(_, value)| value)
})
}
if line(own).is_none()
&& let Some(value) = line(options_txt)
if line(own, SKIN_LAYERS_KEY).is_none()
&& let Some(value) = line(options_txt, SKIN_LAYERS_KEY)
{
self.three_d_skin_layers = value == "true";
}
// The emote key was a `key_key.emote` line of options.txt (#10092): a rebound key is kept.
if line(own, EMOTE_KEY).is_none()
&& let Some(value) = line(options_txt, OLD_EMOTE_LINE).map(str::trim)
&& value.starts_with("key.")
&& (value == "key.keyboard.unknown"
|| crate::keybinds::key_code(value).is_some()
|| crate::keybinds::mouse_button(value).is_some())
{
self.emote_key = value.to_owned();
}
}
/// Binds the extra key `name` (`SORT_KEY`); false for
/// another name (a vanilla mapping).
pub fn set_key(&mut self, name: &str, value: String) -> bool {
match name {
SORT_KEY => self.sort_key = value,
crate::pvp::HUD_EDITOR_KEY => self.pvp.editor_key = value,
_ => return false,
}
true
@@ -589,10 +619,11 @@ pub enum Item {
WheelCyclesSettings,
/// The Select Resource Packs screen's Add button (Modrinth).
PackBrowser,
Pregen,
/// Shown only while cosmetics are enabled (`horizon_cosmetics::enabled`).
CosmeticsMine,
CosmeticsOthers,
CosmeticsAuras,
CosmeticsHideFx,
CosmeticsSolo,
HorizonMarks,
HorizonMe,
@@ -602,14 +633,11 @@ pub enum Item {
/// The Extras page: headers (language keys) and items.
pub fn rows() -> Vec<Result<Item, &'static str>> {
use Item::*;
// Fullbright, Dynamic lights and Hide block-break particles change the picture: they
// are on the graphics screen's Quality page (`graphics_ui::rows`), not here.
let mut rows = vec![
Err("horizon.extras.header.lighting"),
Ok(Fullbright),
Ok(DynamicLights),
Err("horizon.extras.header.third_person"),
Ok(OwnNameTag),
Err("horizon.extras.header.particles"),
Ok(HideBlockParticles),
Err("horizon.extras.header.inventory"),
Ok(MouseTweaks),
Ok(MouseTweaksWheel),
@@ -618,6 +646,8 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
Err("horizon.extras.header.chat"),
Ok(ChatAnimation),
Ok(ChatIndicator),
Err("horizon.extras.header.world"),
Ok(Pregen),
Err("horizon.extras.header.multiplayer"),
Ok(AutoReconnect),
Err("horizon.extras.header.sound"),
@@ -633,7 +663,7 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
Ok(CosmeticsMine),
Ok(CosmeticsSolo),
Ok(CosmeticsOthers),
Ok(CosmeticsAuras),
Ok(CosmeticsHideFx),
Ok(HorizonMarks),
Ok(HorizonMe),
]);
@@ -664,9 +694,10 @@ impl Item {
Item::ChatIndicator => "horizon.extras.chat_indicator",
Item::WheelCyclesSettings => "horizon.extras.wheel_cycles_settings",
Item::PackBrowser => "horizon.extras.pack_browser",
Item::Pregen => "horizon.extras.pregen",
Item::CosmeticsMine => "horizon.extras.cosmetics_mine",
Item::CosmeticsOthers => "horizon.extras.cosmetics_others",
Item::CosmeticsAuras => "horizon.extras.cosmetics_auras",
Item::CosmeticsHideFx => "horizon.extras.cosmetics_hide_fx",
Item::CosmeticsSolo => "horizon.extras.cosmetics_solo",
Item::HorizonMarks => "horizon.extras.horizon_marks",
Item::HorizonMe => "horizon.extras.horizon_me",
@@ -694,11 +725,12 @@ impl Item {
Item::Splitscreen => "horizon.extras.splitscreen.tooltip",
Item::ChatAnimation => "horizon.extras.chat_animation.tooltip",
Item::ChatIndicator => "horizon.extras.chat_indicator.tooltip",
Item::WheelCyclesSettings => "horizon.extras.wheel_cycles_settings.tooltip",
Item::WheelCyclesSettings => "horizon.extras.wheel_cycles_list_settings.tooltip",
Item::PackBrowser => "horizon.extras.pack_browser.tooltip",
Item::Pregen => "horizon.extras.pregen.tooltip",
Item::CosmeticsMine => "horizon.extras.cosmetics_mine.tooltip",
Item::CosmeticsOthers => "horizon.extras.cosmetics_others.tooltip",
Item::CosmeticsAuras => "horizon.extras.cosmetics_auras.tooltip",
Item::CosmeticsHideFx => "horizon.extras.cosmetics_hide_fx.tooltip",
Item::CosmeticsSolo => "horizon.extras.cosmetics_solo.tooltip",
Item::HorizonMarks => "horizon.extras.horizon_marks.tooltip",
Item::HorizonMe => "horizon.extras.horizon_me.tooltip",
@@ -737,9 +769,10 @@ impl Item {
Item::Splitscreen => "Splitscreen",
Item::WheelCyclesSettings => "Scroll wheel changes settings",
Item::PackBrowser => "Resource pack browser",
Item::Pregen => "Chunk pregeneration",
Item::CosmeticsMine => "My cosmetics",
Item::CosmeticsOthers => "Other players' cosmetics",
Item::CosmeticsAuras => "Others' auras and trails",
Item::CosmeticsHideFx => "Hide other players' trails and auras",
Item::CosmeticsSolo => "In single player",
Item::HorizonMarks => "Horizon logos",
Item::HorizonMe => "Show me as Horizon",
@@ -758,7 +791,8 @@ impl Item {
Fullbright | DynamicLights | OwnNameTag | HideBlockParticles | MouseTweaks | Sort
| AutoReconnect | NoAi | AgentControl | ReproKeys | DiscordPresence | Splitscreen
| ChatAnimation | WheelCyclesSettings | MusicPage | PackBrowser | CosmeticsMine
| CosmeticsOthers | CosmeticsAuras | CosmeticsSolo | HorizonMarks | HorizonMe => {
| CosmeticsOthers | CosmeticsHideFx | CosmeticsSolo | HorizonMarks | HorizonMe
| Pregen => {
return None;
}
})
@@ -766,6 +800,9 @@ impl Item {
/// The English description: the fallback of [`Item::description_text`].
pub fn description(self) -> &'static str {
match self {
Item::Pregen => {
"Enables /pregen in your single-player and LAN worlds. With cheats enabled, use /pregen start to generate an area before exploring it. Does not enable the command on servers you join."
}
Item::Fullbright => "Show blocks and entities at full light, even in dark areas.",
Item::DynamicLights => {
"Torches and other light sources held, dropped or on fire light the blocks around them."
@@ -822,7 +859,9 @@ impl Item {
Item::CosmeticsOthers => {
"What other Horizon players wear: everything, only their name tag styles, or nothing. Hidden unless you own cosmetics, until you choose. Hidden, the game never asks what they wear."
}
Item::CosmeticsAuras => "Auras and trails other players wear. Off by default.",
Item::CosmeticsHideFx => {
"Other players' trails and auras stay hidden; their other cosmetics still show. Off by default."
}
Item::CosmeticsSolo => {
"Show your cosmetics and your name tag's badge in your single-player worlds too (your name tag with Own name tag). Off: only on servers."
}
@@ -860,7 +899,7 @@ impl Item {
| Item::PackBrowser => Some(Cost::None),
Item::CosmeticsMine
| Item::CosmeticsOthers
| Item::CosmeticsAuras
| Item::CosmeticsHideFx
| Item::CosmeticsSolo
| Item::HorizonMarks
| Item::HorizonMe => Some(Cost::Low),
@@ -889,7 +928,8 @@ impl Item {
Item::Splitscreen => e.splitscreen,
Item::WheelCyclesSettings => e.wheel_cycles_settings,
Item::PackBrowser => e.pack_browser,
Item::CosmeticsAuras => e.cosmetics_auras,
Item::Pregen => e.pregen,
Item::CosmeticsHideFx => e.cosmetics_hide_fx,
Item::CosmeticsSolo => e.cosmetics_solo,
Item::HorizonMarks => e.horizon_marks,
Item::HorizonMe => e.horizon_listed,
@@ -947,13 +987,14 @@ impl Item {
Item::Splitscreen => e.splitscreen = !e.splitscreen,
Item::WheelCyclesSettings => e.wheel_cycles_settings = !e.wheel_cycles_settings,
Item::PackBrowser => e.pack_browser = !e.pack_browser,
Item::Pregen => e.pregen = !e.pregen,
Item::CosmeticsMine => e.cosmetics_mine = !e.cosmetics_mine,
Item::CosmeticsOthers => {
// From what the button shows; the result is the player's choice from now on.
let o = e.effective_others();
e.cosmetics_others = Some(if back { o.next().next() } else { o.next() });
}
Item::CosmeticsAuras => e.cosmetics_auras = !e.cosmetics_auras,
Item::CosmeticsHideFx => e.cosmetics_hide_fx = !e.cosmetics_hide_fx,
Item::CosmeticsSolo => e.cosmetics_solo = !e.cosmetics_solo,
Item::HorizonMarks => e.horizon_marks = !e.horizon_marks,
Item::HorizonMe => e.horizon_listed = !e.horizon_listed,
@@ -965,6 +1006,7 @@ impl Item {
pub fn key_name(self) -> Option<&'static str> {
match self {
Item::SortKey => Some(SORT_KEY),
Item::Pvp(crate::pvp::Opt::HudEditorKey) => Some(crate::pvp::HUD_EDITOR_KEY),
_ => None,
}
}
@@ -982,7 +1024,7 @@ mod tests {
..Extras::default()
};
assert_eq!(
(e.effective_others(), e.cosmetics_auras, e.cosmetics_mine),
(e.effective_others(), e.cosmetics_hide_fx, e.cosmetics_mine),
(Others::Shown, false, true)
);
Item::CosmeticsOthers.cycle(&mut e, false);
@@ -1041,15 +1083,25 @@ mod tests {
assert_eq!(hidden.effective_others(), Others::Hidden);
}
#[test]
fn a_saved_wheel_setting_from_before_the_default_changed_is_dropped() {
assert!(!Extras::parse("wheelCyclesSettings:true\n").wheel_cycles_settings);
let on = Extras {
wheel_cycles_settings: true,
..Extras::default()
};
assert!(Extras::parse(&on.serialize()).wheel_cycles_settings);
}
#[test]
fn everything_is_off_by_default_and_round_trips() {
let d = Extras::default();
assert!(!d.fullbright && !d.dynamic_lights);
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect);
assert!(!d.mouse_tweaks && !d.sort && !d.own_name_tag && !d.ui_sound_reserve);
assert!(!d.hide_block_particles);
assert!(!d.hide_block_particles && !d.pregen);
assert!(!d.music_page && d.music_off.is_empty());
assert!(d.discord_presence && d.wheel_cycles_settings);
assert!(d.discord_presence && !d.wheel_cycles_settings);
assert_eq!(Extras::parse(""), d);
assert_eq!(Extras::parse(&d.serialize()), d);
let mut e = d.clone();
@@ -1072,6 +1124,8 @@ mod tests {
e.minimap_rotate = true;
e.minimap_corner = Corner::BottomLeft;
e.auto_reconnect = true;
Item::Pregen.cycle(&mut e, false);
assert_eq!(Item::Pregen.switch(&e), Some(true));
Item::OwnNameTag.cycle(&mut e, false);
assert_eq!(Item::OwnNameTag.switch(&e), Some(true));
assert_eq!(Item::HideBlockParticles.switch(&e), Some(false));
@@ -1091,7 +1145,7 @@ mod tests {
Item::Splitscreen.cycle(&mut e, false);
assert_eq!(Item::Splitscreen.switch(&e), Some(true));
Item::WheelCyclesSettings.cycle(&mut e, false);
assert_eq!(Item::WheelCyclesSettings.switch(&e), Some(false));
assert_eq!(Item::WheelCyclesSettings.switch(&e), Some(true));
e.music_off = vec![
"minecraft:music/game/calm1".into(),
"minecraft:music.menu".into(),
+310 -28
View File
@@ -5795,6 +5795,31 @@ impl Renderer {
blocks.iter().map(move |block| (block, fully_inside))
})
}
/// The block entities of the sections a shader pack's shadow pass drew in the last frame
/// (`shadow_visible`), within the 64 blocks `visible_block_entities_in_frustum` keeps.
/// Our probe packs' Iris 1.11.7 shadow maps hold a block entity wherever the shadow pass
/// draws its section's terrain, whether or not the camera's view takes it in (#8464).
pub fn shadow_pass_block_entities(
&self,
camera: DVec3,
) -> impl Iterator<Item = &([i32; 3], u32)> + '_ {
block_entities_within_reach(
self.shadow_visible.iter().map(|v| v.key),
&self.block_entities,
camera,
self.layout.min_y(),
)
}
/// Whether a shader pack's shadow pass drew the section holding block `pos` in the last
/// frame (`shadow_pass_block_entities`).
pub fn shadow_pass_drew(&self, pos: [i32; 3]) -> bool {
let key = (
pos[0] >> 4,
(pos[1] - self.layout.min_y()) >> 4,
pos[2] >> 4,
);
self.shadow_visible.iter().any(|v| v.key == key)
}
/// Milliseconds since `key` was uploaded; a section not in `section_uploaded` is old.
fn section_elapsed_ms(&self, key: SectionKey, now: std::time::Instant) -> u64 {
self.section_uploaded.get(&key).map_or(u64::MAX, |t| {
@@ -6609,17 +6634,11 @@ impl Renderer {
if let Some(atlas) = &mut atlas {
atlas.separate_ao = self.separate_ao;
}
self.pack_material_atlases = atlas.as_ref().and_then(|_| {
self.pack_material_atlases = atlas.as_ref().and_then(|colour| {
let maps = self.pbr_maps.as_ref()?;
let make = |kind: usize, encoder: &mut wgpu::CommandEncoder| {
let arrays: Vec<_> = maps.iter().map(|pair| pair[kind].clone()).collect();
pack_atlas::PackAtlas::material(
&self.device,
encoder,
&arrays,
self.sprite_split,
layers,
)
colour.material_for(&self.device, encoder, &arrays, layers)
};
Some([make(0, &mut encoder)?, make(1, &mut encoder)?])
});
@@ -7635,20 +7654,20 @@ impl Renderer {
shadow_visible.clear();
if let Some(v) = &shadow_view {
let radius = (frame.detail_distance / 16.0) as i32;
let radius = v
.distance
.map_or(radius, |d| radius.min((d / 16.0).ceil() as i32));
let light = ShadowCull {
light: Frustum {
planes: frustum(v.cull),
},
light: shadow_box(v),
casters: v.view_casters.then(|| shadow_casters(cull_proj, v.light)),
reach: v.distance,
};
crate::spans::time("shadow visibility", || {
// Within the unculled distance every section, then those in the light's box.
if let Some(d) = v.unculled {
let all = Frustum {
planes: [glam::Vec4::W; 6],
let all = ShadowCull {
light: Frustum {
planes: [glam::Vec4::W; 6],
},
casters: None,
reach: v.distance,
};
let near = radius.min((d / 16.0).ceil() as i32);
self.sections.visible(
@@ -11390,24 +11409,46 @@ impl Cull for Frusta {
pub struct ShadowCull {
pub light: Frustum,
pub casters: Option<[Frustum; 2]>,
/// `shadowDistance × shadowDistanceRenderMul`: only what lies within this many blocks of the
/// camera along each axis, a cube around it. Our probe's Iris 1.11.7 maps keep the sections
/// whose box, grown by `SHADOW_CASTER_MARGIN` as for the casters, meets that cube (#8464):
/// out to its corners, and a section 1 block past its side but not one 1.5 blocks past.
pub reach: Option<f32>,
}
impl ShadowCull {
/// Whether the camera-relative box `min..max`, grown by the margin, meets (`whole`: lies
/// within) `reach`'s cube.
fn within_reach(&self, min: Vec3, max: Vec3, whole: bool) -> bool {
let (min, max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.reach.is_none_or(|d| {
if whole {
min.cmpge(Vec3::splat(-d)).all() && max.cmple(Vec3::splat(d)).all()
} else {
max.cmpge(Vec3::splat(-d)).all() && min.cmple(Vec3::splat(d)).all()
}
})
}
}
/// How far past a section's 16 blocks the shadow pass looks for what can shade the view: our
/// probes' Iris 1.11.7 maps keep the sections whose box, grown by this much on every side, meets
/// `shadow_casters`' shape. The 31 edge columns of 8 noon scenes allow only a growth of 1.12 to
/// 1.19 blocks (a fit, not Iris's code); with 1.15, 19 of our 20 scenes hold exactly Iris's
/// columns. Without it the edges of the wedge lose a column of terrain.
const SHADOW_CASTER_MARGIN: f32 = 1.15;
/// `shadow_casters`' shape. Over 76 scenes at fields of view 30 to 110, Iris keeps every section
/// that needs up to 1.1224 blocks and drops every one that needs 1.1252 or more (#8464): one
/// growth, whatever the field of view, of 9/8 (a fit, not Iris's code). Without it the edges of
/// the wedge lose a column of terrain.
const SHADOW_CASTER_MARGIN: f32 = 1.125;
impl Cull for ShadowCull {
fn intersects(&self, min: Vec3, max: Vec3) -> bool {
let (grown_min, grown_max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.light.intersects(min, max)
self.within_reach(min, max, false)
&& self.light.intersects(min, max)
&& self
.casters
.is_none_or(|c| c.iter().all(|f| f.intersects(grown_min, grown_max)))
}
fn contains(&self, min: Vec3, max: Vec3) -> bool {
let (grown_min, grown_max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.light.contains(min, max)
self.within_reach(min, max, true)
&& self.light.contains(min, max)
&& self
.casters
.is_none_or(|c| c.iter().all(|f| f.contains(grown_min, grown_max)))
@@ -11417,6 +11458,39 @@ impl Cull for ShadowCull {
self.casters.is_none()
}
}
/// The block entities of `sections` whose box, a block wider on every side, comes within the
/// 64 blocks block entities are drawn to (`Renderer::visible_block_entities_in_frustum`).
fn block_entities_within_reach<'a>(
sections: impl Iterator<Item = SectionKey> + 'a,
block_entities: &'a FxHashMap<SectionKey, Vec<([i32; 3], u32)>>,
camera: DVec3,
min_y: i32,
) -> impl Iterator<Item = &'a ([i32; 3], u32)> + 'a {
sections
.filter_map(move |key| {
let min = (DVec3::new(
f64::from(key.0 * 16 - 1),
f64::from(min_y + key.1 * 16 - 1),
f64::from(key.2 * 16 - 1),
) - camera)
.as_vec3();
let max = min + Vec3::splat(18.0);
let near = Vec3::ZERO.max(min).min(max).length_squared() <= 64.0 * 64.0;
near.then(|| block_entities.get(&key)).flatten()
})
.flatten()
}
/// The shadow camera's box that the shadow pass draws terrain in: the sides of `view.cull`, and
/// its near and far planes only with `depth_planes`.
fn shadow_box(view: &pack_post::ShadowView) -> Frustum {
let mut planes = frustum(view.cull);
if !view.depth_planes {
// `frustum`'s faces at depth 0 and 1 take in everything.
planes[4] = Vec4::W;
planes[5] = Vec4::W;
}
Frustum { planes }
}
/// Camera-relative clip planes (`Frustum`).
#[derive(Clone, Copy, Debug)]
pub struct Frustum {
@@ -12203,7 +12277,8 @@ mod tests {
}
}
/// Every WGSL shader file translates to HLSL as wgpu's DirectX 12 backend
/// writes it for FXC (shader model 5.1), entry point by entry point.
/// writes it for FXC (shader model 5.1), entry point by entry point, and
/// every shader the OpenGL backend runs also translates to GLSL.
#[test]
fn shaders_translate_to_hlsl_for_directx_12_and_glsl_for_opengl() {
fn wgsl_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
@@ -12253,6 +12328,14 @@ mod tests {
}
}
let mut glsl_checked = 0;
// Shaders the OpenGL backend runs must translate: skipping the ones
// that fail hides exactly the bug where a shader GL needs cannot
// compile (#9448).
let mut glsl_failed = Vec::new();
let mut translated = std::collections::HashSet::new();
// naga's GLSL writer gives an image one sampler, and the HUD's glint
// samples one image through two; one failed entry does not hide the rest.
let known_unsupported = [("hud.wgsl", "fs_cit_glint")];
for (path, text) in sources {
// entity.wgsl comes after the overlay's constants (entity_shader).
let module = naga::front::wgsl::parse_str(&text)
@@ -12266,6 +12349,48 @@ mod tests {
)
.validate(&module)
.unwrap_or_else(|e| panic!("{}: {e:?}", path.display()));
// A select between integer vectors on a vector of bools becomes GLSL's
// mix(uvec3, uvec3, bvec3) (GLSL 4.5 or EXT_shader_integer_mix). Old AMD OpenGL
// drivers (Radeon HD 7400M, driver 15.301) pick the float overload and refuse to
// compile the terrain shader (#9892). Scalar selects become `?:` and work everywhere.
let functions = module
.functions
.iter()
.map(|(handle, f)| (f, &info[handle]))
.chain(
module
.entry_points
.iter()
.enumerate()
.map(|(i, e)| (&e.function, info.get_entry_point(i))),
);
for (function, function_info) in functions {
for (handle, expression) in function.expressions.iter() {
let naga::Expression::Select {
condition, accept, ..
} = *expression
else {
continue;
};
let vector_of = |h: naga::Handle<naga::Expression>| match *function_info[h]
.ty
.inner_with(&module.types)
{
naga::TypeInner::Vector { scalar, .. } => Some(scalar.kind),
_ => None,
};
assert!(
vector_of(condition).is_none()
|| !matches!(
vector_of(accept),
Some(naga::ScalarKind::Uint | naga::ScalarKind::Sint)
),
"{} {:?}: select between integer vectors ({handle:?}): use scalar selects",
path.display(),
function.name
);
}
}
for entry in &module.entry_points {
let (module, info) = naga::back::pipeline_constants::process_overrides(
&module,
@@ -12311,11 +12436,18 @@ mod tests {
Default::default(),
)
.and_then(|mut w| w.write());
// Some shaders use features GLSL cannot express (depth textureLoad): GL does
// not run them. The ones it does run must translate, checked below.
if glsl_result.is_err() {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if let Err(e) = glsl_result {
if !known_unsupported.contains(&(name, entry.name.as_str())) {
glsl_failed.push(format!(
"{} {} (GLSL {version}): {e}",
path.display(),
entry.name
));
}
continue;
}
translated.insert((name.to_owned(), entry.name.clone()));
glsl_checked += 1;
assert!(
!glsl.contains("ARB_arrays_of_arrays"),
@@ -12326,6 +12458,19 @@ mod tests {
}
}
}
assert!(
glsl_failed.is_empty(),
"shaders the OpenGL backend runs must translate:\n{}",
glsl_failed.join("\n")
);
// These read the world's depth through `textureLoad`; before #9448 their
// depth binding could not translate, so TAA and the blit never came up.
for (file, entry) in [("world_post.wgsl", "fs_taa"), ("pack_post.wgsl", "fs_blit")] {
assert!(
translated.contains(&(file.to_owned(), entry.to_owned())),
"{file} {entry} must translate to GLSL"
);
}
assert!(glsl_checked >= 10, "{glsl_checked} GLSL translations");
}
#[test]
@@ -13317,6 +13462,7 @@ mod shadow_face_tests {
unculled: None,
every_face,
view_casters: true,
depth_planes: false,
}
}
@@ -13336,6 +13482,24 @@ mod shadow_face_tests {
mod shadow_caster_tests {
use super::*;
#[test]
fn the_shadow_pass_takes_the_block_entities_of_its_sections_within_64_blocks() {
// Sections 64 to 79 high (the world from -64): a chest in each of three. The shadow
// pass drew `near` and `far`; `left_out` lies as near but the pass didn't draw it, and
// `far`'s nearest block is 78.5 blocks away.
let (near, left_out, far) = ((0, 8, 0), (1, 8, 0), (5, 8, 0));
let mut block_entities = FxHashMap::default();
block_entities.insert(near, vec![([3, 70, 3], 7)]);
block_entities.insert(left_out, vec![([20, 70, 3], 7)]);
block_entities.insert(far, vec![([85, 70, 3], 7)]);
let camera = DVec3::new(0.5, 70.0, 0.5);
let drawn = [near, far].into_iter();
let taken: Vec<_> = block_entities_within_reach(drawn, &block_entities, camera, -64)
.copied()
.collect();
assert_eq!(taken, vec![([3, 70, 3], 7)]);
}
/// What the shadow pass keeps of a camera-relative section at `min`, the camera at the
/// origin looking along -X (yaw 90) with the scenes' 70 degree, 16:9 view, and the light in
/// direction `light`; the light's own box takes in everything.
@@ -13352,6 +13516,7 @@ mod shadow_caster_tests {
planes: [Vec4::W; 6],
},
casters: Some(shadow_casters(camera, light)),
reach: None,
};
let min = Vec3::from(min);
cull.intersects(min, min + 16.0)
@@ -13385,8 +13550,8 @@ mod shadow_caster_tests {
assert!(!kept_looking(down, Vec3::Y, [-32.0, 16.0, -96.0]));
}
/// Our probes' Iris 1.11.7 maps keep the sections whose box, grown by a margin of 1.12 to
/// 1.19 blocks, meets the shape (#8464): a camera at (13.5, 69.62, -13.5) under a noon sun with the scenes' flying
/// Our probes' Iris 1.11.7 maps keep the sections whose box, grown by a margin of 1.1224 to
/// 1.1252 blocks, meets the shape (#8464): a camera at (13.5, 69.62, -13.5) under a noon sun with the scenes' flying
/// field of view (77°).
#[test]
fn the_shadow_pass_keeps_a_margin_around_the_view() {
@@ -13398,6 +13563,7 @@ mod shadow_caster_tests {
planes: [Vec4::W; 6],
},
casters: Some(shadow_casters(camera, Vec3::Y)),
reach: None,
};
let min = Vec3::new(
column[0] * 16.0 - 13.5,
@@ -13412,6 +13578,42 @@ mod shadow_caster_tests {
assert!(!kept(7.5, [3.0, 0.0]));
}
/// With `shadowDistanceRenderMul`, our probe's Iris 1.11.7 maps keep the sections within
/// `shadowDistance × mul` of the camera along each axis, out to the cube's corners, and with
/// some slack (the camera at (13.5, 69.62, -13.5)):
/// - at 100 blocks, the column at chunk (7, 5), 98.5 and 93.5 blocks out (136 diagonally), and
/// the one at (-6, -7) are kept; the one at (8, -4), 114.5 out on x, is not;
/// - at 49.5 blocks, the column at (-2, -5), 50.5 out on z, is kept; at 49 it is not;
/// - at 50 blocks from a camera at y 151.62, the ground's sections 70 blocks below are not.
#[test]
fn the_shadow_distance_render_mul_keeps_a_cube() {
let kept = |camera: DVec3, reach: f32, keys: &[(i32, i32)]| {
let y = (64 - crate::chunk::MIN_Y) / 16;
let mut sections = resident::Resident::<()>::default();
for &(x, z) in keys {
sections.insert_with_bounds((x, y, z), (), None);
}
let cull = ShadowCull {
light: Frustum {
planes: [Vec4::W; 6],
},
casters: None,
reach: Some(reach),
};
let mut out = Vec::new();
sections.visible(camera, 12, &cull, |_| true, |_, _| false, &mut out);
let mut kept: Vec<_> = out.iter().map(|v| (v.key.0, v.key.2)).collect();
kept.sort_unstable();
kept
};
let ground = DVec3::new(13.5, 69.62, -13.5);
let columns = [(7, 5), (8, -4), (-6, -7)];
assert_eq!(kept(ground, 100.0, &columns), [(-6, -7), (7, 5)]);
assert_eq!(kept(ground, 49.5, &[(-2, -5)]), [(-2, -5)]);
assert_eq!(kept(ground, 49.0, &[(-2, -5)]), []);
assert_eq!(kept(DVec3::new(13.5, 151.62, -13.5), 50.0, &[(0, 0)]), []);
}
/// With the camera looking straight up under a noon sun, our probe's Iris 1.11.7 map holds
/// 7 columns there, which testing whole sections reproduces (a guess): the sections beside
/// the camera whose 16 blocks reach above it are kept, even where their terrain lies below
@@ -13439,6 +13641,7 @@ mod shadow_caster_tests {
let shadow = ShadowCull {
light: all,
casters: Some(shadow_casters(up, Vec3::Y)),
reach: None,
};
assert_eq!(
drawn(&|out| sections.visible(camera, 4, &shadow, |_| true, |_, _| false, out)),
@@ -13450,4 +13653,83 @@ mod shadow_caster_tests {
.is_empty()
);
}
/// Our probe pack's Iris 1.11.7 shadow maps, under a noon sun with `shadowDistance` 128, hold
/// the terrain at every depth along the light whatever planes the pack gives (#10403): from
/// a cave at y -7, the surface's sections ~70 blocks toward the light with `shadowNearPlane`
/// 0.05 and `shadowFarPlane` 256; from y 600, the ground ~535 blocks away with no planes set;
/// and both with the planes at 200 and 210. Only the box's sides cull.
#[test]
fn the_shadow_pass_draws_terrain_outside_the_pack_s_planes() {
let kept = |near: Option<f32>, far: Option<f32>, y: f64, min: [f32; 3], depth: bool| {
let shadow = horizon_shaders::Shadow {
distance: 128.0,
near,
far,
..horizon_shaders::Shadow::default()
};
let camera = DVec3::new(13.5, y + 1.62, -13.5);
let view = pack_post::ShadowView {
cull: pack_uniforms::shadow_culling_at(Vec3::Y, camera, &shadow),
light: Vec3::Y,
distance: None,
unculled: None,
every_face: true,
view_casters: false,
depth_planes: depth,
};
let cull = ShadowCull {
light: shadow_box(&view),
casters: None,
reach: None,
};
let min = Vec3::from(min);
cull.intersects(min, min + 16.0)
};
// The section holding the surface (y 64..80) above the cave, and the ground under y 600.
let above = [-8.0, 64.0 - (-7.0 + 1.62), -8.0];
let below = [-8.0, 64.0 - (600.0 + 1.62), -8.0];
assert!(kept(Some(0.05), Some(256.0), -7.0, above, false));
assert!(kept(None, None, 600.0, below, false));
assert!(kept(Some(200.0), Some(210.0), -7.0, above, false));
assert!(kept(Some(200.0), Some(210.0), 600.0, below, false));
// A section 200 blocks off to the side is still outside the box.
let side = [200.0, 0.0, -8.0];
assert!(!kept(Some(0.05), Some(256.0), -7.0, side, false));
// Horizon's own packs keep culling by their planes.
assert!(!kept(Some(0.05), Some(256.0), -7.0, above, true));
}
/// The margin doesn't follow the field of view: from the same camera under a noon sun, our
/// probe's Iris 1.11.7 maps keep a section that needs a growth of 1.1224 blocks at a field of
/// view of 70 (77° flying) and drop ones that need 1.1252 to 1.1422 at 50 (55° flying) and
/// 70 (#8464).
#[test]
fn the_shadow_pass_keeps_the_same_margin_at_every_field_of_view() {
let kept = |fov: f32, yaw: f32, pitch: f32, section: [f32; 3]| {
let camera = world_projection(fov * 1.1, 16.0 / 9.0, 1024.0)
* crate::camera::view_matrix(yaw, pitch);
let cull = ShadowCull {
light: Frustum {
planes: [Vec4::W; 6],
},
casters: Some(shadow_casters(camera, Vec3::Y)),
reach: None,
};
let min = Vec3::new(
section[0] * 16.0 - 13.5,
section[1] * 16.0 - 69.62,
section[2] * 16.0 + 13.5,
);
cull.intersects(min, min + 16.0)
};
// fov 70, yaw 159, pitch 20: (4, 4, -4) needs 1.1224 blocks; Iris keeps it.
assert!(kept(70.0, 159.0, 20.0, [4.0, 4.0, -4.0]));
// fov 70, yaw 247.5: (1, 4, 0) needs 1.1253; Iris drops it.
assert!(!kept(70.0, 247.5, 0.0, [1.0, 4.0, 0.0]));
// fov 50, yaw 339, pitch -20: (3, 4, -1) needs 1.1252; looking south, (-2, 3, 0) needs
// 1.1422. Iris drops both.
assert!(!kept(50.0, 339.0, -20.0, [3.0, 4.0, -1.0]));
assert!(!kept(50.0, 0.0, 0.0, [-2.0, 3.0, 0.0]));
}
}
+2 -2
View File
@@ -220,7 +220,7 @@ impl Cull {
/// write storage.
pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Option<DepthTest> {
let depth_test = match adapter.get_info().backend {
wgpu::Backend::Vulkan
wgpu::Backend::Vulkan | wgpu::Backend::Gl
if device
.features()
.contains(wgpu::Features::SHADER_EARLY_DEPTH_TEST) =>
@@ -287,7 +287,7 @@ impl Cull {
0,
fragment,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
@@ -114,8 +114,10 @@ fn see(t: u32) {
}
}
// Phase 1's depth, where the test runs in the shader (gfx/cull.rs).
@group(1) @binding(0) var depth: texture_depth_2d;
// Phase 1's depth, where the test runs in the shader (gfx/cull.rs). A depth
// view bound as an unfilterable float: naga's GLSL backend cannot `textureLoad`
// a depth texture, and the texel is the same value.
@group(1) @binding(0) var depth: texture_2d<f32>;
// The world pass's reversed depth test, greater or equal passing, made here:
// where it cannot be forced before a shader that writes storage, a fragment
@@ -123,7 +125,7 @@ fn see(t: u32) {
// runs only for the fragments that pass it.
@fragment
fn fs_box(in: Box) {
if in.position.z >= textureLoad(depth, vec2<u32>(in.position.xy), 0) {
if in.position.z >= textureLoad(depth, vec2<u32>(in.position.xy), 0).r {
see(in.test);
}
}
@@ -52,7 +52,9 @@ struct Params {
@group(0) @binding(0) var<uniform> params: Params;
@group(0) @binding(1) var linear_clamp: sampler;
@group(0) @binding(2) var input_depth: texture_depth_2d;
// A depth view bound as unfilterable float: naga's GLSL backend cannot
// `textureLoad` a depth texture, and the texel is the same value.
@group(0) @binding(2) var input_depth: texture_2d<f32>;
@group(0) @binding(3) var current_color: texture_2d<f32>;
@group(0) @binding(4) var previous_color: texture_2d<f32>;
@group(0) @binding(5) var dilated_depth_out: texture_storage_2d<r32float, write>;
@@ -333,7 +335,7 @@ fn load_input_depth(p: vec2<i32>) -> f32 {
if !is_on_screen(p, params.render_size) {
return 0.0;
}
return textureLoad(input_depth, p, 0);
return textureLoad(input_depth, p, 0).r;
}
@compute @workgroup_size(8, 8)
@@ -12,7 +12,9 @@ struct Params {
};
@group(0) @binding(0) var<uniform> params: Params;
@group(0) @binding(1) var depth: texture_depth_2d;
// A depth view bound as unfilterable float: naga's GLSL backend cannot
// `textureLoad` a depth texture, and the texel is the same value.
@group(0) @binding(1) var depth: texture_2d<f32>;
@group(0) @binding(2) var atlas: texture_2d<f32>;
@group(0) @binding(3) var atlas_sampler: sampler;
@@ -38,7 +40,7 @@ struct Out {
// xy: the motion vector in UV (to where the pixel was last frame, FSR's convention), z: 1.
@fragment fn fs_motion(in: Out) -> @location(0) vec4<f32> {
let stored = textureLoad(depth, vec2<i32>(in.clip.xy), 0);
let stored = textureLoad(depth, vec2<i32>(in.clip.xy), 0).r;
let tolerance = stored * 1e-3 + 1e-7;
// Not what the world shows here: a transparent texel, or behind something.
if in.translucent != 0u {
@@ -368,6 +368,7 @@ impl NativeFrame {
unculled: None,
every_face: false,
view_casters: false,
depth_planes: true,
})
}
@@ -1172,6 +1173,14 @@ pub fn frame_inputs(
let k = super::native_shadow::distortion(s.distance, s.resolution);
2.0 * s.distance / s.resolution.max(1) as f32 * (1.0 - k)
}),
// Shader API 0.2's display fields, which 0.1 packs don't declare: SDR's values, also
// with HDR on, until HDR output is served for 0.2 packs.
hdr: 0,
headroom: 1.0,
paper_white: 80.0,
peak: 80.0,
black_level: 0.0,
padding: [0; 3],
}
}
@@ -30,6 +30,7 @@ struct Stitched {
/// Each layer's sprite at the first level: its top left corner and its side.
rects: Vec<[u32; 3]>,
padding: u32,
material: bool,
pipeline: wgpu::RenderPipeline,
/// One per sprite array.
groups: Vec<wgpu::BindGroup>,
@@ -66,10 +67,19 @@ fn vs(@builtin(vertex_index) v: u32, @location(0) rect: vec4<i32>, @location(1)
out.source = source.xy;
return out;
}
fn sprite_texel(in: Out) -> vec2<i32> {
return clamp(vec2<i32>(floor(in.position.xy)) - in.rect.xy, vec2(0), vec2(in.rect.z - 1));
}
@fragment
fn fs(in: Out) -> @location(0) vec4<f32> {
let texel = clamp(vec2<i32>(floor(in.position.xy)) - in.rect.xy, vec2(0), vec2(in.rect.z - 1));
return textureLoad(sprites, texel, i32(in.source.x), i32(in.source.y));
return textureLoad(sprites, sprite_texel(in), i32(in.source.x), i32(in.source.y));
}
@fragment
fn fs_material(in: Out) -> @location(0) vec4<f32> {
let texel = sprite_texel(in);
let edge = i32(textureDimensions(sprites, 0).x);
let sampled = min((texel * 2 + 1) * edge / (2 * in.rect.z), vec2(edge - 1));
return textureLoad(sprites, sampled, i32(in.source.x), i32(in.source.y));
}
"#;
@@ -210,14 +220,72 @@ impl PackAtlas {
stitch_mip_level(&sides, mip_option).min(array_levels.saturating_sub(deepest + 1));
let max = device.limits().max_texture_dimension_2d;
let layout = stitch::stitch(&sides, mip, anisotropy_bit, max)?;
let rects = layout
.holders
.iter()
.zip(&sides)
.map(|(&[x, y], &side)| [x + layout.padding, y + layout.padding, side])
.collect();
Some(Self::with_rects(
device,
encoder,
arrays,
split,
sprite,
[layout.width.max(1), layout.height.max(1)],
rects,
layout.padding,
mip + 1,
false,
))
}
/// Companion maps use the colour atlas's coordinates, not a second packing.
pub fn material_for(
&self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
arrays: &[wgpu::Texture],
layers: u32,
) -> Option<Self> {
let Some(stitched) = &self.stitched else {
return Self::material(device, encoder, arrays, self.split, layers);
};
Some(Self::with_rects(
device,
encoder,
arrays,
self.split,
arrays[0].width(),
self.size(),
stitched.rects.clone(),
stitched.padding,
1,
true,
))
}
#[allow(clippy::too_many_arguments)]
fn with_rects(
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
arrays: &[wgpu::Texture],
split: u32,
sprite: u32,
size: [u32; 2],
rects: Vec<[u32; 3]>,
padding: u32,
levels: u32,
material: bool,
) -> Self {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Shader pack block atlas"),
size: wgpu::Extent3d {
width: layout.width.max(1),
height: layout.height.max(1),
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
mip_level_count: mip + 1,
mip_level_count: levels,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
@@ -268,7 +336,7 @@ impl PackAtlas {
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs"),
entry_point: Some(if material { "fs_material" } else { "fs" }),
compilation_options: Default::default(),
targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())],
}),
@@ -293,12 +361,6 @@ impl PackAtlas {
})
})
.collect();
let rects = layout
.holders
.iter()
.zip(&sides)
.map(|(&[x, y], &side)| [x + layout.padding, y + layout.padding, side])
.collect::<Vec<_>>();
let layers = rects.len() as u32;
let atlas = Self {
texture,
@@ -309,13 +371,14 @@ impl PackAtlas {
separate_ao: false,
stitched: Some(Stitched {
rects,
padding: layout.padding,
padding,
material,
pipeline,
groups,
}),
};
atlas.copy(device, encoder, arrays, 0..layers);
Some(atlas)
atlas
}
/// Whether the sprites keep their own sizes ([`PackAtlas::stitched`]).
@@ -425,7 +488,11 @@ impl PackAtlas {
rect: [x, y, side, stitched.padding].map(|v| (v >> level) as i32),
source: [
layer % self.split,
(self.sprite / side).ilog2() + level,
if stitched.material {
0
} else {
(self.sprite / side).ilog2() + level
},
size[0],
size[1],
],
@@ -563,7 +630,7 @@ impl PackAtlas {
"layout(set = 1, binding = 0) readonly buffer HzBlockSlots { uint hz_block_slots[]; };\n\
layout(set = 1, binding = 1) readonly buffer HzSlotOrigins { vec4 hz_slot_origins[]; };\n",
);
// Of each sprite layer, `mc_Entity` (id, then 1 for fluids or -1) and
// Of each sprite layer, `mc_Entity` (id, then 1 for fluids or 0) and
// `at_midBlock.w` (its block's light), the game's table; and the arena page's
// vertices (`TerrainVertex`, six words each).
declarations.push_str(
@@ -610,13 +677,17 @@ impl PackAtlas {
// A vertex's place in its section goes down to the 32768th of a block below it: read back
// with a probe pack of ours, Iris 1.11.7's terrain `gl_Vertex` has that for every position
// we read (water tops at 8/9 - 0.001, plants' offsets), on all three axes (#8464). A fit,
// not Iris's code. Whole and half blocks, and every 1/16, are on that grid already.
// not Iris's code. Whole and half blocks, and every 1/16, are on that grid already. A place
// up to 1/32 of a 32768th (one float step below 16) under a grid line is on it: plants whose
// random offset is 9/15 of a block read exactly on a half block in Iris, and a 32768th
// under it in Horizon (our guess, not tested: Horizon's float sum lands just under the
// line) (#8464). Also a fit.
let body = format!(
" vec4 hz_origin = {origin};\n \
uint hz_layer = hz_v_layer & 32767u;\n \
{cell}\
hz_scale = vec2({:?}, {:?}) * {side};\n \
hz_Vertex = vec4(floor(hz_v_pos * 32768.0) / 32768.0 + hz_origin.xyz, 1.0);\n \
hz_Vertex = vec4(floor(hz_v_pos * 32768.0 + 0.03125) / 32768.0 + hz_origin.xyz, 1.0);\n \
hz_uv_scale = hz_origin.w > 0.0 ? uintBitsToFloat(floatBitsToUint(hz_origin.w) & 0xff800000u) : fract(abs(hz_origin.w));\n \
hz_mid = vec2(0.5);\n \
hz_MultiTexCoord0 = vec4((hz_cell + clamp(vec2(hz_v_uv) * hz_uv_scale, 0.0, 1.0)) * hz_scale, 0.0, 1.0);\n \
@@ -637,7 +708,7 @@ impl PackAtlas {
let entity = if flat {
"vec4(float(hz_block_ids[3u * hz_layer]), float(hz_block_ids[3u * hz_layer + 1u]), 0.0, 0.0)"
} else {
"vec4(-1.0, -1.0, 0.0, 0.0)"
"vec4(-1.0, 0.0, 0.0, 0.0)"
};
// The block a face belongs to: half a block behind its centre (the quad's diagonal);
// w, the light it gives (Iris's `BLOCK_EMISSION_ATTRIBUTE`, 0 to 15).
@@ -890,6 +961,144 @@ mod tests {
assert_eq!([at(9, 5), at(8, 4), at(10, 6)], [[100, 0, 0, 255]; 3]);
}
fn material_fixture(animated: bool) {
let instance = crate::gfx::test_gpu::instance();
// No adapter (a CI runner without a GPU): skip, as the module's other readback tests do.
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
return;
};
let (device, queue) =
pollster::block_on(adapter.request_device(&Default::default())).unwrap();
let colour_array = upscaled_array(&device, &queue, &[2, 4, 1]);
let mut encoder = device.create_command_encoder(&Default::default());
let colour = PackAtlas::stitched(
&device,
&mut encoder,
&[colour_array],
3,
4,
&[2, 4, 1],
0,
0,
)
.unwrap();
for kind in 0..2 {
// Different source resolution, with encoded channel boundaries and defaults.
let markers = if kind == 0 {
[
[128, 126, 255, 19],
crate::sprites::FLAT_NORMAL,
[130, 125, 254, 21],
]
} else {
[
[17, 240, 65, 255],
[18, 0, 66, 0],
crate::sprites::NO_SPECULAR,
]
};
let pixels: Vec<_> = markers.iter().flat_map(|m| m.repeat(4)).collect();
let array = wgpu::util::DeviceExt::create_texture_with_data(
&device,
&queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 2,
height: 2,
depth_or_array_layers: 3,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&pixels,
);
let arrays = [array];
let material = colour
.material_for(&device, &mut encoder, &arrays, 3)
.unwrap();
assert_eq!(material.size(), [16, 8]);
assert_eq!(material.rects_table(), colour.rects_table());
assert_eq!(material.texture.mip_level_count(), 1);
queue.submit([encoder.finish()]);
encoder = device.create_command_encoder(&Default::default());
let changed = [243, 1, 229, 0];
if animated {
// Alter every source layer, but copy only the animated layer.
queue.write_texture(
arrays[0].as_image_copy(),
&changed.repeat(12),
wgpu::TexelCopyBufferLayout {
bytes_per_row: Some(8),
rows_per_image: Some(2),
offset: 0,
},
arrays[0].size(),
);
material.copy(&device, &mut encoder, &arrays, [0]);
}
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 256 * 8,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
material.texture.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &read,
layout: wgpu::TexelCopyBufferLayout {
bytes_per_row: Some(256),
..Default::default()
},
},
material.texture.size(),
);
queue.submit([encoder.finish()]);
encoder = device.create_command_encoder(&Default::default());
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let data = read.slice(..).get_mapped_range().unwrap();
// Independent, hand-worked colour rectangles, including all padding pixels.
for (layer, [x, y, side]) in [[9usize, 1, 2], [1, 1, 4], [9, 5, 1]]
.into_iter()
.enumerate()
{
let expected = if animated && layer == 0 {
changed
} else {
markers[layer]
};
for py in y - 1..=y + side {
for px in x - 1..=x + side {
let at = py * 256 + px * 4;
assert_eq!(
&data[at..at + 4],
&expected,
"kind={kind}, layer={layer}, ({px},{py})"
);
}
}
}
}
queue.submit([encoder.finish()]);
}
#[test]
fn stitched_material_maps_share_colour_rectangles() {
material_fixture(false);
}
#[test]
fn animated_stitched_material_updates_only_its_rectangle() {
material_fixture(true);
}
#[test]
fn terrain_inputs_respects_separate_ao() {
let instance = crate::gfx::test_gpu::instance();
@@ -174,7 +174,8 @@ fn flat_draws_map_uvs_onto_a_stitched_sprite() {
/// Read back with a probe pack of ours, Iris 1.11.7's terrain `gl_Vertex` (camera on the block
/// grid) puts a water top, 8/9 - 0.001 of a block up, at 29094/32768, and plants offset by 13/15
/// and 0.1 of a block at 28398/32768 and 3276/32768 (#8464): each 32768th below the position.
/// Whole blocks and sixteenths stay where they are.
/// Whole blocks and sixteenths stay where they are, and so does a place float rounding put a hair
/// below a grid line: Iris reads plants offset by 9/15 exactly on a half block.
#[test]
fn terrain_vertices_go_down_to_the_32768th_below_them() {
let instance = crate::gfx::test_gpu::instance();
@@ -204,6 +205,15 @@ fn terrain_vertices_go_down_to_the_32768th_below_them() {
([0.1, water, 13.0 / 15.0], [3276.0, 29094.0, 28398.0]),
([13.0 / 15.0, 0.1, water], [28398.0, 3276.0, 29094.0]),
([1.0, 0.5, 15.9375], [32768.0, 16384.0, 522240.0]),
// One float step below 1, 0.5 and 9.5.
(
[
1.0 - f32::EPSILON / 2.0,
0.5 - f32::EPSILON / 4.0,
9.5 - f32::EPSILON * 8.0,
],
[32768.0, 16384.0, 311296.0],
),
];
let vertices: Vec<_> = cases
.iter()
@@ -16,14 +16,16 @@ const MAPPED: u8 = 3;
const ROW: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
const SHADER: &str = "
@group(0) @binding(0) var depth: texture_depth_2d;
// A depth view bound as unfilterable float: naga's GLSL backend cannot
// `textureLoad` a depth texture, and the texel is the same value.
@group(0) @binding(0) var depth: texture_2d<f32>;
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
return vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0);
}
@fragment fn fs() -> @location(0) vec4<f32> {
let centre = vec2<i32>(textureDimensions(depth) / 2u);
return vec4<f32>(textureLoad(depth, centre, 0), 0.0, 0.0, 1.0);
return vec4<f32>(textureLoad(depth, centre, 0).r, 0.0, 0.0, 1.0);
}
";
@@ -64,7 +66,7 @@ impl CenterDepth {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
+208 -51
View File
@@ -40,6 +40,9 @@ mod higher_shadowcolor_tests;
#[cfg(test)]
mod single_side_tests;
#[cfg(test)]
mod undrawn_terrain_tests;
#[cfg(test)]
mod shadow_faces_tests;
@@ -55,6 +58,9 @@ mod custom_type_tests;
#[cfg(test)]
mod sky_depth_tests;
#[cfg(test)]
mod translucent_color_tests;
/// The texture behind a pack sampler name.
#[derive(Clone, Copy, PartialEq)]
enum Source {
@@ -111,6 +117,10 @@ enum SamplerKind {
Nearest,
Repeat,
NearestRepeat,
/// The block atlas: nearest texels, blended between the two nearest levels.
Atlas,
/// colortex buffers: linear, blended between the two nearest levels.
Buffer,
Comparison,
}
@@ -120,15 +130,15 @@ impl SamplerKind {
Source::Color(_) | Source::ShadowColor(_) | Source::Dummy if !filtering => {
Self::Nearest
}
// shadowtex0/1 through a plain sampler: linear, as Iris 1.11.7 reads them, when the
// device filters their copies (`ShadowTargets::linear`).
Source::ShadowDepth(_, false) if filtering => Self::Linear,
Source::Depth | Source::Depth1 | Source::Depth2 | Source::ShadowDepth(_, false) => {
Self::Nearest
}
Source::Noise => Self::Repeat,
Source::Shadow | Source::ShadowDepth(_, true) => Self::Comparison,
// Blocks look as the game draws them: nearest texels.
// Blocks look as the game draws them: nearest texels. Between levels, Iris 1.11.7
// blends `gtexture`'s two nearest (our probe packs, #9307: a read at level 1.25 is
// levels 1 and 2 mixed 3:1).
Source::Atlas if filtering => Self::Atlas,
Source::Atlas | Source::Normals | Source::Specular => Self::NearestRepeat,
Source::Image(_) if filtering => Self::Linear,
Source::Image(_) => Self::Nearest,
@@ -138,15 +148,18 @@ impl SamplerKind {
(true, false) => Self::Repeat,
(false, false) => Self::NearestRepeat,
},
Source::Color(_) | Source::ShadowColor(_) | Source::Dummy | Source::Lightmap => {
Self::Linear
}
// Iris 1.11.7 blends a buffer's two nearest mipmap levels (our probe packs, #9307:
// every colortex read at levels 1.25 and 2.5 in composite and final).
Source::Color(_) => Self::Buffer,
Source::ShadowColor(_) | Source::Dummy | Source::Lightmap => Self::Linear,
}
}
fn binding_type(self) -> wgpu::SamplerBindingType {
match self {
Self::Linear | Self::Repeat => wgpu::SamplerBindingType::Filtering,
Self::Linear | Self::Repeat | Self::Atlas | Self::Buffer => {
wgpu::SamplerBindingType::Filtering
}
Self::Nearest | Self::NearestRepeat => wgpu::SamplerBindingType::NonFiltering,
Self::Comparison => wgpu::SamplerBindingType::Comparison,
}
@@ -369,6 +382,8 @@ struct Pass {
writes: Vec<(u32, usize)>,
/// Buffers flipped after the pass.
flip: u16,
/// `hz_depth_linear`: which of the depth samplers a plain sampler reads filter.
depth_linear: [f32; 4],
/// Buffers sampled, for the bind group cache key.
reads: u16,
/// shadowcolor buffers sampled by a program of the other buffers.
@@ -429,6 +444,14 @@ struct Mips {
levels: Vec<(wgpu::TextureView, wgpu::BindGroup)>,
}
/// The picture a pack's `final` draws at the world's size while the window is another: it is
/// copied onto the window once, after the pack's passes, as the game's own post pass does
/// without a pack.
struct FinalTarget {
size: [u32; 2],
view: wgpu::TextureView,
}
struct Targets {
size: [u32; 2],
/// A and B of each buffer used.
@@ -460,7 +483,7 @@ pub(super) struct World<'a> {
pub lightmap: wgpu::TextureView,
/// Terrain's geometry, when the pack draws it.
pub terrain: Option<Geometry<'a>>,
/// Of each block sprite layer, `mc_Entity` (id, then 1 for fluids or -1) and `at_midBlock.w`
/// Of each block sprite layer, `mc_Entity` (id, then 1 for fluids or 0) and `at_midBlock.w`
/// (its block's light): three values a layer.
pub block_ids: &'a [i32],
/// The atlas of the sun and moon's sprites.
@@ -538,6 +561,10 @@ pub struct PackPost {
terrain_cutout: Option<Pass>,
/// What draws translucent terrain (`gbuffers_water` or its fallback), after `deferred`.
water: Option<Pass>,
/// The pack has no program for solid and cutout terrain, or for translucent terrain:
/// nothing draws it (`horizon_shaders::Post::terrain_undrawn`).
terrain_undrawn: bool,
water_undrawn: bool,
/// What draws the sky (`gbuffers_skybasic` or its fallback), before terrain, and its vertices.
sky: Option<Sky>,
/// What draws entities and block entities, after terrain, and their vertices.
@@ -647,6 +674,9 @@ pub struct PackPost {
nearest: wgpu::Sampler,
repeat: wgpu::Sampler,
nearest_repeat: wgpu::Sampler,
atlas_sampler: wgpu::Sampler,
/// colortex buffers' (`SamplerKind::Buffer`).
buffer_sampler: wgpu::Sampler,
/// None when it would write nothing: colortex0 holds integers and there is no depth to copy
/// nor buffer to clear.
blit: Option<(wgpu::RenderPipeline, wgpu::BindGroupLayout)>,
@@ -659,6 +689,12 @@ pub struct PackPost {
blit_group: Option<([wgpu::TextureView; 2], wgpu::BindGroup)>,
/// Shows colortex0 when the pack has no `final` (OQ-5).
copy: (wgpu::RenderPipeline, wgpu::BindGroupLayout),
/// Copies the picture `final` drew at the world's size onto the window: no flip, it is
/// already in the screen's rows.
upscale: (wgpu::RenderPipeline, wgpu::BindGroupLayout),
/// The picture `final` draws while the world's size is not the window's.
final_target: Option<FinalTarget>,
screen: wgpu::TextureFormat,
uniforms: FrameUniforms,
}
@@ -777,6 +813,14 @@ fn fits(ty: &str, sample_type: wgpu::TextureSampleType) -> bool {
}
}
/// `hz_depth_linear` for a program: 1 for each of shadowtex0, shadowtex1, `shadow` and
/// `watershadow` whose depth filters (`linear`, bit n: shadowtex n). `shadow` is shadowtex1 in a
/// program that also declares `watershadow` (6.3).
fn depth_linear(interface: &horizon_shaders::Interface, linear: u8) -> [f32; 4] {
let watershadow = interface.samplers.iter().any(|s| s.name == "watershadow");
[0, 1, usize::from(watershadow), 0].map(|n| f32::from(linear >> n & 1))
}
fn source(name: &str, shadow_space: bool, shadow_pass: bool, watershadow: bool) -> Source {
let shadow_color = horizon_shaders::shadow_color(name);
let shadow_depth = match name {
@@ -1104,6 +1148,11 @@ pub(super) struct ShadowView {
/// maps fit keeping only those with `shadow.culling` unset (#8464): under a noon sun, only
/// the terrain above the ground the camera sees; with a low sun ahead, none behind the camera.
pub view_casters: bool,
/// Whether the projection's near and far planes in `cull` drop sections too. Our probes'
/// Iris 1.11.7 maps hold the terrain at every depth we put it along the light (from 535 blocks
/// beyond the shadow camera to about 120 before it), whatever `shadowNearPlane` and
/// `shadowFarPlane` the pack sets, or none (#10403): only its sides cull.
pub depth_planes: bool,
}
/// Set 3 of flat terrain, read by the vertex stage: the sprite layers' table (`mc_Entity`'s id
@@ -1190,7 +1239,7 @@ struct Resources<'a> {
/// The formats and dimensions of the images no `image.*` gives, for their stand-ins.
stand_ins: &'a std::cell::RefCell<Vec<(wgpu::TextureFormat, wgpu::TextureViewDimension)>>,
/// Bit n: shadowtex n read through a plain sampler filters linearly (`shadowtexNNearest`
/// unset, and the device filters `R32Float`).
/// unset): the translator's helpers blend a gather of it (`hz_depth_linear`).
shadow_linear: u8,
}
@@ -1234,8 +1283,9 @@ fn bindings(
let mut reads = 0u16;
let mut shadow_reads = 0u16;
let watershadow = interface.samplers.iter().any(|s| s.name == "watershadow");
// A gbuffers pass draws into its buffers and the depth buffer: reading them as well would
// be a feedback loop (undefined in GL, refused by wgpu), so those read a blank texture.
// Opaque gbuffers draws cannot sample their own attachments. Translucent draws can
// read colortex4 and above from the preceding deferred stage; those reads use a copy
// taken before the draw, so the sampled texture is never also an attachment.
let in_place = match geometry {
Some(_) => buffers.iter().fold(0u16, |m, &b| m | 1 << b),
None => 0,
@@ -1345,7 +1395,9 @@ fn bindings(
Source::Depth => geometry.is_some(),
// Translucent terrain reads the copy; opaque terrain would read itself.
Source::Depth1 | Source::Depth2 => group == Group::Gbuffers,
Source::Color(n) => in_place & 1 << n != 0,
Source::Color(n) => {
(group != Group::Translucent || n < 4) && in_place & 1 << n != 0
}
_ => false,
};
let mut sample_type = match src {
@@ -1355,7 +1407,6 @@ fn bindings(
Source::ShadowColor(n) => shadow
.and_then(|f| f[n].sample_type(None, Some(features)))
.unwrap_or(float),
Source::ShadowDepth(n, false) if pack.shadow_linear & 1 << n != 0 => float,
Source::Depth | Source::Depth1 | Source::Depth2 | Source::ShadowDepth(..) => {
wgpu::TextureSampleType::Float { filterable: false }
}
@@ -1817,6 +1868,7 @@ fn build_pass(
samplers,
writes,
flip,
depth_linear: depth_linear(interface, pack.shadow_linear),
shadow_reads,
written,
mipmaps: p.mipmaps,
@@ -1826,7 +1878,13 @@ fn build_pass(
ids: geometry.is_some_and(|g| g.ids.is_some()),
groups: HashMap::new(),
portal_groups: HashMap::new(),
copies: image_buffers(&images) & reads,
copies: (image_buffers(&images)
| if p.group == Group::Translucent {
written
} else {
0
})
& reads,
reads: reads | image_buffers(&images),
buffers: !interface.buffers.is_empty(),
images,
@@ -1948,6 +2006,7 @@ fn build_compute(
samplers,
writes: Vec::new(),
flip: 0,
depth_linear: depth_linear(interface, pack.shadow_linear),
copies: written & reads | before_colors,
reads: reads | written,
shadow_reads,
@@ -2130,13 +2189,9 @@ impl PackPost {
packed,
released: std::cell::Cell::new(("", 0)),
stand_ins: &stand_ins,
shadow_linear: if features.contains(wgpu::Features::FLOAT32_FILTERABLE) {
(0..2)
.filter(|&n| !shadow_config.nearest[n])
.fold(0, |m, n| m | 1 << n)
} else {
0
},
shadow_linear: (0..2)
.filter(|&n| !shadow_config.nearest[n])
.fold(0, |m, n| m | 1 << n),
};
let mut build = |mut p: horizon_shaders::PostProgram, geometry: Option<&Geometry<'_>>| {
let in_shadow = p.group.shadow();
@@ -2252,6 +2307,7 @@ impl PackPost {
cull: g.cull,
});
let split = post.terrain.is_some() && post.terrain_cutout.is_some();
let (terrain_undrawn, water_undrawn) = (post.terrain_undrawn, post.water_undrawn);
let mut terrain = post
.terrain
.zip(terrain_geometry.as_ref())
@@ -2595,13 +2651,6 @@ impl PackPost {
let depth1 = every_pass()
.flat_map(|p| &p.samplers)
.any(|s| matches!(s.source, Source::ShadowDepth(1, _)));
let linear = every_pass()
.flat_map(|p| &p.samplers)
.filter(|s| s.filtering)
.fold(0u8, |m, s| match s.source {
Source::ShadowDepth(n, false) => m | 1 << n,
_ => m,
});
let t = super::pack_shadow::ShadowTargets::new(
device,
&shadow_config,
@@ -2609,7 +2658,6 @@ impl PackPost {
colors,
shadow_doubled & colors,
depth1,
linear,
);
notes.push(format!(
"shadow map {0}x{0} over {2} blocks, sunPathRotation {3}, shadowcolor buffers {colors:#b} (two textures: {4:#b}){1}",
@@ -2722,7 +2770,7 @@ impl PackPost {
},
&[
texture_entry(0, float),
texture_entry(1, wgpu::TextureSampleType::Depth),
texture_entry(1, wgpu::TextureSampleType::Float { filterable: false }),
],
&blit_targets,
// GL's window depth, written for depthtex0 and the terrain's depth test.
@@ -2749,6 +2797,20 @@ impl PackPost {
&[target(screen)],
None,
);
let upscale = helper(
device,
"vs_screen",
"fs_copy",
&[
texture_entry(0, float),
entry(
2,
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
),
],
&[target(screen)],
None,
);
let filterable = |b: usize| {
formats[b].sample_type(None, Some(device.features()))
== Some(wgpu::TextureSampleType::Float { filterable: true })
@@ -2792,6 +2854,8 @@ impl PackPost {
terrain,
terrain_cutout,
water,
terrain_undrawn,
water_undrawn,
sky,
entities,
clouds,
@@ -2941,8 +3005,25 @@ impl PackPost {
),
repeat: sampler(device, wgpu::FilterMode::Linear, wgpu::AddressMode::Repeat),
nearest_repeat: sampler(device, wgpu::FilterMode::Nearest, wgpu::AddressMode::Repeat),
atlas_sampler: device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Shader pack atlas"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
}),
buffer_sampler: device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Shader pack buffers"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
}),
blit,
copy,
upscale,
final_target: None,
screen,
uniforms: {
let mut u = FrameUniforms::default();
u.atlas = world.atlas.map_or([0; 2], |a| a.1);
@@ -2985,7 +3066,8 @@ impl PackPost {
}
}
let fog = self.uniforms.fog();
// Our block members first (`hz_target`, `hz_fog_color`, `hz_fog`), then the pack's.
// Our block members first (`hz_target`, `hz_fog_color`, `hz_fog`, `hz_depth_linear`),
// then the pack's.
let ours = [
[
out[0] as f32,
@@ -2995,12 +3077,21 @@ impl PackPost {
],
fog[0].to_array(),
fog[1].to_array(),
pass.depth_linear,
];
let head: &[u8] = bytemuck::cast_slice(&ours);
let n = head.len().min(pass.block.len());
pass.block[..n].copy_from_slice(&head[..n]);
for (index, ty, offset) in &pass.uniforms {
if let Some(v) = index.and_then(|i| self.uniforms.values.get(i)) {
let Some((i, v)) = index.and_then(|i| Some((i, self.uniforms.values.get(i)?))) else {
continue;
};
// A built-in of another type keeps its initial value (0); custom uniforms were
// checked when the pass was built.
if pack_uniforms::NAMES
.get(i)
.is_none_or(|name| v.read_as(name, ty))
{
v.write(ty, &mut pass.block, *offset as usize);
}
}
@@ -3038,12 +3129,6 @@ impl PackPost {
shadow_color(i, usize::from(key & 1 << (32 + i) != 0))
.unwrap_or(&self.dummy)
}
Source::ShadowDepth(i, false) if s.filtering => {
match shadow.and_then(|t| t.linear[i].as_ref()) {
Some(v) => v,
None => &self.dummy,
}
}
Source::ShadowDepth(i, _) => match shadow {
Some(t) => match (i, &t.depth1) {
(1, Some(d)) => &d.1,
@@ -3144,6 +3229,8 @@ impl PackPost {
SamplerKind::Nearest => &self.nearest,
SamplerKind::Repeat => &self.repeat,
SamplerKind::NearestRepeat => &self.nearest_repeat,
SamplerKind::Atlas => &self.atlas_sampler,
SamplerKind::Buffer => &self.buffer_sampler,
SamplerKind::Comparison => shadow.map_or(&self.shadow.1, |t| &t.comparison),
};
entries.push(wgpu::BindGroupEntry {
@@ -3992,12 +4079,13 @@ impl PackPost {
},
every_face: true,
view_casters: true,
depth_planes: false,
})
}
/// Whether the pack draws terrain itself.
/// Whether the pack draws terrain itself, or has nothing draw it.
pub fn has_terrain(&self) -> bool {
self.terrain.is_some() || self.terrain_cutout.is_some()
self.terrain.is_some() || self.terrain_cutout.is_some() || self.terrain_undrawn
}
/// Whether the pack's shadow pass draws terrain (`shadow_view`).
@@ -4025,7 +4113,7 @@ impl PackPost {
/// Whether the pack draws translucent terrain itself.
pub fn has_water(&self) -> bool {
self.water.is_some()
self.water.is_some() || self.water_undrawn
}
/// The names of the programs that run, in order.
@@ -4077,6 +4165,14 @@ impl PackPost {
}
self.setup_pending = true;
self.rgb_unset = true;
// Free the old targets before making the new ones: a pack with large buffers can't
// hold both sets at once on a card it otherwise fits (a window resize ran out of video
// memory). The bind groups hold the old views too, and the GPU may still be using
// them, so wait for it; a resize is rare.
if self.targets.take().is_some() {
self.forget_groups();
let _ = device.poll(wgpu::PollType::wait_indefinitely());
}
let sizes: [[u32; 2]; BUFFERS] =
std::array::from_fn(|i| self.sizes[i].map_or(size, |s| s.resolve(size)));
let full_chain = |size: [u32; 2]| 32 - size[0].max(size[1]).max(1).leading_zeros();
@@ -4302,9 +4398,6 @@ impl PackPost {
TerrainList::ShadowTranslucent,
terrain,
);
if let Some(t) = &self.shadow_targets {
t.copy_linear(encoder);
}
let mut comp = std::mem::take(&mut self.shadow_comp);
for pass in &mut comp {
let mut compute = std::mem::take(&mut pass.compute);
@@ -4473,6 +4566,35 @@ impl PackPost {
terrain: &mut TerrainDraw<'_>,
) {
self.resize(device, size);
// A resolution scale leaves the picture smaller (or larger) than the window: the pack's
// `final` draws it at the picture's size, and one copy takes it to the window (#9291).
let final_view = if size != window && self.passes.iter().any(|p| p.group == Group::Final) {
if self.final_target.as_ref().is_none_or(|t| t.size != size) {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Shader pack final"),
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.screen,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
self.final_target = Some(FinalTarget {
size,
view: texture.create_view(&Default::default()),
});
}
self.final_target.as_ref().map(|t| t.view.clone())
} else {
self.final_target = None;
None
};
if let Some((layout, ids, rects)) = &self.block_ids {
// A page that grew has a new buffer.
self.page_groups
@@ -4509,10 +4631,8 @@ impl PackPost {
.get_or_insert_with(|| super::pack_center_depth::CenterDepth::new(device))
.collect(device);
self.uniforms.update(frame, inputs, size);
// Until the camera's biome is known, `smooth` waits for the world's values.
if !inputs.biome_known {
self.custom.restart_smoothing();
}
// `smooth` starts on the first frame that knows the camera's biome.
self.custom.world_frame(inputs.biome_known);
self.uniforms.eval_custom(&mut self.custom);
if self.targets.is_none() {
return;
@@ -4777,8 +4897,8 @@ impl PackPost {
self.mips_valid |= stale;
let final_pass = pass.group == Group::Final;
// A pass writing buffers of a size of their own draws at that size (they share it).
// `final` draws the picture at the world's size; a copy takes it to the window.
let out = match pass.writes.first() {
_ if final_pass => window,
Some(&(_, b)) => self.targets.as_ref().map_or(size, |t| t.sizes[b]),
None => size,
};
@@ -4801,7 +4921,7 @@ impl PackPost {
overwrite
};
if final_pass {
attachments.push(attach(screen, overwrite));
attachments.push(attach(final_view.as_ref().unwrap_or(screen), overwrite));
shown = true;
} else if pass.sink {
attachments.push(attach(&targets.sink, ops));
@@ -4884,6 +5004,31 @@ impl PackPost {
rp.set_pipeline(&self.copy.0);
rp.set_bind_group(0, &group, &[]);
rp.draw(0..3, 0..1);
} else if let Some(picture) = &final_view {
// The picture at the world's size onto the window: one upscale, smoothly.
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Shader pack final"),
layout: &self.upscale.1,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(picture),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&self.linear),
},
],
});
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Shader pack final"),
color_attachments: &[attach(screen, overwrite)],
timestamp_writes: self.timing.as_mut().and_then(|t| t.writes("final copy")),
..Default::default()
});
rp.set_pipeline(&self.upscale.0);
rp.set_bind_group(0, &group, &[]);
rp.draw(0..3, 0..1);
}
}
}
@@ -5569,8 +5714,20 @@ mod const_offset_tests;
#[cfg(test)]
mod integer_colortex0_tests;
#[cfg(test)]
mod atlas_mip_tests;
#[cfg(test)]
mod wrong_type_uniform_tests;
#[cfg(test)]
mod atlas_name_post_tests;
#[cfg(test)]
mod unknown_sampler_terrain_tests;
#[cfg(test)]
mod mipmap_box_tests;
#[cfg(test)]
mod colortex_mip_blend_tests;
@@ -9,7 +9,9 @@ fn vs_full(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
}
@group(0) @binding(0) var source: texture_2d<f32>;
@group(0) @binding(1) var world_depth: texture_depth_2d;
// A depth view read as an unfilterable float: naga's GLSL backend cannot
// `textureLoad` a depth texture, and the texel is the same either way.
@group(0) @binding(1) var world_depth: texture_2d<f32>;
struct World {
@location(0) color: vec4<f32>,
@@ -24,7 +26,7 @@ fn fs_blit(@builtin(position) p: vec4<f32>) -> World {
let at = vec2<i32>(i32(p.x), size.y - 1 - i32(p.y));
var out: World;
out.color = textureLoad(source, at, 0);
out.depth = 1.0 - textureLoad(world_depth, at, 0);
out.depth = 1.0 - textureLoad(world_depth, at, 0).r;
return out;
}
@@ -49,15 +51,51 @@ fn vs_uv(@builtin(vertex_index) i: u32) -> Full {
return Full(vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0), vec2<f32>(uv.x, 1.0 - uv.y));
}
// The screen's own rows: a picture a shader pack's `final` drew (not a GL-rows buffer).
@vertex
fn vs_screen(@builtin(vertex_index) i: u32) -> Full {
let uv = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
return Full(vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0), uv);
}
@fragment
fn fs_copy(v: Full) -> @location(0) vec4<f32> {
return textureSample(source, linear, v.uv);
}
// One level of a buffer's mip chain from the level above (6.1.7): the average of the 2×2
// texels under each destination texel, by one bilinear sample at their shared corner.
// One level of a buffer's mip chain from the level above (6.1.7): a box filter, the average
// of the texels under each destination texel (OpenGL 4.6, 8.14.4, recommends one). Along an
// even side a texel covers two of the level above; along an odd side of 2d + 1 texels, texel i
// covers 2 + 1 / d of them: 2i, 2i + 1 and 2i + 2, weighted d - i, d and i + 1 over 2d + 1.
// Every texel of the level above then counts as much, so a small bright spot keeps its share
// down to the last level, which is the buffer's mean.
fn down_weights(i: u32, side: u32) -> vec3<f32> {
if side == 1u {
return vec3<f32>(1.0, 0.0, 0.0);
}
if side % 2u == 0u {
return vec3<f32>(0.5, 0.5, 0.0);
}
let d = f32(side / 2u);
return vec3<f32>(d - f32(i), d, f32(i) + 1.0) / f32(side);
}
@fragment
fn fs_down(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {
let size = max(textureDimensions(source) / 2u, vec2<u32>(1u));
return textureSampleLevel(source, linear, p.xy / vec2<f32>(size), 0.0);
let above = textureDimensions(source);
let at = vec2<u32>(p.xy);
let wx = down_weights(at.x, above.x);
let wy = down_weights(at.y, above.y);
let first = vec2<i32>(at * 2u);
let last = vec2<i32>(above) - 1;
var sum = vec4<f32>(0.0);
for (var y = 0; y < 3; y++) {
for (var x = 0; x < 3; x++) {
let w = wx[x] * wy[y];
if w > 0.0 {
sum += w * textureLoad(source, min(first + vec2<i32>(x, y), last), 0);
}
}
}
return sum;
}
@@ -0,0 +1,108 @@
//! The block atlas is read with nearest texels, blended between the two nearest levels: our
//! probe packs (#9307) read `gtexture` in gbuffers_terrain, and the atlas as a custom texture in
//! composite, at levels 0.5 and 1.25 in Iris 1.11.7, and got the two nearest levels mixed.
use super::destination_tests::Fixture;
use super::*;
use std::io::{Cursor, Write};
const VERTEX: &str = "#version 120\nvarying vec2 uv;\nvoid main() { uv = gl_MultiTexCoord0.xy; gl_Position = ftransform(); }\n";
/// The atlas as composite's `noisetex`, read at levels 0.5 (red) and 0.25 (green).
fn pack() -> Post {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let mut add = |name: &str, source: &str| {
zip.start_file(name, zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(source.as_bytes()).unwrap();
};
add(
"shaders/shaders.properties",
"texture.composite.noisetex=minecraft:textures/atlas/blocks.png\n",
);
add("shaders/composite.vsh", VERTEX);
add(
"shaders/composite.fsh",
"#version 130\nuniform sampler2D noisetex;\nvoid main() {\n/* DRAWBUFFERS:0 */\n\
\x20 gl_FragData[0] = vec4(textureLod(noisetex, vec2(0.5), 0.5).r, textureLod(noisetex, vec2(0.5), 0.25).r, 0.0, 1.0);\n}\n",
);
let pack = horizon_shaders::Pack::from_zip_bytes(
"original-atlas-levels",
zip.finish().unwrap().into_inner(),
)
.unwrap();
let mut macros = horizon_shaders::Macros::standard();
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
horizon_shaders::load_post(&pack, "", &properties, &macros, &Default::default())
}
/// A 4x4 atlas whose first level is black and second white.
fn atlas(gpu: &Fixture) -> wgpu::TextureView {
let texture = gpu.device.create_texture(&wgpu::TextureDescriptor {
label: Some("Original two-level atlas"),
size: wgpu::Extent3d {
width: 4,
height: 4,
depth_or_array_layers: 1,
},
mip_level_count: 2,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
for (level, side, value) in [(0u32, 4u32, 0u8), (1, 2, 255)] {
gpu.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: level,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&[value, value, value, 255].repeat((side * side) as usize),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(side * 4),
rows_per_image: None,
},
wgpu::Extent3d {
width: side,
height: side,
depth_or_array_layers: 1,
},
);
}
texture.create_view(&Default::default())
}
#[test]
fn the_atlas_blends_its_two_nearest_levels() {
let Some(gpu) = Fixture::new() else { return };
// The pack reads no lightmap: any texture serves.
let lightmap = atlas(&gpu);
let mut post = PackPost::new(
&gpu.device,
&gpu.queue,
&gpu.adapter,
pack(),
wgpu::TextureFormat::Rgba8Unorm,
World {
atlas: Some((atlas(&gpu), [4, 4])),
material_maps: None,
lightmap,
terrain: None,
block_ids: &[],
sprite_rects: &[],
celestial: None,
gui_size: [16, 16],
clouds: None,
weather: false,
hand: false,
},
)
.expect("the pack runs");
for p in gpu.render(&mut post, [4, 4]) {
// Half of white, and a quarter (within the blend's 8-bit weight).
assert!(p[0].abs_diff(128) <= 2 && p[1].abs_diff(64) <= 2, "{p:?}");
}
}
@@ -0,0 +1,61 @@
//! A buffer's mipmaps are read blended between the two nearest levels: our probe packs (#9307)
//! read every colortex at levels 2.5 and 1.25 in composite and final, in Iris 1.11.7, and got the
//! two nearest levels mixed.
use super::destination_tests::Fixture;
use super::*;
use std::io::{Cursor, Write};
const VERTEX: &str = "#version 120\nvarying vec2 uv;\nvoid main() { uv=gl_MultiTexCoord0.xy; gl_Position=ftransform(); }\n";
/// composite writes 1.0 into the left half of a 4x4 colortex1 and 0 into the right half, so at
/// (0.25, 0.5) level 1 reads 1.0 and level 2 (1x1) the mean, 0.5. final shows the read at
/// level 1.5 in red and at level 1.25 in green.
fn pack() -> Post {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let mut add = |name: &str, source: &str| {
zip.start_file(
format!("shaders/{name}"),
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(source.as_bytes()).unwrap();
};
add("composite.vsh", VERTEX);
add(
"composite.fsh",
"#version 330 compatibility\n/*\nconst int colortex1Format = RGBA16F;\n*/\n\
/* RENDERTARGETS: 1 */\nlayout(location = 0) out vec4 o;\n\
void main() {\n o = vec4(gl_FragCoord.x < 2.0 ? 1.0 : 0.0, 0.0, 0.0, 1.0);\n}\n",
);
add("final.vsh", VERTEX);
add(
"final.fsh",
"#version 330 compatibility\n/*\nconst bool colortex1MipmapEnabled = true;\n*/\n\
uniform sampler2D colortex1;\n\
void main() {\n vec2 at = vec2(0.25, 0.5);\n\
gl_FragColor = vec4(textureLod(colortex1, at, 1.5).r, textureLod(colortex1, at, 1.25).r, 0.0, 1.0);\n}\n",
);
let pack = horizon_shaders::Pack::from_zip_bytes(
"original-colortex-mip-blend",
zip.finish().unwrap().into_inner(),
)
.unwrap();
let mut macros = horizon_shaders::Macros::standard();
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
let post = horizon_shaders::load_post(&pack, "", &properties, &macros, &Default::default());
assert_eq!(post.programs.len(), 2, "{:?}", post.notes);
post
}
#[test]
fn a_buffer_blends_its_two_nearest_levels() {
let Some(gpu) = Fixture::new() else { return };
let mut post = gpu.build(pack());
let pixels = gpu.render(&mut post, [4, 4]);
// Level 1.5: 1.0 and 0.5 mixed 1:1, 0.75; level 1.25: mixed 3:1, 0.875.
let [r, g, ..] = pixels[0];
assert!(
r.abs_diff(191) <= 2 && g.abs_diff(223) <= 2,
"levels 1.5 and 1.25: got red {r}, green {g}, expected 191 and 223"
);
}
@@ -653,15 +653,48 @@ pub(super) fn fixture_frame(hud: &HudBatch) -> Frame<'_> {
/// moved toward the next texel, times four (0 nearest, 255 linear). `nearest` is a line for
/// both stage files.
fn shadow_depth_filtering(nearest: &str) -> Option<Vec<[u8; 4]>> {
shadow_depth_reads(
nearest,
"float moved(sampler2D s, ivec2 t) {\n\
float a = texelFetch(s, t, 0).r;\n\
return (texture(s, (vec2(t) + vec2(0.75, 0.5)) / 16.0).r - a) * 16.0;\n\
}\n\
void main() {\n\
ivec2 t = ivec2(int(gl_FragCoord.x) % 15, 8);\n\
gl_FragColor = vec4(moved(shadowtex0, t) * 4.0, moved(shadowtex1, t) * 4.0, 0.0, 1.0);\n\
}\n",
)
}
/// `shadow_depth_filtering`'s shadow map read by `reads`: `final`'s code after its declarations
/// of shadowtex0 and shadowtex1.
fn shadow_depth_reads(nearest: &str, reads: &str) -> Option<Vec<[u8; 4]>> {
// The shadow map's depth runs from 0 at its left edge to 1 at its right.
let ramp = [
[-1., -1., 0.],
[1., -1., 0.],
[1., 1., 0.],
[-1., -1., 0.],
[1., 1., 0.],
[-1., 1., 0.],
];
shadow_depth_map_reads(
nearest,
reads,
"#version 120\nvoid main(){gl_Position=vec4(gl_Vertex.xy,gl_Vertex.x,1.0);}",
ramp,
)
}
/// A shadow map drawn by `shadow_vsh` from the two triangles `positions` (the rest keeps its
/// clear depth, the far plane), read by `reads` as in `shadow_depth_reads`.
fn shadow_depth_map_reads(
nearest: &str,
reads: &str,
shadow_vsh: &str,
positions: [[f32; 3]; 6],
) -> Option<Vec<[u8; 4]>> {
let gpu = Gpu::new()?;
if !gpu
.device
.features()
.contains(wgpu::Features::FLOAT32_FILTERABLE)
{
eprintln!("DEPTH_FIXTURE_NO_FLOAT32_FILTERABLE");
return None;
}
let color = gpu.texture(T::Rgba8Unorm);
let depth = gpu.texture(T::Depth32Float);
gpu.clear(&color, &depth, 0.0);
@@ -693,22 +726,10 @@ fn shadow_depth_filtering(nearest: &str) -> Option<Vec<[u8; 4]>> {
"final.fsh".into(),
format!(
"#version 330 compatibility\n{settings}\
uniform sampler2D shadowtex0;\nuniform sampler2D shadowtex1;\n\
float moved(sampler2D s, ivec2 t) {{\n\
float a = texelFetch(s, t, 0).r;\n\
return (texture(s, (vec2(t) + vec2(0.75, 0.5)) / 16.0).r - a) * 16.0;\n\
}}\n\
void main() {{\n\
ivec2 t = ivec2(int(gl_FragCoord.x) % 15, 8);\n\
gl_FragColor = vec4(moved(shadowtex0, t) * 4.0, moved(shadowtex1, t) * 4.0, 0.0, 1.0);\n\
}}\n"
uniform sampler2D shadowtex0;\nuniform sampler2D shadowtex1;\n{reads}"
),
),
// The shadow map's depth runs from 0 at its left edge to 1 at its right.
(
"shadow.vsh".into(),
"#version 120\nvoid main(){gl_Position=vec4(gl_Vertex.xy,gl_Vertex.x,1.0);}".into(),
),
("shadow.vsh".into(), shadow_vsh.into()),
(
"shadow.fsh".into(),
format!("#version 120\n{settings}void main(){{gl_FragData[0]=vec4(1.0);}}"),
@@ -740,14 +761,6 @@ fn shadow_depth_filtering(nearest: &str) -> Option<Vec<[u8; 4]>> {
inputs,
);
assert!(post.has_shadow(), "{:?}", post.notes);
let positions: [[f32; 3]; 6] = [
[-1., -1., 0.],
[1., -1., 0.],
[1., 1., 0.],
[-1., -1., 0.],
[1., 1., 0.],
[-1., 1., 0.],
];
let vertices = gpu
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
@@ -775,6 +788,58 @@ fn shadow_depth_is_read_linearly_through_a_plain_sampler() {
}
}
#[test]
fn shadow_depth_reads_filter_directly_and_with_a_texel_offset() {
// texture2D on the sampler itself, and textureOffset one texel to the right: both a quarter
// texel past a centre, so each moves a quarter of the way to the next texel.
let reads = "void main() {\n\
ivec2 t = ivec2(int(gl_FragCoord.x) % 14, 8);\n\
vec2 p = (vec2(t) + vec2(0.75, 0.5)) / 16.0;\n\
float a = texelFetch(shadowtex0, t, 0).r;\n\
float b = texelFetch(shadowtex1, t + ivec2(1, 0), 0).r;\n\
float r = (texture2D(shadowtex0, p).r - a) * 64.0;\n\
float g = (textureOffset(shadowtex1, p, ivec2(1, 0)).r - b) * 64.0;\n\
gl_FragColor = vec4(r, g, 0.0, 1.0);\n\
}\n";
if let Some(pixels) = shadow_depth_reads("", reads) {
all_pixels(&pixels, [255, 255, 0, 255], "shadowtex direct and offset");
}
}
#[test]
fn shadow_depth_filter_weights_are_256ths_as_in_our_iris_readings() {
// The map is at the far plane but for texel (8, 8), which is nearer. Reads between texels
// (7, 7) and (8, 8) give (8, 8)'s weight: Iris 1.11.7's filtered reads on our NVIDIA GPU
// fit weights of 1/256 along each axis, rounded half up, and a corner's product weight
// rounded half up to 1/256 (#8464). Red: a read a + 0.25/256 of the way along x only
// moves a/256 (77). Green: at (77.25, 77.25)/256 along both, (8, 8) weighs 23/256
// (77 × 77 / 256 = 23.16; exact weights would give 23.31).
let reads = "void main() {\n\
float far = texelFetch(shadowtex0, ivec2(7, 7), 0).r;\n\
float near = texelFetch(shadowtex0, ivec2(8, 8), 0).r;\n\
float f = 77.25 / 256.0;\n\
float along = texture(shadowtex0, vec2(7.5 + f, 8.5) / 16.0).r;\n\
float corner = texture(shadowtex0, vec2(7.5 + f, 7.5 + f) / 16.0).r;\n\
float x = (far - along) / (far - near) * 256.0;\n\
float w = (far - corner) / (far - near) * 256.0;\n\
gl_FragColor = vec4(abs(x - 77.0) < 0.01 ? 1.0 : 0.0,\n\
abs(w - 23.0) < 0.01 ? 1.0 : 0.0, 0.0, 1.0);\n\
}\n";
// Texel (8, 8) of the 16² map: x and y from 0 to 1/8 in clip space, depth 0.
let bump = [
[0., 0., -1.],
[0.125, 0., -1.],
[0.125, 0.125, -1.],
[0., 0., -1.],
[0.125, 0.125, -1.],
[0., 0.125, -1.],
];
let vsh = "#version 120\nvoid main(){gl_Position=vec4(gl_Vertex.xyz,1.0);}";
if let Some(pixels) = shadow_depth_map_reads("", reads, vsh, bump) {
all_pixels(&pixels, [255, 255, 0, 255], "shadowtex filter weights");
}
}
#[test]
fn shadowtex_nearest_settings_read_the_nearest_texel() {
for (line, expected) in [
@@ -0,0 +1,65 @@
//! A buffer's mip chain is a box filter of the level above, odd sides included, so a small
//! bright spot keeps its share of every level down to the last, the buffer's mean: OpenGL 4.6
//! (8.14.4) recommends a box filter for generated mipmaps, and Iris 1.11.7's colortex mipmaps
//! kept a 26x22-pixel spot of a 1280x720 buffer in its last level (probe packs of ours).
use super::destination_tests::Fixture;
use super::*;
use std::io::{Cursor, Write};
const VERTEX: &str = "#version 120\nvarying vec2 uv;\nvoid main() { uv=gl_MultiTexCoord0.xy; gl_Position=ftransform(); }\n";
/// composite writes 1.0 into one texel of colortex1, its top right corner, and 0 elsewhere;
/// final shows level 2 (the 1x1 level of a 5x3 buffer) in red and texel (1, 0) of level 1 (2x1)
/// in green, both scaled so that the box filter's values read 0.5.
fn pack() -> Post {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let mut add = |name: &str, source: &str| {
zip.start_file(
format!("shaders/{name}"),
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(source.as_bytes()).unwrap();
};
add("composite.vsh", VERTEX);
add(
"composite.fsh",
"#version 330 compatibility\n/*\nconst int colortex1Format = RGBA16F;\n*/\n\
/* RENDERTARGETS: 1 */\nlayout(location = 0) out vec4 o;\n\
void main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n\
o = vec4(p == ivec2(4, 2) ? 1.0 : 0.0, 0.0, 0.0, 1.0);\n}\n",
);
add("final.vsh", VERTEX);
add(
"final.fsh",
"#version 330 compatibility\n/*\nconst bool colortex1MipmapEnabled = true;\n*/\n\
uniform sampler2D colortex1;\n\
void main() {\n float mean = textureLod(colortex1, vec2(0.5), 2.0).r;\n\
float right = texelFetch(colortex1, ivec2(1, 0), 1).r;\n\
gl_FragColor = vec4(mean * 7.5, right * 3.75, 0.0, 1.0);\n}\n",
);
let pack = horizon_shaders::Pack::from_zip_bytes(
"original-mipmap-box",
zip.finish().unwrap().into_inner(),
)
.unwrap();
let mut macros = horizon_shaders::Macros::standard();
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
let post = horizon_shaders::load_post(&pack, "", &properties, &macros, &Default::default());
assert_eq!(post.programs.len(), 2, "{:?}", post.notes);
post
}
#[test]
fn a_bright_texel_keeps_its_share_of_odd_sized_levels() {
let Some(gpu) = Fixture::new() else { return };
let mut post = gpu.build(pack());
let pixels = gpu.render(&mut post, [5, 3]);
// The 1x1 level is the mean of the 15 texels, 1/15; texel (1, 0) of the 2x1 level covers
// columns 2, 3 and 4 (weights 1, 2, 2 of 5) of all three rows (1 of 3 each): 2/15.
let [r, g, ..] = pixels[0];
assert!(
r.abs_diff(128) <= 2 && g.abs_diff(128) <= 2,
"mean and level-1 texel scaled to 0.5: got red {r}, green {g}, expected 128 and 128"
);
}
@@ -0,0 +1,152 @@
//! A translucent draw reads the preceding scene even when it writes the same color buffer.
//! Original programs and independently calculated colors; no shader-pack assets.
use super::depth_test::{Gpu, SIZE, VERTEX, fixture_frame};
use super::*;
use crate::hud::HudBatch;
use wgpu::{TextureFormat as T, util::DeviceExt};
#[test]
fn translucent_draws_sample_the_color_written_by_deferred() {
let Some(gpu) = Gpu::new() else { return };
let positions: [[f32; 3]; 6] = [
[-1.0, -1.0, 0.0],
[1.0, -1.0, 0.0],
[1.0, 1.0, 0.0],
[-1.0, -1.0, 0.0],
[1.0, 1.0, 0.0],
[-1.0, 1.0, 0.0],
];
let vertices = gpu
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Original translucent quad"),
contents: bytemuck::cast_slice(&positions),
usage: wgpu::BufferUsages::VERTEX,
});
const ATTRS: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0=>Float32x3];
let layouts = [Some(wgpu::VertexBufferLayout {
array_stride: 12,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &ATTRS,
})];
// Odd and even numbers of deferred passes leave the current scene on different sides.
// Exercise two buffer numbers and the legacy sampler aliases too.
for (buffer, sampler) in [(4, "colortex4"), (7, "gaux4")] {
for stages in [1, 2] {
for blended in [false, true] {
let mut files = vec![
("deferred.vsh".into(), VERTEX.into()),
(
"deferred.fsh".into(),
format!(
"#version 120\n/* RENDERTARGETS: {buffer} */\nvoid main(){{gl_FragData[0]=vec4(0.25,0.5,0.75,1.0);}}"
),
),
(
"gbuffers_water.vsh".into(),
"#version 120\nvoid main(){gl_Position=gl_Vertex;}".into(),
),
(
"gbuffers_water.fsh".into(),
format!(
"#version 120\n/* RENDERTARGETS: {buffer} */\nuniform sampler2D {sampler};\nvoid main(){{gl_FragData[0]=vec4(texture2D({sampler},vec2(0.5)).rgb+vec3(0.125,0.0,0.0),0.5);}}"
),
),
("final.vsh".into(), VERTEX.into()),
(
"final.fsh".into(),
format!(
"#version 120\nuniform sampler2D colortex{buffer};varying vec2 uv;\nvoid main(){{gl_FragColor=vec4(texture2D(colortex{buffer},uv).rgb,1.0);}}"
),
),
(
"shaders.properties".into(),
format!(
"blend.gbuffers_water={}\n",
if blended {
"SRC_ALPHA ONE_MINUS_SRC_ALPHA ONE ONE_MINUS_SRC_ALPHA"
} else {
"off"
}
),
),
];
if stages == 2 {
files.extend([
("deferred1.vsh".into(), VERTEX.into()),
("deferred1.fsh".into(), format!(
"#version 120\n/* RENDERTARGETS: {buffer} */\nvoid main(){{gl_FragData[0]=vec4(0.5,0.75,0.25,1.0);}}"
)),
]);
}
let color = gpu.texture(T::Rgba8Unorm);
let depth = gpu.texture(T::Depth32Float);
gpu.clear(&color, &depth, 0.0);
let mut post = gpu.load(
files,
World {
atlas: None,
material_maps: None,
lightmap: color.clone(),
terrain: Some(Geometry {
buffers: &layouts,
table: None,
depth_write: true,
atlas: None,
material_maps: false,
ids: None,
cull: false,
}),
block_ids: &[],
sprite_rects: &[],
celestial: None,
gui_size: SIZE,
clouds: None,
weather: false,
hand: false,
},
horizon_shaders::GameInputs {
terrain: Some(horizon_shaders::GbuffersInputs {
declarations: "layout(location=0)in vec3 fixture_position;\n".into(),
body: "hz_Vertex=vec4(fixture_position,1.0);\n".into(),
..Default::default()
}),
..Default::default()
},
);
assert!(post.has_water(), "{:?}", post.notes);
let mut expected = if stages == 1 {
[0.25f32, 0.5, 0.75]
} else {
[0.5, 0.75, 0.25]
};
expected[0] += if blended { 0.0625 } else { 0.125 };
let expected = expected.map(|c| (c * 255.0).round() as u8);
let hud = HudBatch::new(SIZE);
for frame in 0..2 {
let pixels = gpu.render(
&mut post,
&color,
&depth,
&fixture_frame(&hud),
&mut |rp, list, _, _| {
if list == TerrainList::Translucent {
rp.set_vertex_buffer(0, vertices.slice(..));
rp.draw(0..6, 0..1);
}
},
);
for p in pixels {
assert!(
p[..3]
.iter()
.zip(expected)
.all(|(&a, b)| a.abs_diff(b) <= 2),
"buffer {buffer}, {stages} deferred stages, blended {blended}, frame {frame}: {p:?}, expected {expected:?}"
);
}
}
}
}
}
}
@@ -0,0 +1,49 @@
//! A pack with no program for terrain draws none (#10455): Iris 1.11.7 drew no terrain, solid
//! or translucent, into any buffer or depth with probe packs of ours having no gbuffers
//! programs. The game hands the pack its terrain, so it doesn't draw it either. The programs
//! here are original and cut down.
use super::destination_tests::Fixture;
use std::io::{Cursor, Write};
const VERTEX: &str = "#version 120\nvoid main() { gl_Position = ftransform(); }\n";
const WHITE: &str =
"#version 120\n/* DRAWBUFFERS:0 */\nvoid main() { gl_FragData[0] = vec4(1.0); }\n";
/// A pack with `programs` (each drawing white into colortex0) loaded for a game that can hand it
/// terrain: whether it takes solid and translucent terrain from the game.
fn takes_terrain(programs: &[&str]) -> Option<(bool, bool)> {
let gpu = Fixture::new()?;
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
for name in programs {
for (ext, source) in [("vsh", VERTEX), ("fsh", WHITE)] {
zip.start_file(
format!("shaders/{name}.{ext}"),
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(source.as_bytes()).unwrap();
}
}
let pack = horizon_shaders::Pack::from_zip_bytes(
"undrawn-terrain",
zip.finish().unwrap().into_inner(),
)
.unwrap();
let mut macros = horizon_shaders::Macros::standard();
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
let inputs = horizon_shaders::GameInputs {
terrain: Some(Default::default()),
..Default::default()
};
let post = horizon_shaders::load_post(&pack, "", &properties, &macros, &inputs);
let post = gpu.try_build(post).ok()?;
Some((post.has_terrain(), post.has_water()))
}
#[test]
fn a_pack_without_terrain_programs_takes_terrain_from_the_game() {
let Some(taken) = takes_terrain(&["composite"]) else {
return;
};
assert_eq!(taken, (true, true));
}
@@ -43,6 +43,64 @@ fn a_pack_without_final_reads_the_replaced_world_colour() {
replacement(Change::Colour, false);
}
/// A Resolution Scale leaves the pack's picture smaller than the window. Its `final` draws at
/// the picture's size and one copy upsizes it to the window (#9291), so a final that fetches
/// its pixel by `gl_FragCoord` (as Photon's does) covers every pixel, not a quarter of them.
#[test]
fn a_scaled_picture_fills_the_whole_window() {
let instance = crate::gfx::test_gpu::instance();
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
return;
};
let Ok((device, queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_limits: adapter.limits(),
..Default::default()
})) else {
return;
};
eprintln!("scaled picture adapter: {:?}", adapter.get_info());
let picture = [4, 2];
let window = [8, 4];
let colour = texture(&device, picture, T::Rgba8Unorm);
let depth = texture(&device, picture, T::Depth32Float);
clear(&device, &queue, &colour, &depth, [32, 64, 16, 255], 0.25);
let mut post = pack_with(
&device,
&queue,
&adapter,
&colour,
&[
(
"final.vsh",
"#version 120\nvoid main(){gl_Position=ftransform();}",
),
(
"final.fsh",
"#version 330 compatibility\nuniform sampler2D colortex0;\nvoid main(){gl_FragColor=texelFetch(colortex0,ivec2(gl_FragCoord.xy),0);}",
),
],
);
let hud = HudBatch::new(window);
let pixels = render(
&device,
&queue,
&mut post,
&colour,
&depth,
&frame(&hud),
picture,
window,
);
// Independently specified: the world's colour at every window pixel.
let wrong = pixels.iter().filter(|p| **p != [32, 64, 16, 255]).count();
assert_eq!(
wrong,
0,
"{wrong} of {} pixels are not the picture",
pixels.len()
);
}
fn replacement(change: Change, final_shader: bool) {
let instance = crate::gfx::test_gpu::instance();
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
@@ -62,7 +120,9 @@ fn replacement(change: Change, final_shader: bool) {
let mut post = pack(&device, &queue, &adapter, &colour, final_shader);
let hud = HudBatch::new(size);
let frame = frame(&hud);
let initial = render(&device, &queue, &mut post, &colour, &depth, &frame, size);
let initial = render(
&device, &queue, &mut post, &colour, &depth, &frame, size, size,
);
let expected = if final_shader {
[32, 64, 191, 255]
} else {
@@ -93,9 +153,13 @@ fn replacement(change: Change, final_shader: bool) {
0.75
};
clear(&device, &queue, &colour, &depth, pixel, reverse_depth);
let actual = render(&device, &queue, &mut post, &colour, &depth, &frame, size);
let actual = render(
&device, &queue, &mut post, &colour, &depth, &frame, size, size,
);
let mut fresh = pack(&device, &queue, &adapter, &colour, final_shader);
let reference = render(&device, &queue, &mut fresh, &colour, &depth, &frame, size);
let reference = render(
&device, &queue, &mut fresh, &colour, &depth, &frame, size, size,
);
// Independently specified RG channels and GL depth (1 - reverse-Z), in UNORM8.
let expected = if !final_shader {
[160, 96, 48, 255]
@@ -178,13 +242,8 @@ fn pack(
lightmap: &wgpu::TextureView,
final_shader: bool,
) -> PackPost {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let options = zip::write::SimpleFileOptions::default();
zip.start_file("shaders/shaders.properties", options)
.unwrap();
zip.write_all(b"oldLighting=false\n").unwrap();
if final_shader {
for (name, source) in [
let programs: &[(&str, &str)] = if final_shader {
&[
(
"final.vsh",
"#version 120\nvarying vec2 uv;\nvoid main(){gl_Position=ftransform();uv=gl_MultiTexCoord0.xy;}",
@@ -193,10 +252,29 @@ fn pack(
"final.fsh",
"#version 120\nvarying vec2 uv;uniform sampler2D colortex0;uniform sampler2D depthtex0;\nvoid main(){gl_FragColor=vec4(texture2D(colortex0,uv).rg,texture2D(depthtex0,uv).r,1.0);}",
),
] {
zip.start_file(format!("shaders/{name}"), options).unwrap();
zip.write_all(source.as_bytes()).unwrap();
}
]
} else {
&[]
};
pack_with(device, queue, adapter, lightmap, programs)
}
/// A pack of `programs` (`name`, GLSL source) over `lightmap`.
fn pack_with(
device: &wgpu::Device,
queue: &wgpu::Queue,
adapter: &wgpu::Adapter,
lightmap: &wgpu::TextureView,
programs: &[(&str, &str)],
) -> PackPost {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let options = zip::write::SimpleFileOptions::default();
zip.start_file("shaders/shaders.properties", options)
.unwrap();
zip.write_all(b"oldLighting=false\n").unwrap();
for (name, source) in programs {
zip.start_file(format!("shaders/{name}"), options).unwrap();
zip.write_all(source.as_bytes()).unwrap();
}
let pack = horizon_shaders::Pack::from_zip_bytes(
"original-world-inputs",
@@ -241,12 +319,13 @@ fn render(
depth: &wgpu::TextureView,
frame: &Frame,
size: [u32; 2],
window: [u32; 2],
) -> Vec<[u8; 4]> {
let screen = texture(device, size, T::Rgba8Unorm);
let screen = texture(device, window, T::Rgba8Unorm);
let stride = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(stride * size[1]),
size: u64::from(stride * window[1]),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
@@ -261,7 +340,7 @@ fn render(
frame,
&Default::default(),
size,
size,
window,
&[],
&mut |_, _, _, _| {},
);
@@ -285,7 +364,7 @@ fn render(
.unwrap()
.chunks_exact(stride as usize)
.flat_map(|row| {
row[..size[0] as usize * 4]
row[..window[0] as usize * 4]
.as_chunks::<4>()
.0
.iter()
@@ -0,0 +1,56 @@
//! A built-in uniform declared with another GLSL type than the one Iris 1.11.7 gives is disabled
//! there ("Wrong uniform type ... Disabling that uniform") and reads 0; our probe packs (#9307)
//! read 0 for each such declaration. Declared with its own type, it keeps its value.
use super::destination_tests::Fixture;
use super::*;
use std::io::{Cursor, Write};
const VERTEX: &str = "#version 120\nvarying vec2 uv;\nvoid main() { uv = gl_MultiTexCoord0.xy; gl_Position = ftransform(); }\n";
/// composite declares two floats as `int` and `vec2` and an int as `float`, and writes what it
/// reads into colortex1; final declares the same names with their own types and adds them.
fn pack() -> Post {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let mut add = |name: &str, source: &str| {
zip.start_file(
format!("shaders/{name}"),
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(source.as_bytes()).unwrap();
};
add("composite.vsh", VERTEX);
add("final.vsh", VERTEX);
add(
"composite.fsh",
"#version 130\nuniform int viewWidth;\nuniform vec2 viewHeight;\nuniform float fogShape;\n\
void main() {\n/* DRAWBUFFERS:1 */\n\
\x20 gl_FragData[0] = vec4(float(viewWidth), viewHeight.x, fogShape + 1.0, 255.0) / 255.0;\n}\n",
);
add(
"final.fsh",
"#version 130\nuniform sampler2D colortex1;\nuniform float viewWidth;\nuniform int fogShape;\n\
varying vec2 uv;\nvoid main() {\n\
\x20 vec4 c = texture(colortex1, uv);\n\
\x20 gl_FragColor = vec4(c.r, c.g + viewWidth * 4.0 / 255.0, c.b + float(fogShape + 2) * 10.0 / 255.0, 1.0);\n}\n",
);
let pack = horizon_shaders::Pack::from_zip_bytes(
"original-wrong-uniform-types",
zip.finish().unwrap().into_inner(),
)
.unwrap();
let mut macros = horizon_shaders::Macros::standard();
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
horizon_shaders::load_post(&pack, "", &properties, &macros, &Default::default())
}
#[test]
fn built_ins_declared_with_another_type_read_zero() {
let Some(gpu) = Fixture::new() else { return };
let mut post = gpu.build(pack());
// 8 pixels wide; post programs read `fogShape` -1. composite reads 0, 0 and 0 (+1 = 1);
// final reads 8 (green 32) and -1 (+2 = 1, blue 10).
for p in gpu.render(&mut post, [8, 8]) {
assert_eq!(p, [0, 32, 11, 255]);
}
}
@@ -35,13 +35,6 @@ pub(super) struct ShadowTargets {
pub depth: (wgpu::Texture, wgpu::TextureView),
/// `shadowtex1`: a copy of `shadowtex0` taken before translucent terrain, when read.
pub depth1: Option<(wgpu::Texture, wgpu::TextureView)>,
/// `shadowtex0`/`1` as a plain sampler filters them: Iris 1.11.7 reads them linearly unless
/// a pack asks for the nearest texel (measured). wgpu filters a depth format only for a
/// comparison, so these are `R32Float` copies of the final depths, when read that way.
pub linear: [Option<wgpu::TextureView>; 2],
/// The rows a depth copy goes through to `linear` (a depth format copies only to a buffer),
/// and their stride in bytes.
staging: Option<(wgpu::Buffer, u32)>,
/// Both sides of each shadowcolor buffer used; one texture for both when no `shadowcomp`
/// program draws into or flips the buffer.
pub color: [Option<[wgpu::TextureView; 2]>; SHADOW_COLORS],
@@ -85,9 +78,8 @@ fn target(
impl ShadowTargets {
/// The buffers of `shadow` the pack uses: `colors` (bit n: shadowcolor n), `depth1` when
/// some program reads `shadowtex1`, `linear` (bit n: shadowtex n read through a filtering
/// sampler), `doubled` (bit n: shadowcolor n needs a B texture). The resolution is kept
/// within the device's limit.
/// some program reads `shadowtex1`, `doubled` (bit n: shadowcolor n needs a B texture). The
/// resolution is kept within the device's limit.
pub fn new(
device: &wgpu::Device,
shadow: &horizon_shaders::Shadow,
@@ -95,7 +87,6 @@ impl ShadowTargets {
colors: u16,
doubled: u16,
depth1: bool,
linear: u8,
) -> Self {
let size = shadow
.resolution
@@ -124,43 +115,10 @@ impl ShadowTargets {
[a, b]
})
});
let linear = [0, 1].map(|n| {
(linear & 1 << n != 0).then(|| {
let label = format!("Shader pack shadowtex{n} (filtered)");
device
.create_texture(&wgpu::TextureDescriptor {
label: Some(&label),
size: wgpu::Extent3d {
width: size,
height: size,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
})
.create_view(&Default::default())
})
});
let staging = linear.iter().any(Option::is_some).then(|| {
let stride = (size * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack shadow depth rows"),
size: u64::from(stride) * u64::from(size),
usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
(buffer, stride)
});
Self {
size,
depth: target(device, "Shader pack shadowtex0", size, depth, copy),
depth1: depth1.then(|| target(device, "Shader pack shadowtex1", size, depth, copy)),
linear,
staging,
color,
clears: std::array::from_fn(|n| {
let b = &shadow.colors[n];
@@ -266,38 +224,4 @@ impl ShadowTargets {
);
}
}
/// `linear`: the filtered copies of the depths the shadow pass left (`shadowtex1` from its
/// copy before translucent geometry).
pub fn copy_linear(&self, encoder: &mut wgpu::CommandEncoder) {
let Some((buffer, stride)) = &self.staging else {
return;
};
for (n, linear) in self.linear.iter().enumerate() {
let Some(linear) = linear else {
continue;
};
let depth = match (n, &self.depth1) {
(1, Some(d)) => &d.0,
_ => &self.depth.0,
};
let rows = wgpu::TexelCopyBufferInfo {
buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(*stride),
rows_per_image: None,
},
};
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
aspect: wgpu::TextureAspect::DepthOnly,
..depth.as_image_copy()
},
rows,
depth.size(),
);
encoder.copy_buffer_to_texture(rows, linear.texture().as_image_copy(), depth.size());
}
}
}
@@ -96,15 +96,12 @@ pub struct PackInputs {
pub still_ticks: Option<u64>,
}
/// The `cloudHeight` uniform. Vanilla reads `visual/cloud_height` only while the cloud color
/// has alpha (`LevelExtractor`); a dimension without clouds has no height, which the uniform
/// reports as NaN. NaN is not vanilla's own value: packs map it to "no clouds".
pub fn cloud_height(cloud_color_alpha: f32, height: f32) -> f32 {
if crate::clouds::has_color(cloud_color_alpha) {
height
} else {
f32::NAN
}
/// The `cloudHeight` uniform: the dimension's `visual/cloud_height`
/// (`EnvironmentAttributes.CLOUD_HEIGHT`, 192.33 where the dimension doesn't set it), whether or
/// not it has clouds. ShaderDoc says NaN for a dimension without clouds, but Iris 1.11.7 reads
/// 192.33 in the Nether and the End, in every program kind our probe packs read it from.
pub fn cloud_height(sky: &crate::environment::Sky) -> f32 {
sky.cloud_height
}
/// The local player's state behind Iris's status uniforms (`currentPlayerHealth`,
@@ -155,6 +152,31 @@ impl Value {
Value::I(a)
}
/// Whether a program that declares the built-in `name` as `ty` reads this value. Iris 1.11.7
/// disables a built-in declared with another GLSL type than the one it gives ("Wrong uniform
/// type ... Disabling that uniform"), and the program reads 0. Our probe packs saw it for a
/// float declared `int` or `vec2`, an int `float`, an `ivec2` `vec2`, `int` or `ivec3`, a
/// `vec3` `vec2` or `vec4`, a `mat4` `mat3`, and any `uint`; an int or a bool built-in
/// declared `bool` or `int` was kept. A float declared `bool` is left as it was: Iris warned,
/// but our probe read true.
pub fn read_as(&self, name: &str, ty: &str) -> bool {
let int = matches!(self, Value::I(_));
let (declared_int, size) = match ty {
"float" => (false, 1),
"bool" if !int => return true,
"int" | "bool" => (true, 1),
"mat2" => (false, 4),
"mat3" => (false, 9),
"mat4" => (false, 16),
t if t.starts_with('u') => return false,
t if let Some(n) = t.strip_prefix("ivec") => (true, n.parse().unwrap_or(0)),
t if let Some(n) = t.strip_prefix("vec") => (false, n.parse().unwrap_or(0)),
_ => return true,
};
let name = name.strip_prefix("gbuffers.").unwrap_or(name);
declared_int == int && size == components(name)
}
/// Writes the value as the type the pack declared, at `offset` of a std140 block.
pub fn write(&self, ty: &str, out: &mut [u8], offset: usize) {
let ints = matches!(ty, "int" | "bool" | "uint") || ty.starts_with(['i', 'u']);
@@ -367,6 +389,25 @@ fn body(angle: f32, tilt: f32) -> Vec3 {
.transform_vector3(Vec3::new(0.0, 100.0, 0.0))
}
/// `sunPosition` and `moonPosition` (`angle`: the body's sky angle in degrees) and `upPosition`
/// (`angle` none) to the last bit, as Iris 1.11.7 gives them: our probes' readings (50: 25 ticks
/// of day and night, `sunPathRotation` 0 and 30, four view directions) fit `(0, 100, 0, 0)`
/// times `gbufferModelView` turned by JOML quaternions, in floats: `rotate(rotationY(-90°))`,
/// then for a body `rotate(rotationZ(sunPathRotation))` and `rotate(rotationX(angle))`. Turned
/// by matrices instead, as `body` and vanilla 26.3's sky do, 4e-6 stands where Iris has an exact
/// 0, and the rest differs by 1 to 2 ulps (#8464).
fn celestial(view: Mat4, tilt: f32, angle: Option<f32>) -> Vec3 {
use crate::camera::joml::{Mat4 as Joml, Quat};
use horizon_core::geometry::trig::DEG_TO_RAD;
let mut m = Joml::affine(view);
m.rotate_affine(Quat::rotation_y(-90.0 * DEG_TO_RAD));
if let Some(angle) = angle {
m.rotate_affine(Quat::rotation_z(tilt * DEG_TO_RAD));
m.rotate_affine(Quat::rotation_x(angle * DEG_TO_RAD));
}
Vec3::from_array(m.transform_affine([0.0, 100.0, 0.0, 0.0]))
}
/// `sunPathRotation`'s turn of the sky's bodies: `tilt` degrees about the world's X axis, so a
/// positive angle moves the noon sun toward -Z (north), as Iris does.
pub fn tilt_matrix(tilt: f32) -> Mat4 {
@@ -511,7 +552,12 @@ fn invert_generic(m: Mat4) -> Mat4 {
/// `shadow_camera`'s view and projection in wgpu's clip space (depth 0..1), for culling.
pub fn shadow_culling(frame: &Frame, shadow: &Shadow) -> Mat4 {
let (view, gl) = shadow_camera(shadow_light(frame, shadow), frame.camera, shadow);
shadow_culling_at(shadow_light(frame, shadow), frame.camera, shadow)
}
/// `shadow_culling` for the direction toward the light and the camera's position.
pub fn shadow_culling_at(light: Vec3, camera: DVec3, shadow: &Shadow) -> Mat4 {
let (view, gl) = shadow_camera(light, camera, shadow);
// GL's depth -w..w to wgpu's 0..w.
let depth = Mat4::from_cols(
Vec4::X,
@@ -683,8 +729,8 @@ impl FrameUniforms {
let sun_angle = day_fraction(frame.sky.sun_angle);
let day = sun_angle < 0.5;
let tilt = self.shadow.sun_path_rotation;
let sun = to_view(body(frame.sky.sun_angle, tilt));
let moon = to_view(body(frame.sky.moon_angle, tilt));
let sun = celestial(view, tilt, Some(frame.sky.sun_angle));
let moon = celestial(view, tilt, Some(frame.sky.moon_angle));
// Half-lives are given in ticks (7.2); smoothing runs per frame in seconds (OQ-26), at
// a tenth of a second a tick: Iris 1.11.7 smooths that slowly (measured frame by frame
// with a probe pack: wetness 60 s rising, 20 s falling; eyeBrightnessSmooth 1 s;
@@ -771,7 +817,7 @@ impl FrameUniforms {
"hasSkylight" => Value::i(&[i32::from(inputs.has_skylight)]),
"hasCeiling" => Value::i(&[i32::from(inputs.has_ceiling)]),
"eyeAltitude" => Value::f(&[frame.camera.y as f32]),
"upPosition" => v3(to_view(Vec3::new(0.0, 100.0, 0.0))),
"upPosition" => v3(celestial(view, tilt, None)),
"sunPosition" => v3(sun),
"endFlashPosition" => v3(to_view(inputs.end_flash_direction)),
"centerDepthSmooth" => Value::f(&[center_depth]),
@@ -1014,6 +1060,36 @@ mod tests {
assert_eq!(out[60..64], [0; 4], "a value past the block is dropped");
}
/// The declarations our probe packs (#9307) ran in Iris 1.11.7: kept, or read as 0.
#[test]
fn built_ins_are_read_only_as_iris_gives_them() {
let int = Value::i(&[1]);
let float = Value::f(&[0.25]);
let matrix = Value::f(&[1.0; 16]);
for (value, name, ty, kept) in [
(&int, "isSpectator", "bool", true),
(&int, "isSpectator", "int", true),
(&int, "worldTime", "bool", true),
(&int, "worldTime", "uint", false),
(&int, "worldTime", "float", false),
(&Value::i(&[2048, 2048]), "atlasSize", "ivec2", true),
(&Value::i(&[2048, 2048]), "atlasSize", "vec2", false),
(&Value::i(&[2048, 2048]), "atlasSize", "int", false),
(&Value::i(&[2048, 2048]), "atlasSize", "ivec3", false),
(&float, "sunAngle", "float", true),
(&float, "sunAngle", "vec2", false),
(&float, "viewWidth", "int", false),
(&Value::f(&[1.0, 2.0, 3.0]), "cameraPosition", "vec3", true),
(&Value::f(&[1.0, 2.0, 3.0]), "cameraPosition", "vec4", false),
(&Value::f(&[1.0, 2.0, 3.0]), "cameraPosition", "vec2", false),
(&matrix, "gbufferModelView", "mat4", true),
(&matrix, "gbufferModelView", "mat3", false),
(&Value::i(&[1]), GBUFFERS_FOG_MODE, "int", true),
] {
assert_eq!(value.read_as(name, ty), kept, "{ty} {name}");
}
}
/// The load-time run of custom uniforms sees each built-in at its size: Iris 1.11.7 reads 2
/// for the first line of our probes K and X (#9086) and 0 for the others.
#[test]
@@ -1101,11 +1177,40 @@ mod tests {
);
}
/// A dimension type of `attributes` (JSON), loaded as the game loads one and sampled at noon.
fn sky_of(name: &str, attributes: &str) -> crate::environment::Sky {
let root = std::env::temp_dir().join(format!(
"horizon-cloud-height-{}-{name}",
std::process::id()
));
let dir = root.join("data/minecraft/dimension_type");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join(format!("{name}.json")),
format!(r#"{{"attributes": {attributes}}}"#),
)
.unwrap();
let environment =
crate::environment::Environment::load_dimension(&root, name, false).unwrap();
std::fs::remove_dir_all(&root).unwrap();
environment.sample(6000, None, None)
}
#[test]
fn cloud_height_needs_a_cloud_color() {
assert_eq!(cloud_height(0.8, 192.33), 192.33);
assert_eq!(cloud_height(0.8, 120.0), 120.0);
assert!(cloud_height(0.0, 192.33).is_nan());
fn cloud_height_is_the_dimensions_with_or_without_clouds() {
// Our probe packs read 192.33 in Iris 1.11.7's Nether and End, whose dimension types
// set neither a cloud colour nor a cloud height.
let nether = sky_of(
"nether_like",
r##"{"minecraft:visual/fog_start_distance": 10.0, "minecraft:visual/fog_end_distance": 96.0}"##,
);
assert_eq!(nether.cloud_color[3], 0.0, "no clouds");
assert_eq!(cloud_height(&nether), 192.33);
let cloudy = sky_of(
"cloudy",
r##"{"minecraft:visual/cloud_color": "#ccffffff", "minecraft:visual/cloud_height": 120.0}"##,
);
assert_eq!(cloud_height(&cloudy), 120.0);
}
#[test]
@@ -1364,6 +1469,105 @@ mod initial_history_tests {
assert_eq!(float(&u, "sunAngle")[0].to_bits(), 0x3eb134f4);
}
/// `sunPosition`, `moonPosition`, `upPosition` and `shadowLightPosition` to the last bit, as
/// a probe pack of ours read them back in Iris 1.11.7: noon looking west, just after sunset
/// looking south (where Iris's sun is exactly 0 in z), and with `sunPathRotation = 30` at
/// 1000 ticks, at 13000 looking down 45° and at 12786 with yaw 200, pitch -30. The sky
/// angles are vanilla's timeline at those ticks.
#[test]
fn the_sun_moon_and_up_are_iris_s_to_the_last_bit() {
let hud = HudBatch::new([1280, 720]);
let mut f = frame(&hud);
let o = 0;
type Case = (f32, f32, f32, u32, u32, [[u32; 3]; 3], bool);
let cases: [Case; 5] = [
(
0.0,
90.0,
0.0,
0,
0x43340000,
[[o, 0x42c7fffe, o], [o, 0xc2c7fffe, o], [o, 0x42c7fffe, o]],
true,
),
(
0.0,
0.0,
0.0,
0x42b420b1,
0x4387082c,
[
[0x42c7fff7, 0xbde43dae, o],
[0xc2c7fff7, 0x3de4376e, o],
[o, 0x42c7ffff, o],
],
false,
),
(
30.0,
90.0,
0.0,
0x4394c5da,
0x43eec5da,
[
[0x41b8fb81, 0x42203312, 0x42b15411],
[0xc1b8fb8c, 0xc220331b, 0xc2b1540f],
[o, 0x42c7fffe, o],
],
true,
),
(
30.0,
0.0,
45.0,
0x42bb0aec,
0x4388c2bb,
[
[0x42c79f54, 0xbfcb7a52, 0xc0bdd8f1],
[0xc2c79f54, 0x3fcb7a25, 0x40bdd8c7],
[o, 0x428d6bdc, 0x428d6bde],
],
false,
),
(
30.0,
200.0,
-30.0,
0x42b420b1,
0x4387082c,
[
[0xc2bbe678, 0x41885944, 0x41edb502],
[0x42bbe677, 0xc1885947, 0xc1edb4fc],
[o, 0x42ad347e, 0xc247fffe],
],
false,
),
];
for (tilt, yaw, pitch, sun, moon, [sun_at, moon_at, up], day) in cases {
f.yaw = yaw;
f.pitch = pitch;
f.sky.sun_angle = f32::from_bits(sun);
f.sky.moon_angle = f32::from_bits(moon);
let mut u = FrameUniforms {
shadow: Shadow {
sun_path_rotation: tilt,
..Shadow::default()
},
..FrameUniforms::default()
};
u.update(&f, &PackInputs::default(), [1280, 720]);
let vector = |name: &str| -> [u32; 3] {
let v = bits(&u, name);
[v[0], v[1], v[2]]
};
assert_eq!(vector("sunPosition"), sun_at, "{sun:x}");
assert_eq!(vector("moonPosition"), moon_at, "{sun:x}");
assert_eq!(vector("upPosition"), up, "{sun:x}");
let light = if day { sun_at } else { moon_at };
assert_eq!(vector("shadowLightPosition"), light, "{sun:x}");
}
}
/// At night the moon casts the shadows, here with `sunPathRotation = 30`: Iris 1.11.7 at
/// 16000 ticks (the moon at 324.4897°), the camera at (-556.5, 76.62, 212.5), whose
/// negative x keeps its sign in the remainder.
@@ -2088,3 +2292,7 @@ mod initial_history_tests {
}
}
}
#[cfg(test)]
#[path = "pack_uniforms/ftransform_test.rs"]
mod ftransform_test;
@@ -0,0 +1,218 @@
//! Original GPU probe of a pack's `ftransform()`, in gbuffers and shadow programs.
use wgpu::util::DeviceExt;
/// Iris 1.11.7's `ftransform()` read back with a probe pack of ours (#8464) has the bits of
/// `gl_ProjectionMatrix * (gl_ModelViewMatrix * gl_Vertex)` at every vertex our probes read: the
/// model-view matrix first, then the projection, not their product matrix. These matrices tell
/// the two apart (one rounding against two): the model-view matrix takes 16777 from x, so the
/// vertex at 16777.25 comes out at exactly 0.25, and a third of that is one rounding; the product
/// matrix holds a third of 16777 rounded to a float, which leaves an error near 1e-4 after the
/// subtraction.
#[test]
fn ftransform_applies_the_model_view_matrix_before_the_projection() {
let instance = crate::gfx::test_gpu::instance();
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
return;
};
let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).unwrap();
let third = 1.0f32 / 3.0;
let model_view = glam::Mat4::from_translation(glam::Vec3::new(-16777.0, 2.0, 0.0));
let projection = glam::Mat4::from_scale(glam::Vec3::new(third, 0.5, 1.0));
let vertices = [[16777.25f32, 1.0, -3.0], [16778.0, -2.0, 5.0]];
// `0.25 * third` and `1.0 * third` are exact products: one rounding of each.
let expected = [[0.25 * third, 1.5, -3.0, 1.0], [third, 0.0, 5.0, 1.0]];
let mut failures = Vec::new();
for shadow in [false, true] {
let got = ftransform(&device, &queue, model_view, projection, &vertices, shadow);
for ((v, want), got) in vertices.iter().zip(&expected).zip(&got) {
if got.map(f32::to_bits) != want.map(f32::to_bits) {
failures.push(format!("{v:?}, shadow={shadow}: {got:?} != {want:?}"));
}
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// `ftransform()` of each of `vertices` in a gbuffers program (or a shadow program, with the
/// matrices as the shadow camera's), read back from a point per vertex as float bits.
fn ftransform(
device: &wgpu::Device,
queue: &wgpu::Queue,
model_view: glam::Mat4,
projection: glam::Mat4,
vertices: &[[f32; 3]],
shadow: bool,
) -> Vec<[f32; 4]> {
let pp = |code: &str| horizon_shaders::Preprocessed {
code: code.to_owned(),
..Default::default()
};
let vertex = pp(&format!(
"varying vec4 probe;\nvoid main() {{\n probe = ftransform();\n \
gl_Position = vec4((float(gl_VertexID) + 0.5) * {} - 1.0, 0.0, 0.0, 1.0);\n}}",
2.0 / vertices.len() as f32,
));
// An integer target keeps the float bits on any adapter.
let fragment = pp(
"varying vec4 probe;\nlayout(location = 0) out uvec4 bits;\n\
void main() { bits = floatBitsToUint(probe); }",
);
let inputs = horizon_shaders::GbuffersInputs {
declarations: "layout(location = 0) in vec3 hz_v_pos;".into(),
body: " hz_Vertex = vec4(hz_v_pos, 1.0);\n hz_Color = vec4(1.0);\n".into(),
..Default::default()
};
let program = if shadow {
horizon_shaders::translate_shadow(&vertex, &fragment, &inputs)
} else {
horizon_shaders::translate_gbuffers(
&vertex,
&fragment,
horizon_shaders::Target::Buffers,
&inputs,
)
}
.unwrap();
let prefix = if shadow { "shadow" } else { "gbuffer" };
let mut block = program.interface.initial_values.clone();
block.resize(program.interface.uniform_size.max(16) as usize, 0);
for (name, matrix) in [("ModelView", model_view), ("Projection", projection)] {
let name = format!("{prefix}{name}");
let at = (program.interface.uniforms.iter())
.find(|u| u.name == name)
.unwrap_or_else(|| panic!("no {name}"))
.offset as usize;
block[at..at + 64].copy_from_slice(bytemuck::cast_slice(&matrix.to_cols_array()));
}
let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: &block,
usage: wgpu::BufferUsages::UNIFORM,
});
let data = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(vertices),
usage: wgpu::BufferUsages::VERTEX,
});
let group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
}],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&group_layout)],
..Default::default()
});
let module = |module| {
device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)),
})
};
let vs = module(program.vertex);
let fs = module(program.fragment);
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &vs,
entry_point: Some("main"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: 12,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &wgpu::vertex_attr_array![0 => Float32x3],
})],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::PointList,
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &fs,
entry_point: Some("main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba32Uint,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let output = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: vertices.len() as u32,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Uint,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: vertices.len() as u64 * 16,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let view = output.create_view(&Default::default());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &group, &[]);
pass.set_vertex_buffer(0, data.slice(..));
pass.draw(0..vertices.len() as u32, 0..1);
}
encoder.copy_texture_to_buffer(
output.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &read,
layout: wgpu::TexelCopyBufferLayout::default(),
},
output.size(),
);
queue.submit([encoder.finish()]);
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let mapped = read.slice(..).get_mapped_range().unwrap();
bytemuck::cast_slice::<u8, [f32; 4]>(&mapped).to_vec()
}
@@ -319,7 +319,7 @@ mod tests {
#[test]
fn a_native_weather_stage_validates() {
use horizon_shader_api::stages::StageKind;
let source = StageKind::Weather.prelude()
let source = StageKind::Weather.prelude(horizon_shader_api::Api::V0_1)
+ "fn weather(input: WeatherInput) -> vec4<f32> {\n \
return input.color * vec4(input.light, input.position.x, f32(input.snow));\n}\n";
let text = native_source(&source);
@@ -43,9 +43,7 @@ struct TaaUniform {
jitter: [f32; 4],
}
/// TAA's GPU resources, absent when the device cannot compile the shader
/// (the OpenGL backend's naga GLSL emitter does not support `textureLoad`
/// from depth textures).
/// TAA's GPU resources, absent when the device cannot compile the shader.
struct TaaResources {
layout: wgpu::BindGroupLayout,
pipeline: wgpu::RenderPipeline,
@@ -146,9 +144,6 @@ impl Post {
cache: None,
})
};
// The OpenGL backend's GLSL translator does not support textureLoad
// from depth textures: on devices running through OpenGL (such as older
// Intel GPUs on Linux), TAA cannot compile its pipeline.
let taa_resources = {
let taa_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Horizon TAA bindings"),
@@ -161,7 +156,9 @@ impl Post {
count: None,
},
texture(2, float),
texture(3, wgpu::TextureSampleType::Depth),
// A depth view through an unfilterable float binding: the
// texel is the same, and the GLSL backend can read it.
texture(3, wgpu::TextureSampleType::Float { filterable: false }),
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
File diff suppressed because it is too large. Load diff
+52 -7
View File
@@ -1232,7 +1232,8 @@ impl HudAtlas {
.ok();
let animation = animation_of(mcmeta.as_deref());
// An animated strip keeps its first frame.
let frames = name.starts_with("block/") || name.starts_with("item/");
let frames =
animation.is_some() || name.starts_with("block/") || name.starts_with("item/");
let (w, h, pixels) = if frames {
first_frame(image, animation.as_ref())
} else {
@@ -1313,12 +1314,13 @@ impl HudAtlas {
edition.3 = pixels;
}
images.push(("horizon/white".into(), 4, 4, vec![255; 64]));
images.push((
crate::pad_cursor::SPRITE.into(),
crate::pad_cursor::SIZE,
crate::pad_cursor::SIZE,
crate::pad_cursor::pixels(),
));
// The controller's art, unless a pack brought its own (walked above, as a mod's GUI
// textures are).
for image in crate::pad_glyph::images() {
if !images.iter().any(|i| i.0 == image.0) {
images.push(image);
}
}
if full {
Self::slots(&mut images, crate::trims::slot_size(root), mod_image);
// MissingTextureAtlasSprite.generateMissingImage: 16x16, magenta
@@ -3495,6 +3497,49 @@ mod tests {
let banner = atlas.sprites["custom/banner"];
assert_eq!(banner.texels((atlas.width, atlas.height)), (16, 32));
}
#[test]
fn an_animated_gui_sprite_packs_its_first_frame_and_animates() {
let root =
std::env::temp_dir().join(format!("horizon-atlas-gui-anim-{}", std::process::id()));
let sprites = root.join("assets/minecraft/textures/gui/sprites/icon");
fs::create_dir_all(&sprites).unwrap();
// A GUI sprite like icon/music_notes: 4 frames stacked vertically (16x64),
// with animation metadata, and a still 16x32 texture beside it.
write_strip(
&sprites.join("music_notes.png"),
16,
64,
&[
[10, 20, 30, 255],
[40, 50, 60, 255],
[70, 80, 90, 255],
[100, 110, 120, 255],
],
Some(r#"{"animation": {"frametime": 2}}"#),
);
write_strip(
&sprites.join("static_badge.png"),
16,
32,
&[[9, 9, 9, 255]],
None,
);
let atlas = HudAtlas::build(&root).unwrap();
let _ = fs::remove_dir_all(&root);
let rect = atlas.sprites["gui/sprites/icon/music_notes"];
// One frame, not the whole 16x64 strip squeezed into a slot.
assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 16));
assert_eq!(texel_at(&atlas, rect, 0, 15), [10, 20, 30, 255]);
let (_, animation) = atlas
.sprite_animations
.iter()
.find(|(r, _)| r.u0 == rect.u0 && r.v0 == rect.v0)
.expect("the gui sprite animates");
assert_eq!(animation.frame_count(), 4);
// A still texture there stays whole.
let static_badge = atlas.sprites["gui/sprites/icon/static_badge"];
assert_eq!(static_badge.texels((atlas.width, atlas.height)), (16, 32));
}
/// A resource root with one plain item texture and these CIT files (relative path, contents).
fn cit_root(name: &str, files: &[(&str, &str)]) -> PathBuf {
let root =
+5
View File
@@ -32,6 +32,7 @@ pub mod collisions;
pub mod command_block;
pub mod connected;
pub mod containers;
pub mod controller_ui;
pub mod crash;
pub mod datapack;
pub mod dynamic_light;
@@ -62,6 +63,7 @@ pub mod menu_blur;
pub mod mesher;
pub mod minimap;
pub mod mipmap;
pub mod mod_browser;
pub mod mod_list;
pub mod model_library;
pub mod models;
@@ -75,6 +77,7 @@ pub mod pack_browser;
pub mod pack_screen;
pub mod packs;
pub mod pad_cursor;
pub mod pad_glyph;
pub mod par;
pub mod particles;
pub mod poi_sections;
@@ -91,8 +94,10 @@ pub mod sculk;
pub mod section_mask;
pub mod server_terrain;
pub mod settings;
pub mod settings_shell;
pub mod shader_options;
pub mod shader_pack_list;
pub mod shader_ui;
pub mod signs;
pub mod skins;
pub mod sound_engine;
+33 -16
View File
@@ -4025,9 +4025,12 @@ mod tests {
);
// A chunk covers only one quarter of this parent's 32² cell. Both
// opaque terrain and water must leave precisely that 16² footprint.
// Only active tiles enter the mesher snapshot, even when samples are ready.
lod.active.insert(key);
lod.covered.insert((-1, -2));
lod.covered_bounds = Some([-16, -32, 0, -16]);
let mesh = lod.mesh(key);
lod.active.remove(&key);
let top_area = |vertices: &[TerrainVertex], y: f32| {
vertices
.as_chunks::<4>()
@@ -4213,14 +4216,19 @@ mod tests {
&lod.reduced[&(-1, -1)].columns,
&lod.saved[&(-1, -1)]
));
assert!(
let reduced_spans = |lod: &Lod| {
lod.snapshot()
.visited_source(-16, -16, 2)
.unwrap()
.get()
.spans
.is_empty()
);
.iter()
.map(|span| (span.min, span.max, span.state))
.collect::<Vec<_>>()
};
// Reduction keeps a block held by any column of the footprint, so
// this single-column build survives the cached two-block reduction.
assert_eq!(reduced_spans(&lod), vec![(120, 121, stone)]);
let old = lod.saved[&(-1, -1)].clone();
lod.observe(Arc::new(chunk.clone()), &facts);
receive_observed(&mut lod);
@@ -4233,30 +4241,43 @@ mod tests {
&lod.reduced[&(-1, -1)].columns,
&lod.saved[&(-1, -1)]
));
assert_eq!(
reduced_spans(&lod),
vec![(120, 121, stone), (130, 131, stone)]
);
// A seed reduction arriving after the edit cannot restore old data.
lod.finish_detail((-1, -1), ReducedColumns::new(old));
assert_eq!(lod.ready[&fine][0].surface.unwrap().height, 131);
assert_eq!(
reduced_spans(&lod),
vec![(120, 121, stone), (130, 131, stone)]
);
// Exercise the actual worker/update seam: a parent stays displayed
// until all four child meshes can replace it in the same update.
// until all four child meshes have arrived, possibly over several updates.
let camera = [-256.0, 100.0, -256.0];
lod.area = Some(([-16, -16], 2, 64, 0, false, None));
lod.plan.roots = vec![key];
lod.plan.nodes.insert(key);
// As a replan does (`update` only selects after a change).
lod.reselect = true;
let await_meshes = |lod: &mut Lod| {
let await_meshes = |lod: &mut Lod, count: usize| {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let mut uploaded = Vec::new();
loop {
let meshes = lod.update(camera, 2, 64, None, None);
if !meshes.is_empty() {
return meshes;
uploaded.extend(lod.update(camera, 2, 64, None, None));
if uploaded.len() >= count {
return uploaded;
}
assert!(
lod.removed().is_empty(),
"retired before replacement meshes"
);
assert!(std::time::Instant::now() < deadline, "mesh worker stalled");
std::thread::sleep(std::time::Duration::from_millis(1));
}
};
let uploaded = await_meshes(&mut lod);
let uploaded = await_meshes(&mut lod, 1);
assert_eq!(uploaded.len(), 1);
assert_eq!(uploaded[0].0, key);
assert!(lod.active.contains(&key));
@@ -4266,13 +4287,7 @@ mod tests {
lod.ready.insert(child, lod.ready[&key].clone());
}
lod.reselect = true;
assert!(lod.update(camera, 2, 64, None, None).is_empty());
assert!(
lod.active.contains(&key),
"parent retired before child meshes"
);
assert!(lod.removed().is_empty());
let uploaded = await_meshes(&mut lod);
let uploaded = await_meshes(&mut lod, 4);
assert_eq!(uploaded.len(), 4);
assert!(
key.children()
@@ -4376,6 +4391,7 @@ mod tests {
.insert(parent, Arc::new(vec![Column::default(); 256]));
}
lod.active = [near, far].into_iter().collect();
lod.wanted_stale = true;
lod.shared.jobs.lock().unwrap().clear();
lod.sample_jobs = SAMPLE_JOBS;
lod.pending = (0..SAMPLE_JOBS - 1)
@@ -4401,6 +4417,7 @@ mod tests {
lod.plan.split.clear();
lod.detail_masks.clear();
lod.covered = [(0, 0)].into_iter().collect();
lod.full = lod.covered.clone();
lod.detail_request_pending = false;
lod.detail_request_at = std::time::Instant::now() - std::time::Duration::from_secs(1);
lod.request_detail([0, 0]);
@@ -1412,6 +1412,9 @@ pub struct Mesher<'a> {
pub shader_pack_lighting: bool,
/// OptiFine/Iris separate ambient occlusion: vertex RGB does not include AO, and AO factor is passed in vertex alpha.
pub separate_ao: bool,
/// A `shaders/` pack draws the terrain (with or without its `oldLighting`): fluid tops are
/// split into triangles as Iris splits them (`fluid::splits_north_east`).
pub shader_pack: bool,
pub assets: &'a Assets,
pub render: &'a RenderAssets,
pub tables: &'a MeshTables,
@@ -1503,6 +1506,7 @@ impl Mesher<'_> {
self.nether_shading,
self.shader_pack_lighting,
self.separate_ao,
self.shader_pack,
);
fluid::tesselate(self.tables, shade, pad, water, &mut out, [x, y, z]);
}
@@ -188,13 +188,28 @@ impl FluidFlowWorld for FlowView<'_> {
Ok(self.info[state as usize].sturdy & 1 << d as u8 != 0)
}
}
/// Whether a `shaders/` pack's fluid top with these corner heights is split into triangles along
/// its north-east to south-west diagonal, as Iris 1.11.7 draws it, rather than along vanilla's
/// north-west to south-east one (`FluidRenderer.tesselate` puts its vertices NW, SW, SE, NE, and
/// `RenderSystem`'s quad indices join vertex 0 to 2).
///
/// Our probe packs' readings of Iris (#8464) fit this: a top is split along the diagonal whose
/// corners differ more in height, and a top whose north-west and south-east corners are level
/// (a still, flat top among them) along north-east to south-west. It is a fit, not Iris's code:
/// it covers every lava top we read and every still top but one, and misses 26 of the 343 water
/// tops we read (undiagnosed).
pub(super) fn splits_north_east(nw: f32, ne: f32, sw: f32, se: f32) -> bool {
let (along_nw, along_ne) = ((nw - se).abs(), (ne - sw).abs());
along_nw < along_ne || along_nw == 0.0
}
/// Emits one fluid cell at section-relative `[x, y, z]`.
/// `(nether, shader_pack_lighting, separate_ao)`: the Nether's face shading, only the up-face value
/// when a shader pack lights the faces (`Mesher::shader_pack_lighting`), and whether to keep pure
/// alpha for separate AO.
/// `(nether, shader_pack_lighting, separate_ao, shader_pack)`: the Nether's face shading, only the
/// up-face value when a shader pack lights the faces (`Mesher::shader_pack_lighting`), whether to
/// keep pure alpha for separate AO, and whether a `shaders/` pack draws the terrain
/// (`Mesher::shader_pack`: tops split as Iris splits them, [`splits_north_east`]).
pub(super) fn tesselate(
tables: &MeshTables,
(nether, shader_pack_lighting, separate_ao): (bool, bool, bool),
(nether, shader_pack_lighting, separate_ao, shader_pack): (bool, bool, bool, bool),
pad: &Padded,
water_color: u32,
out: &mut SectionMesh,
@@ -383,13 +398,19 @@ pub(super) fn tesselate(
!same(s) && !s.solid
})
});
let mut corners = [
([fx, fy + nw, fz], uv[0]),
([fx, fy + sw, fz + 1.0], uv[1]),
([fx + 1.0, fy + se, fz + 1.0], uv[2]),
([fx + 1.0, fy + ne, fz], uv[3]),
];
// Starting from the south-west corner joins it to the north-east one (0 to 2), with the
// same winding.
if shader_pack && splits_north_east(nw, ne, sw, se) {
corners.rotate_left(1);
}
quad(
[
([fx, fy + nw, fz], uv[0]),
([fx, fy + sw, fz + 1.0], uv[1]),
([fx + 1.0, fy + se, fz + 1.0], uv[2]),
([fx + 1.0, fy + ne, fz], uv[3]),
],
corners,
layer,
color(cardinal(D::Up)),
light([x, y, z]),
@@ -492,6 +513,49 @@ mod tests {
}
assert!(atan2(f64::NAN, 1.0).is_nan());
}
/// Corner heights read back from Iris 1.11.7 with a probe pack of ours (#8464), from water
/// and lava spreading over a floor and from a still lake, and whether Iris split each top
/// along north-east to south-west. Each height is the vanilla average it reads as (for
/// example 13/27 for 0.48047 + 0.001), less `FluidRenderer`'s 0.001.
#[test]
fn fluid_tops_split_where_iris_splits_them() {
let h = |num: f32, den: f32| num / den - 0.001;
// (north-west, north-east, south-west, south-east)
let cases = [
// Still and flat: a lake's water, a lava pool.
([h(8.0, 9.0); 4], true),
([h(96.0, 117.0); 4], true),
// Level along one axis: both diagonals equally steep.
(
[h(5.0, 9.0), h(13.0, 27.0), h(5.0, 9.0), h(13.0, 27.0)],
false,
),
(
[h(100.0, 117.0), h(100.0, 117.0), h(2.0, 3.0), h(2.0, 3.0)],
false,
),
// North-west to south-east steeper.
([h(5.0, 9.0), h(4.0, 9.0), h(4.0, 9.0), h(7.0, 18.0)], false),
([h(7.0, 18.0), h(4.0, 9.0), h(4.0, 9.0), h(5.0, 9.0)], false),
([h(5.0, 6.0), h(4.0, 9.0), h(2.0, 9.0), h(2.0, 9.0)], false),
// North-east to south-west steeper.
([h(1.0, 2.0), h(5.0, 9.0), h(7.0, 18.0), h(4.0, 9.0)], true),
(
[h(4.0, 9.0), h(2.0, 9.0), h(96.0, 117.0), h(4.0, 9.0)],
true,
),
// North-west and south-east level: a saddle.
([h(4.0, 9.0), h(7.0, 18.0), h(7.0, 18.0), h(4.0, 9.0)], true),
];
for ([nw, ne, sw, se], iris) in cases {
assert_eq!(
splits_north_east(nw, ne, sw, se),
iris,
"{:?}",
[nw, ne, sw, se]
);
}
}
#[test]
fn coverage_of_full_and_partial_faces() {
assert_eq!(coverage(&VoxelShape::block(), Direction::North), 1.0);
@@ -73,6 +73,7 @@ fn mesh(
nether_shading: false,
shader_pack_lighting: false,
separate_ao: false,
shader_pack: false,
assets: &f.assets,
render: &f.render,
tables: &f.tables,
@@ -133,6 +133,7 @@ fn a_shader_pack_lights_the_faces_itself() {
nether_shading: false,
shader_pack_lighting,
separate_ao: false,
shader_pack: false,
assets: &assets,
render: &render,
tables: &tables,
@@ -188,6 +189,7 @@ fn a_shader_pack_lights_every_nether_face_like_an_up_face() {
nether_shading,
shader_pack_lighting: true,
separate_ao: false,
shader_pack: false,
assets: &assets,
render: &render,
tables: &tables,
@@ -239,6 +241,7 @@ fn separate_ao_passes_ao_in_alpha_without_darkening_rgb() {
nether_shading: false,
shader_pack_lighting: true,
separate_ao: true,
shader_pack: false,
assets: &assets,
render: &render,
tables: &tables,
@@ -313,6 +316,7 @@ fn reused_mesh_matches_fresh_geometry_across_sections_and_resource_reload() {
nether_shading: false,
shader_pack_lighting: false,
separate_ao: false,
shader_pack: false,
assets: &assets,
render: &render,
tables: &tables,
@@ -425,3 +429,67 @@ fn benchmark_padded_reuse() {
}
}
}
/// Run explicitly with prepared assets. Under a `shaders/` pack, a still water top (a source
/// in a stone basin, flat) starts from its south-west corner, so its triangles meet along
/// north-east to south-west as Iris 1.11.7's do in our probes (`fluid::splits_north_east`);
/// without one it keeps vanilla's north-west start (`FluidRenderer.tesselate`).
#[test]
#[ignore = "requires prepared 26.3 resources (HORIZON_MESH_TEST_RESOURCES or .local/horizon-client/26.3)"]
fn a_shader_pack_s_still_water_top_starts_at_its_south_west_corner() {
let root = std::env::var_os("HORIZON_MESH_TEST_RESOURCES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3")
});
let assets = Assets::load(&root).unwrap();
let facts = BlockFacts::load(&root, assets.registry).unwrap();
let biomes = Biomes::load(&root).unwrap();
let render = assets.reload(&root).unwrap();
let visibility = crate::models::load_visibility(&root, assets.registry).unwrap();
let tables = MeshTables::new(&assets, &render, &facts, visibility.clone()).unwrap();
let state = |name| assets.registry.default_state(name).unwrap().0;
let mut chunk = Chunk::empty(0, 0);
for x in 7..=9 {
for z in 7..=9 {
chunk.set(x, MIN_Y + 7, z, state("minecraft:stone"));
chunk.set(x, MIN_Y + 8, z, state("minecraft:stone"));
}
}
chunk.set(8, MIN_Y + 8, 8, state("minecraft:water"));
let mut region = [[None; 3]; 3];
region[1][1] = Some(&chunk);
let first_corner = |shader_pack| {
let mut mesher = Mesher {
nether_shading: false,
shader_pack_lighting: shader_pack,
separate_ao: false,
shader_pack,
assets: &assets,
render: &render,
tables: &tables,
biomes: &biomes,
visibility: visibility.clone(),
zoom: BiomeZoom::new(0),
blend_radius: 0,
smooth_lighting: true,
cutout_leaves: true,
translucent_layers: &[],
leaf_culling: LeafCullingMode::Off,
};
let mesh = mesher.mesh(&region, 0);
// The top and its backward face, both from the same first corner.
let tops: Vec<[f32; 3]> = mesh
.translucent
.chunks(4)
.filter(|q| q.iter().all(|v| v.pos[1] > 8.5 && v.pos[1] < 9.0))
.map(|q| q[0].pos)
.collect();
assert_eq!(tops.len(), 2, "{tops:?}");
assert_eq!(tops[0], tops[1]);
[tops[0][0], tops[0][2]]
};
assert_eq!(first_corner(false), [8.0, 8.0]);
assert_eq!(first_corner(true), [8.0, 9.0]);
}
@@ -0,0 +1,189 @@
//! What Options > Mods > Browse mods shows (docs/design/mod-hotload.md): the
//! registry's content mods this game installs, a search over them, and the one
//! whose page is open. The game fills it from a worker
//! (`horizon_client::mod_registry`, `game/mod_browser.rs`); the options screen
//! only reads it and asks for installs through its events.
/// One project of the registry, as the list and its page show it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Listing {
pub id: String,
pub name: String,
pub summary: String,
/// Markdown, shown as plain text.
pub description: String,
pub authors: Vec<String>,
pub license: String,
pub categories: Vec<String>,
pub tags: Vec<String>,
/// The version this game would install, its date and changelog.
pub version: String,
pub published: String,
pub changelog: String,
pub downloads: u64,
/// The project's page on the website.
pub page: String,
/// The version installed in this game folder, if any.
pub installed: Option<String>,
}
impl Listing {
/// Whether a search for `query` (already lower case) finds it: its name,
/// id, summary, authors, categories or tags.
pub fn matches(&self, query: &str) -> bool {
let query = query.trim();
query.is_empty()
|| [&self.name, &self.id, &self.summary]
.into_iter()
.chain(&self.authors)
.chain(&self.categories)
.chain(&self.tags)
.any(|field| field.to_lowercase().contains(query))
}
/// Installed, but not the version the registry offers now.
pub fn has_update(&self) -> bool {
self.installed
.as_ref()
.is_some_and(|installed| *installed != self.version)
}
}
/// Where the browser is.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Status {
/// Not asked yet.
#[default]
Idle,
/// The index is being read.
Loading,
/// The projects are listed.
Ready,
/// The index couldn't be read: why, in English (shown inside a translated line).
Failed(String),
}
#[derive(Clone, Debug, Default)]
pub struct ModBrowser {
pub status: Status,
pub listings: Vec<Listing>,
/// The project an install runs for.
pub installing: Option<String>,
/// The last install's outcome, already translated, for the page it ran on.
pub message: Option<(String, bool)>,
}
impl ModBrowser {
/// The listings a search for `query` finds, by index into `listings`.
pub fn found(&self, query: &str) -> Vec<usize> {
let query = query.to_lowercase();
(0..self.listings.len())
.filter(|&i| self.listings[i].matches(&query))
.collect()
}
pub fn listing(&self, id: &str) -> Option<&Listing> {
self.listings.iter().find(|l| l.id == id)
}
}
/// A project's markdown description as lines of plain text for the page:
/// heading marks, emphasis and list bullets dropped, links shown as their text,
/// blank lines and fences left out.
pub fn plain_lines(markdown: &str) -> Vec<String> {
let mut out = Vec::new();
for line in markdown.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with("```") || line.starts_with("<!--") {
continue;
}
let line = line.trim_start_matches('#').trim_start();
let line = match line.strip_prefix("- ").or_else(|| line.strip_prefix("* ")) {
Some(rest) => format!("• {rest}"),
None => line.to_owned(),
};
let line = links_as_text(&line).replace("**", "").replace('`', "");
if !line.is_empty() {
out.push(line);
}
}
out
}
/// `[text](url)` → `text`, `![alt](url)` → nothing.
fn links_as_text(line: &str) -> String {
let mut out = String::with_capacity(line.len());
let mut rest = line;
while let Some(open) = rest.find('[') {
let Some(close) = rest[open..].find("](").map(|c| open + c) else {
break;
};
let Some(end) = rest[close..].find(')').map(|e| close + e) else {
break;
};
let image = open > 0 && rest[..open].ends_with('!');
out.push_str(&rest[..if image { open - 1 } else { open }]);
if !image {
out.push_str(&rest[open + 1..close]);
}
rest = &rest[end + 1..];
}
out.push_str(rest);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn listing(id: &str, tags: &[&str]) -> Listing {
Listing {
id: id.into(),
name: id.to_uppercase(),
summary: format!("All about {id}"),
tags: tags.iter().map(|t| (*t).to_owned()).collect(),
version: "1.0".into(),
..Listing::default()
}
}
#[test]
fn a_search_finds_names_tags_and_categories_in_any_case() {
let mut pipes = listing("pipes", &["tech"]);
pipes.categories = vec!["technology".into()];
let browser = ModBrowser {
listings: vec![listing("ruby", &["gems"]), pipes],
..ModBrowser::default()
};
assert_eq!(browser.found(""), [0, 1]);
assert_eq!(browser.found("RUBY"), [0]);
assert_eq!(browser.found("gems"), [0]);
assert_eq!(browser.found("techno"), [1]);
assert!(browser.found("nothing like it").is_empty());
}
#[test]
fn an_update_is_another_version_than_the_installed_one() {
let mut l = listing("ruby", &[]);
assert!(!l.has_update());
l.installed = Some("1.0".into());
assert!(!l.has_update());
l.installed = Some("0.9".into());
assert!(l.has_update());
}
#[test]
fn markdown_reads_as_plain_lines() {
let text = "# Ruby\n\nAdds **rubies**. See [the wiki](https://x.y).\n\n![shot](https://x.y/a.png)\n- one\n* two\n```\ncode\n```\n";
assert_eq!(
plain_lines(text),
[
"Ruby",
"Adds rubies. See the wiki.",
"• one",
"• two",
"code"
]
);
}
}
+3 -3
View File
@@ -93,7 +93,7 @@ pub(crate) fn prepare_with_models(
models: &crate::model_library::ParsedModels,
) -> Result<PreparedModels> {
let facts: std::collections::BTreeMap<String, Value> =
serde_json::from_slice(&std::fs::read(root.join("model-states.json"))?)?;
horizon_world::json_file::read(&root.join("model-states.json"))?;
let blocks: Vec<&str> = facts
.keys()
.filter(|name| registry.default_state(name).is_some())
@@ -158,11 +158,11 @@ pub fn load_visibility(
collision::CachedCollisionRegistry,
registry::BlockTableFile,
};
use std::{collections::BTreeMap, fs};
use std::collections::BTreeMap;
let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?;
let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?;
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("render-definitions.json"))?)?;
horizon_world::json_file::read(&root.join("render-definitions.json"))?;
let definitions = raw
.into_iter()
.map(|(name, v)| {
File diff suppressed because it is too large. Load diff
+30 -3
View File
@@ -899,9 +899,24 @@ fn merge(kind: Merge, layers: &[Vec<u8>]) -> Option<Vec<u8>> {
.iter()
// SoundManager skips a sounds.json Gson rejects, whole.
.filter(|b| kind != Merge::Sounds || crate::sound_events::is_valid_file(b))
.filter_map(|b| match serde_json::from_slice(b) {
Ok(Value::Object(m)) => Some(m),
_ => None,
.filter_map(|b| {
match serde_json::from_slice(b) {
Ok(Value::Object(m)) => Some(m),
// `Language.loadFromJson` reads with Gson's lenient reader, so
// a lang file with `#` comments still counts; a file that
// strict JSON accepts keeps its bytes as they are.
_ if kind == Merge::Lang => {
let mut strings = std::collections::HashMap::new();
horizon_client_core::lang::read_lang_file(b, &mut strings);
Some(
strings
.into_iter()
.map(|(k, v)| (k, Value::String(v)))
.collect(),
)
}
_ => None,
}
})
.collect();
let list = |key: &str, layers: &mut dyn Iterator<Item = &Map<String, Value>>| {
@@ -1424,6 +1439,18 @@ mod tests {
parse(lang.unwrap()),
serde_json::json!({"a":"vanilla a","b":"pack b"})
);
// A layer with `#` comments is read leniently, not dropped.
let lenient = merge(
Merge::Lang,
&[
json(r#"{"a":"vanilla a"}"#),
json("# a pack comment\n{\"b\":\"pack b\", # trailing\n\"a\":\"pack a\"}"),
],
);
assert_eq!(
parse(lenient.unwrap()),
serde_json::json!({"a":"pack a","b":"pack b"})
);
// SoundManager: sounds add up; `replace` starts the event over.
let sounds = merge(
Merge::Sounds,
+11 -39
View File
@@ -1,43 +1,13 @@
//! The controller's menu cursor in inventories: a crosshair whose centre is
//! the point it clicks. Horizon's own art (pad_cursor.png).
//! the point it clicks. Horizon's own art, packed with the button glyphs (`pad_glyph`).
/// The atlas sprite.
pub const SPRITE: &str = "horizon/pad_cursor";
/// The texture's size in texels, and the size it's drawn at in GUI pixels
/// (an item's).
pub const SIZE: u32 = 32;
pub const SPRITE: &str = "horizon:gui/controller/crosshair_inv";
/// The size it's drawn at in GUI pixels (an item's); its texture is twice that.
pub const DRAWN: f32 = 16.0;
const PNG: &[u8] = include_bytes!("pad_cursor.png");
/// The texture as `SIZE` square RGBA texels.
pub fn pixels() -> Vec<u8> {
decode(PNG).expect("pad_cursor.png is a 32x32 PNG")
}
fn decode(bytes: &[u8]) -> Option<Vec<u8>> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().ok()?;
let info = reader.info();
if (info.width, info.height) != (SIZE, SIZE) {
return None;
}
let mut buf = vec![0; reader.output_buffer_size()?];
let frame = reader.next_frame(&mut buf).ok()?;
let channels = frame.color_type.samples();
Some(
buf.chunks(channels)
.take((SIZE * SIZE) as usize)
.flat_map(|p| match channels {
4 => [p[0], p[1], p[2], p[3]],
3 => [p[0], p[1], p[2], 255],
2 => [p[0], p[0], p[0], p[1]],
_ => [p[0], p[0], p[0], 255],
})
.collect(),
)
}
pub(crate) const PNG: &[u8] =
include_bytes!("../../horizon-client/assets/horizon/textures/gui/controller/crosshair_inv.png");
/// Where to draw the cursor (top-left, GUI pixels) so its centre lands on
/// the GUI point `at`.
@@ -51,10 +21,12 @@ mod tests {
#[test]
fn the_cursor_is_a_crosshair_centred_on_its_point() {
let px = pixels();
assert_eq!(px.len(), (SIZE * SIZE * 4) as usize);
let alpha = |x: u32, y: u32| px[((y * SIZE + x) * 4 + 3) as usize];
let middle = (SIZE / 2 - 1)..=(SIZE / 2);
let (_, w, h, px) = crate::pad_glyph::images()
.find(|i| i.0 == SPRITE)
.expect("the cursor is packed");
assert_eq!((w as f32, h as f32), (DRAWN * 2.0, DRAWN * 2.0));
let alpha = |x: u32, y: u32| px[((y * w + x) * 4 + 3) as usize];
let middle = (w / 2 - 1)..=(w / 2);
assert!(
middle
.clone()
@@ -0,0 +1,386 @@
//! A controller button as the player sees it: Horizon's own art where the pad's family has one
//! (`assets/horizon/textures/gui/controller/`, which a resource pack can replace), else the label
//! printed on the pad, in its colour, on a dark key. Whatever shows a button draws and measures it
//! here; `Button::label` stays for plain text and narration.
use crate::gamepad::{Button, GlyphStyle};
use crate::hud::{HudAtlas, HudBatch, rgba};
use crate::pad_cursor;
/// The art's height as drawn, in GUI pixels. Its texture is twice that, so it maps pixel for pixel
/// at GUI scale 2 and to whole pixels at 4.
const DRAWN_HEIGHT: f32 = 16.0;
/// The clear edge the art has all round.
const MARGIN: f32 = 2.0;
/// How tall a glyph shows, art or key: the text line and 2 above and below it.
pub const HEIGHT: f32 = DRAWN_HEIGHT - 2.0 * MARGIN;
/// How wide a face button's art shows; a declared button's label leaves it room.
pub const FACE_WIDTH: f32 = 12.0;
/// A picture of a button in a family (Auto reads as Xbox, as `Button::label` has it). Every family
/// has its own file for every button, some of them a copy of another's until theirs is drawn.
struct Art {
family: GlyphStyle,
button: Button,
/// The atlas sprite: where a pack's own file lands.
sprite: &'static str,
png: &'static [u8],
}
macro_rules! art {
($($family:ident $button:ident $file:literal,)*) => {
&[$(Art {
family: GlyphStyle::$family,
button: Button::$button,
sprite: concat!("horizon:gui/controller/", $file),
png: include_bytes!(concat!(
"../../horizon-client/assets/horizon/textures/gui/controller/",
$file,
".png"
)),
},)*]
};
}
/// All the art. A new picture is one line here and its file: a button not listed is text, and a
/// picture is measured from its texture, so it can be as wide as it needs.
static ART: &[Art] = art![
Xbox South "xb_a",
Xbox East "xb_b",
Xbox West "xb_x",
Xbox North "xb_y",
Xbox LeftBumper "xb_lb",
Xbox RightBumper "xb_rb",
Xbox LeftTrigger "xb_lt",
Xbox RightTrigger "xb_rt",
Xbox Select "xb_view",
Xbox Start "xb_menu",
Xbox LeftStick "xb_l3",
Xbox RightStick "xb_r3",
Xbox DPadUp "xb_up",
Xbox DPadDown "xb_down",
Xbox DPadLeft "xb_left",
Xbox DPadRight "xb_right",
PlayStation South "psx_cross",
PlayStation East "psx_circle",
PlayStation West "psx_square",
PlayStation North "psx_triangle",
PlayStation LeftBumper "psx_l1",
PlayStation RightBumper "psx_r1",
PlayStation LeftTrigger "psx_l2",
PlayStation RightTrigger "psx_r2",
PlayStation Select "psx_create",
PlayStation Start "psx_options",
PlayStation LeftStick "psx_l3",
PlayStation RightStick "psx_r3",
PlayStation DPadUp "psx_up",
PlayStation DPadDown "psx_down",
PlayStation DPadLeft "psx_left",
PlayStation DPadRight "psx_right",
Nintendo South "nx_b",
Nintendo East "nx_a",
Nintendo West "nx_y",
Nintendo North "nx_x",
Nintendo LeftBumper "nx_l",
Nintendo RightBumper "nx_r",
Nintendo LeftTrigger "nx_zl",
Nintendo RightTrigger "nx_zr",
Nintendo Select "nx_minus",
Nintendo Start "nx_plus",
Nintendo LeftStick "nx_l3",
Nintendo RightStick "nx_r3",
Nintendo DPadUp "nx_up",
Nintendo DPadDown "nx_down",
Nintendo DPadLeft "nx_left",
Nintendo DPadRight "nx_right",
];
fn find(button: Button, style: GlyphStyle) -> Option<&'static Art> {
let family = match style {
GlyphStyle::Auto => GlyphStyle::Xbox,
style => style,
};
ART.iter()
.find(|art| art.family == family && art.button == button)
}
/// The sprite of a button in a family, if it has one.
pub fn sprite(button: Button, style: GlyphStyle) -> Option<&'static str> {
find(button, style).map(|art| art.sprite)
}
/// The sprite this atlas can draw for the button; none (the boot screen's atlas) means text.
pub fn art(atlas: &HudAtlas, button: Button, style: GlyphStyle) -> Option<&'static str> {
sprite(button, style).filter(|name| atlas.sprites.contains_key(*name))
}
/// How wide the art shows: half its texture (IHDR's width, in a PNG's first bytes) less its edge.
/// A pack's own texture of another size is drawn in the same place.
fn art_width(art: &Art) -> f32 {
let texels = u32::from_be_bytes([art.png[16], art.png[17], art.png[18], art.png[19]]);
texels as f32 / 2.0 - 2.0 * MARGIN
}
/// How wide the glyph shows.
pub fn width(atlas: &HudAtlas, button: Button, style: GlyphStyle) -> f32 {
match find(button, style).filter(|a| atlas.sprites.contains_key(a.sprite)) {
Some(art) => art_width(art),
None => HudBatch::text_width(atlas, button.label(style)).ceil() + 4.0,
}
}
/// What the glyph covers with its label's text at `(x, y)`: `[x, y, w, h]`.
pub fn rect(atlas: &HudAtlas, button: Button, style: GlyphStyle, x: f32, y: f32) -> [f32; 4] {
[x - 1.0, y - 2.0, width(atlas, button, style), HEIGHT]
}
/// Draw the glyph over the 8 pixel text line at `(x, y)`, filling [`rect`]. A dark key backs text
/// only: the art brings its own.
pub fn draw(
batch: &mut HudBatch,
atlas: &HudAtlas,
button: Button,
style: GlyphStyle,
x: f32,
y: f32,
) {
let [left, top, wide, tall] = rect(atlas, button, style, x, y);
if let Some(name) = art(atlas, button, style) {
batch.sprite_scaled(
atlas,
name,
left - MARGIN,
top - MARGIN,
wide + 2.0 * MARGIN,
tall + 2.0 * MARGIN,
u32::MAX,
);
} else {
let [r, g, b] = button.color(style);
batch.fill(atlas, left, top, wide, tall, rgba(40, 40, 40, 255));
batch.text(
atlas,
button.label(style),
x + 1.0,
y,
rgba(r, g, b, 255),
false,
);
}
}
/// Horizon's art for the atlas: each `(sprite, width, height, RGBA texels)`.
pub fn images() -> impl Iterator<Item = (String, u32, u32, Vec<u8>)> {
ART.iter()
.map(|art| (art.sprite, art.png))
.chain([(pad_cursor::SPRITE, pad_cursor::PNG)])
.map(|(name, png)| {
let (w, h, pixels) = decode(png).expect("Horizon's controller art is PNG");
(name.to_owned(), w, h, pixels)
})
}
fn decode(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().ok()?;
let (w, h) = (reader.info().width, reader.info().height);
let mut buf = vec![0; reader.output_buffer_size()?];
let frame = reader.next_frame(&mut buf).ok()?;
let channels = frame.color_type.samples();
let pixels = buf
.chunks(channels)
.take((w * h) as usize)
.flat_map(|p| match channels {
4 => [p[0], p[1], p[2], p[3]],
3 => [p[0], p[1], p[2], 255],
2 => [p[0], p[0], p[0], p[1]],
_ => [p[0], p[0], p[0], 255],
})
.collect();
Some((w, h, pixels))
}
#[cfg(test)]
mod tests {
use super::*;
fn atlas() -> HudAtlas {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
fn file(button: Button, style: GlyphStyle) -> Option<&'static str> {
sprite(button, style).and_then(|name| name.strip_prefix("horizon:gui/controller/"))
}
/// The batch's quads as `[left, top, right, bottom]`.
fn quads(batch: &HudBatch) -> Vec<[f32; 4]> {
batch
.vertices
.as_chunks::<6>()
.0
.iter()
.map(|quad| {
let xs = quad.iter().map(|v| v.pos[0]);
let ys = quad.iter().map(|v| v.pos[1]);
[
xs.clone().fold(f32::MAX, f32::min),
ys.clone().fold(f32::MAX, f32::min),
xs.fold(f32::MIN, f32::max),
ys.fold(f32::MIN, f32::max),
]
})
.collect()
}
#[test]
fn xbox_and_auto_show_the_letters_and_shoulders() {
for style in [GlyphStyle::Xbox, GlyphStyle::Auto] {
for (button, expected) in [
(Button::South, "xb_a"),
(Button::East, "xb_b"),
(Button::West, "xb_x"),
(Button::North, "xb_y"),
(Button::LeftBumper, "xb_lb"),
(Button::RightBumper, "xb_rb"),
(Button::LeftTrigger, "xb_lt"),
(Button::RightTrigger, "xb_rt"),
(Button::Select, "xb_view"),
(Button::Start, "xb_menu"),
] {
assert_eq!(file(button, style), Some(expected));
}
}
}
#[test]
fn playstation_shows_its_symbols_by_position_and_its_own_shoulders() {
let style = GlyphStyle::PlayStation;
assert_eq!(file(Button::South, style), Some("psx_cross"));
assert_eq!(file(Button::East, style), Some("psx_circle"));
assert_eq!(file(Button::West, style), Some("psx_square"));
assert_eq!(file(Button::North, style), Some("psx_triangle"));
assert_eq!(file(Button::LeftBumper, style), Some("psx_l1"));
assert_eq!(file(Button::RightTrigger, style), Some("psx_r2"));
assert_eq!(file(Button::Select, style), Some("psx_create"));
}
#[test]
fn nintendo_shows_what_its_pad_prints_at_each_position() {
let style = GlyphStyle::Nintendo;
assert_eq!(file(Button::South, style), Some("nx_b"));
assert_eq!(file(Button::East, style), Some("nx_a"));
assert_eq!(file(Button::West, style), Some("nx_y"));
assert_eq!(file(Button::North, style), Some("nx_x"));
assert_eq!(file(Button::LeftTrigger, style), Some("nx_zl"));
assert_eq!(file(Button::Start, style), Some("nx_plus"));
}
#[test]
fn every_family_has_its_own_file_for_every_button() {
for (style, prefix) in [
(GlyphStyle::Xbox, "xb_"),
(GlyphStyle::PlayStation, "psx_"),
(GlyphStyle::Nintendo, "nx_"),
] {
for button in Button::ALL {
let name = file(button, style).unwrap();
assert!(name.starts_with(prefix), "{button:?} {name}");
}
}
}
#[test]
fn every_sprite_has_its_texture_at_twice_gui_size() {
let images: Vec<_> = images().collect();
assert_eq!(images.len(), ART.len() + 1, "the art and the cursor");
for (name, w, h, pixels) in &images {
assert_eq!(pixels.len(), (w * h * 4) as usize, "{name}");
assert_eq!(*h as f32, DRAWN_HEIGHT * 2.0, "{name}");
}
for art in ART {
let (_, w, ..) = images.iter().find(|i| i.0 == art.sprite).unwrap();
assert_eq!(art_width(art), *w as f32 / 2.0 - 4.0, "{}", art.sprite);
}
}
#[test]
fn no_button_has_two_pictures_in_a_family() {
for (i, art) in ART.iter().enumerate() {
assert!(
!ART[..i]
.iter()
.any(|a| a.family == art.family && a.button == art.button),
"{}",
art.sprite
);
}
}
#[test]
fn art_measures_from_its_shape_and_text_from_its_label() {
let atlas = atlas();
assert_eq!(width(&atlas, Button::South, GlyphStyle::Xbox), 12.0);
assert_eq!(width(&atlas, Button::LeftBumper, GlyphStyle::Xbox), 20.0);
assert_eq!(
width(&atlas, Button::LeftBumper, GlyphStyle::PlayStation),
20.0
);
assert_eq!(width(&atlas, Button::DPadUp, GlyphStyle::Nintendo), 12.0);
let mut no_art = atlas;
no_art
.sprites
.remove(sprite(Button::LeftTrigger, GlyphStyle::Nintendo).unwrap());
let label = HudBatch::text_width(&no_art, "ZL").ceil() + 4.0;
assert_eq!(
width(&no_art, Button::LeftTrigger, GlyphStyle::Nintendo),
label
);
}
#[test]
fn an_atlas_without_the_art_falls_back_to_text() {
let mut atlas = atlas();
atlas
.sprites
.remove(sprite(Button::South, GlyphStyle::Xbox).unwrap());
assert_eq!(art(&atlas, Button::South, GlyphStyle::Xbox), None);
let label = HudBatch::text_width(&atlas, "A").ceil() + 4.0;
assert_eq!(width(&atlas, Button::South, GlyphStyle::Xbox), label);
}
#[test]
fn art_is_one_quad_centred_on_the_text_line_with_no_key_behind_it() {
let atlas = atlas();
let mut batch = HudBatch::new([640, 480]);
draw(
&mut batch,
&atlas,
Button::South,
GlyphStyle::Xbox,
10.0,
20.0,
);
assert_eq!(quads(&batch), vec![[7.0, 16.0, 23.0, 32.0]]);
let mut batch = HudBatch::new([640, 480]);
draw(
&mut batch,
&atlas,
Button::LeftBumper,
GlyphStyle::Xbox,
10.0,
20.0,
);
assert_eq!(quads(&batch), vec![[7.0, 16.0, 31.0, 32.0]]);
}
#[test]
fn text_sits_on_a_key_covering_what_rect_says() {
let mut atlas = atlas();
let style = GlyphStyle::Nintendo;
atlas.sprites.remove(sprite(Button::South, style).unwrap());
let mut batch = HudBatch::new([640, 480]);
draw(&mut batch, &atlas, Button::South, style, 10.0, 20.0);
let [x, y, w, h] = rect(&atlas, Button::South, style, 10.0, 20.0);
assert_eq!(quads(&batch)[0], [x, y, x + w, y + h]);
}
}
+13 -9
View File
@@ -17,6 +17,7 @@ use horizon_core::{
geometry::{Aabb, Axis, Vec3, trig},
random::{LegacyRandom, RandomSource},
};
use horizon_protocol::entity_data::PositionSource;
use horizon_world::block_collision::BlockCollisionRegistry;
use std::{
array,
@@ -50,9 +51,10 @@ pub struct ParticleOptions {
/// `GeyserParticleOptions.waterBlocks` and `GeyserBaseParticleOptions`'
/// `waterBlocks` and `burstImpulseBase` (0 where the type has none).
pub geyser: Option<(i32, f32)>,
/// `VibrationParticleOption`: the listener the signal flies to and its
/// arrival time in ticks (`ParticleEngine::vibration` is the same particle).
pub vibration: Option<([f64; 3], i32)>,
/// `VibrationParticleOption`: the listener's `PositionSource`, the point
/// the signal flies to and its arrival time in ticks
/// (`ParticleEngine::vibration` is the same particle).
pub vibration: Option<(PositionSource, [f64; 3], i32)>,
/// A native mod's own particle type, by its namespaced name (`mymod:spark`):
/// `SimpleParticleType` plus the provider `particles/<name>.json` names.
pub mod_particle: Option<String>,
@@ -94,10 +96,11 @@ impl ParticleOptions {
..Self::simple(ty)
}
}
/// `VibrationParticleOption(destination, arrivalInTicks)`.
pub fn vibration(dest: [f64; 3], ticks: i32) -> Self {
/// `VibrationParticleOption(destination, arrivalInTicks)`: the listener's
/// position source and the point this engine flies the signal to.
pub fn vibration(source: PositionSource, dest: [f64; 3], ticks: i32) -> Self {
Self {
vibration: Some((dest, ticks)),
vibration: Some((source, dest, ticks)),
..Self::simple(ParticleType::Vibration)
}
}
@@ -2988,8 +2991,8 @@ impl ParticleEngine {
// the listener the signal flies to and its arrival time; the sprite
// is the set's own draw from the engine's random.
T::Vibration => {
let (dest, ticks) = o.vibration?;
let mut q = Self::vibration_particle(p, dest, ticks);
let (_, dest, ticks) = o.vibration.as_ref()?;
let mut q = Self::vibration_particle(p, *dest, *ticks);
q.set = set;
q.sprite = self.sprite_from_set(ty);
q
@@ -5644,7 +5647,8 @@ mod tests {
#[test]
fn a_vibration_option_makes_the_signal_its_provider_draws() {
let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
let options = ParticleOptions::vibration([10.5, 70.5, -3.5], 20);
let options =
ParticleOptions::vibration(PositionSource::Block([10, 70, -4]), [10.5, 70.5, -3.5], 20);
// Within the camera's 32 blocks, so only the provider decides.
engine.add_with(&options, [0.5, 1.5, 0.5], [0.0; 3], false, false);
assert_eq!(engine.made().get("vibration"), Some(&1));
+316 -2
View File
@@ -575,8 +575,53 @@ pub struct Hud {
/// Hits in a row the server confirmed, until this player is hurt or 3 seconds pass.
pub combo: bool,
pub combo_corner: Corner,
/// Frames drawn in the last second.
pub fps: bool,
pub fps_corner: Corner,
/// Left and right clicks in the last second.
pub cps: bool,
pub cps_corner: Corner,
/// The movement keys, mouse buttons and jump, lit while held, with clicks per second.
pub keys: bool,
pub keys_corner: Corner,
/// The computer's local time.
pub clock: bool,
pub clock_corner: Corner,
/// How far the last hit landed from the eyes, for 3 seconds; it only measures.
pub reach: bool,
pub reach_corner: Corner,
/// Horizontal speed in blocks per second.
pub speed: bool,
pub speed_corner: Corner,
/// A dark box behind each widget.
pub background: bool,
/// The boxes' opacity, in percent.
pub opacity: u8,
/// The widgets' text colour (durability keeps its own).
pub text: Colour,
/// A shadow under the widgets' text, as vanilla's HUD text has.
pub shadow: bool,
}
impl Hud {
/// Whether any widget is on: with none, the HUD draws nothing and reads nothing.
pub fn any(&self) -> bool {
[
self.armour,
self.effects,
self.held,
self.ping,
self.coords,
self.server,
self.combo,
self.fps,
self.cps,
self.keys,
self.clock,
self.reach,
self.speed,
]
.contains(&true)
}
}
impl Default for Hud {
fn default() -> Self {
@@ -596,11 +641,35 @@ impl Default for Hud {
server_corner: Corner::TopLeft,
combo: false,
combo_corner: Corner::TopLeft,
fps: false,
fps_corner: Corner::TopLeft,
cps: false,
cps_corner: Corner::TopLeft,
keys: false,
keys_corner: Corner::BottomLeft,
clock: false,
clock_corner: Corner::TopRight,
reach: false,
reach_corner: Corner::TopLeft,
speed: false,
speed_corner: Corner::TopLeft,
background: true,
opacity: HUD_OPACITY,
text: Colour::White,
shadow: true,
}
}
}
pub use crate::extras::Corner;
/// The widgets' boxes at first: the extras' 0x78 alpha, 47%.
pub const HUD_OPACITY: u8 = 47;
pub const HUD_OPACITIES: (u8, u8) = (0, 100);
impl Hud {
/// The boxes' colour, ARGB.
pub fn background_argb(&self) -> u32 {
alpha(self.opacity) << 24
}
}
/// The value of the view options while they follow the world.
fn world_label() -> String {
crate::lang::get_or("horizon.pvp.view.world", "World's")
@@ -682,7 +751,38 @@ impl ChatOptions {
}
}
#[derive(Clone, Debug, Default, PartialEq)]
/// Combat feel (`docs/pvp.md`): how fights look. Legacy draws them as 1.8.9 did; what the
/// game sends to a server never changes, so a vanilla server and its anticheat see 26.3.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Combat {
/// Legacy (1.8.9) instead of Modern.
pub legacy: bool,
/// Keep the attack indicator under Legacy (1.8.9 had none).
pub indicator: bool,
/// Under Legacy, silence the attack sounds 1.9 added (1.8.9 played none on a hit).
pub sounds: bool,
/// The worlds this game hosts (single player and LAN) fight by 1.8.9's rules: no attack
/// cooldown, no sweep, 1.8 weapon damage, effects, enchantments and critical hits
/// (`horizon_client::legacy_combat`). Never used as a client of a server.
pub rules: bool,
}
impl Combat {
/// Whether this client leaves out sound `name` a server sent: under Legacy with its
/// sounds, the `entity.player.attack.*` family (strong, weak, crit, sweep, knockback,
/// nodamage), which 1.9 brought with the attack cooldown.
pub fn mutes_sound(&self, name: &str) -> bool {
let name = name.strip_prefix("minecraft:").unwrap_or(name);
self.legacy && self.sounds && name.starts_with("entity.player.attack.")
}
/// Whether this client leaves out particles of `ty` a server sent: under Legacy, the
/// sweep and the damage hearts, which 1.9 brought (1.8.9's hits show crits only).
pub fn hides_particle(&self, ty: crate::particles::ParticleType) -> bool {
use crate::particles::ParticleType as T;
self.legacy && matches!(ty, T::SweepAttack | T::DamageIndicator)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Pvp {
pub crosshair: Crosshair,
pub outline: Outline,
@@ -690,6 +790,28 @@ pub struct Pvp {
pub hud: Hud,
pub tweaks: Tweaks,
pub chat: ChatOptions,
/// Where each HUD widget sits and its size.
pub layout: crate::pvp_hud::Layout,
/// The key that opens the HUD editor from the game (unbound at first).
pub editor_key: String,
pub combat: Combat,
}
/// The HUD editor key's name for the controls (`Extras::set_key`).
pub const HUD_EDITOR_KEY: &str = "horizon.hud_editor";
impl Default for Pvp {
fn default() -> Self {
Self {
crosshair: Crosshair::default(),
outline: Outline::default(),
hit: Hit::default(),
hud: Hud::default(),
tweaks: Tweaks::default(),
chat: ChatOptions::default(),
layout: crate::pvp_hud::Layout::default(),
editor_key: "key.keyboard.unknown".into(),
combat: Combat::default(),
}
}
}
fn flag(value: &str, d: bool) -> bool {
match value {
@@ -743,6 +865,15 @@ impl Pvp {
"hudHeld" => u.held = flag(value, u.held),
"hudHeldCorner" => u.held_corner = Corner::parse(value, u.held_corner),
"hudBackground" => u.background = flag(value, u.background),
"hudOpacity" => u.opacity = num(value, HUD_OPACITIES, u.opacity),
"hudTextColour" => {
u.text = Colour::parse(value)
.filter(|c| *c != Colour::Inverted)
.unwrap_or(u.text)
}
"hudShadow" => u.shadow = flag(value, u.shadow),
"hudPlace" => self.layout.parse(value),
"hudEditorKey" if value.starts_with("key.") => self.editor_key = value.to_owned(),
"hudPing" => u.ping = flag(value, u.ping),
"hudPingCorner" => u.ping_corner = Corner::parse(value, u.ping_corner),
"hudCoords" => u.coords = flag(value, u.coords),
@@ -751,6 +882,18 @@ impl Pvp {
"hudServerCorner" => u.server_corner = Corner::parse(value, u.server_corner),
"hudCombo" => u.combo = flag(value, u.combo),
"hudComboCorner" => u.combo_corner = Corner::parse(value, u.combo_corner),
"hudFps" => u.fps = flag(value, u.fps),
"hudFpsCorner" => u.fps_corner = Corner::parse(value, u.fps_corner),
"hudCps" => u.cps = flag(value, u.cps),
"hudCpsCorner" => u.cps_corner = Corner::parse(value, u.cps_corner),
"hudKeys" => u.keys = flag(value, u.keys),
"hudKeysCorner" => u.keys_corner = Corner::parse(value, u.keys_corner),
"hudClock" => u.clock = flag(value, u.clock),
"hudClockCorner" => u.clock_corner = Corner::parse(value, u.clock_corner),
"hudReach" => u.reach = flag(value, u.reach),
"hudReachCorner" => u.reach_corner = Corner::parse(value, u.reach_corner),
"hudSpeed" => u.speed = flag(value, u.speed),
"hudSpeedCorner" => u.speed_corner = Corner::parse(value, u.speed_corner),
"numericEnchants" => t.numeric_enchants = flag(value, t.numeric_enchants),
"lowFire" => t.fire_lower = num(value, FIRE_LOWER, t.fire_lower),
"shieldSize" => t.shield_size = num(value, SHIELD_SIZES, t.shield_size),
@@ -767,6 +910,14 @@ impl Pvp {
"chatCompact" => self.chat.compact = flag(value, self.chat.compact),
"chatCopy" => self.chat.copy = flag(value, self.chat.copy),
"chatSearch" => self.chat.search = flag(value, self.chat.search),
"combatFeel" => match value {
"legacy" => self.combat.legacy = true,
"modern" => self.combat.legacy = false,
_ => {}
},
"combatIndicator" => self.combat.indicator = flag(value, self.combat.indicator),
"combatSounds" => self.combat.sounds = flag(value, self.combat.sounds),
"combatRules" => self.combat.rules = flag(value, self.combat.rules),
"viewTime" => {
t.time = match value {
"off" => None,
@@ -838,6 +989,35 @@ impl Pvp {
u.combo,
u.combo_corner.name(),
);
let _ = write!(
out,
"hudFps:{}\nhudFpsCorner:{}\nhudCps:{}\nhudCpsCorner:{}\nhudKeys:{}\nhudKeysCorner:{}\n",
u.fps,
u.fps_corner.name(),
u.cps,
u.cps_corner.name(),
u.keys,
u.keys_corner.name(),
);
let _ = write!(
out,
"hudClock:{}\nhudClockCorner:{}\nhudReach:{}\nhudReachCorner:{}\nhudSpeed:{}\nhudSpeedCorner:{}\n",
u.clock,
u.clock_corner.name(),
u.reach,
u.reach_corner.name(),
u.speed,
u.speed_corner.name(),
);
let _ = write!(
out,
"hudOpacity:{}\nhudTextColour:{}\nhudShadow:{}\n",
u.opacity,
u.text.name(),
u.shadow,
);
self.layout.serialize(out);
let _ = writeln!(out, "hudEditorKey:{}", self.editor_key);
let t = &self.tweaks;
let _ = write!(
out,
@@ -862,6 +1042,13 @@ impl Pvp {
"chatTimestamps:{}\nchatCompact:{}\nchatCopy:{}\nchatSearch:{}\n",
c.timestamps, c.compact, c.copy, c.search,
);
let c = &self.combat;
let feel = if c.legacy { "legacy" } else { "modern" };
let _ = write!(
out,
"combatFeel:{feel}\ncombatIndicator:{}\ncombatSounds:{}\ncombatRules:{}\n",
c.indicator, c.sounds, c.rules
);
}
}
@@ -955,7 +1142,27 @@ opts! {
HudCombo, "hud_combo", "Combo counter",
"Hits in a row the server confirmed, until you are hurt or 3 seconds pass without one.";
HudComboCorner, "hud_combo_corner", "Combo corner", "Where the combo shows.";
HudFps, "hud_fps", "FPS", "Frames drawn in the last second.";
HudFpsCorner, "hud_fps_corner", "FPS corner", "Where the FPS shows.";
HudCps, "hud_cps", "Clicks per second", "Your left and right clicks in the last second.";
HudCpsCorner, "hud_cps_corner", "CPS corner", "Where the clicks per second show.";
HudKeys, "hud_keys", "Keystrokes",
"Your movement keys, mouse buttons and jump, lit while you hold them, with clicks per second.";
HudKeysCorner, "hud_keys_corner", "Keystrokes corner", "Where the keystrokes show.";
HudClock, "hud_clock", "Clock", "Your computer's time.";
HudClockCorner, "hud_clock_corner", "Clock corner", "Where the clock shows.";
HudReach, "hud_reach", "Reach",
"How far from your eyes your last hit landed, for 3 seconds. It only measures: your reach stays vanilla's.";
HudReachCorner, "hud_reach_corner", "Reach corner", "Where the reach shows.";
HudSpeed, "hud_speed", "Speed", "How fast you move across the ground, in blocks per second.";
HudSpeedCorner, "hud_speed_corner", "Speed corner", "Where the speed shows.";
HudBackground, "hud_background", "Widget backgrounds", "A dark box behind each widget.";
HudOpacity, "hud_opacity", "Background opacity", "How dark the boxes behind the widgets are.";
HudTextColour, "hud_text_colour", "Text colour",
"The widgets' text colour. Durability keeps its green to red.";
HudShadow, "hud_shadow", "Text shadow", "A shadow under the widgets' text, as vanilla's HUD text has.";
HudEditorKey, "hud_editor_key", "HUD editor key",
"Opens the HUD editor from the game. Click, then press a key; Escape unbinds it.";
NumericEnchants, "numeric_enchants", "Enchantment levels as numbers",
"Tooltips and the enchanting table show Sharpness 5 instead of Sharpness V.";
FireLower, "fire_lower", "Lower fire",
@@ -980,6 +1187,14 @@ opts! {
"Clicking a message in the open chat copies its text, unless the click does something else.";
ChatSearch, "chat_search", "Chat search",
"Ctrl+F in the open chat: what you type shows only the messages holding it. Enter or Ctrl+F again stops.";
CombatFeel, "combat_feel", "Combat feel",
"Legacy draws fights as 1.8.9 did: the item in your hand, its swing, eating, the bow and a sword held up while you hold use, without the dip after each hit or the attack indicator. Only the look: what you send a server stays the same.";
CombatIndicator, "combat_indicator", "Attack indicator in Legacy",
"Keeps the attack indicator under Legacy, which 1.8.9 didn't have.";
CombatSounds, "combat_sounds", "1.8 hit sounds",
"Under Legacy, leaves out the attack sounds 1.9 added (strong, weak, sweep, critical...). Hurt sounds stay.";
CombatRules, "combat_rules", "1.8 combat in worlds you host",
"Single player and the worlds you open to LAN fight by 1.8.9's rules: no attack cooldown or sweep, 1.8 weapon damage, Strength, Sharpness and critical hits. Servers you join keep their own rules.";
}
/// The PvP & HUD page: headers (language keys) and options.
pub fn rows() -> Vec<Result<Opt, &'static str>> {
@@ -1030,7 +1245,23 @@ pub fn rows() -> Vec<Result<Opt, &'static str>> {
HudServerCorner,
HudCombo,
HudComboCorner,
HudFps,
HudFpsCorner,
HudCps,
HudCpsCorner,
HudKeys,
HudKeysCorner,
HudClock,
HudClockCorner,
HudReach,
HudReachCorner,
HudSpeed,
HudSpeedCorner,
HudBackground,
HudOpacity,
HudTextColour,
HudShadow,
HudEditorKey,
]
.map(Ok),
);
@@ -1043,6 +1274,8 @@ pub fn rows() -> Vec<Result<Opt, &'static str>> {
rows.extend([ViewTime, ViewWeather].map(Ok));
rows.push(Err("horizon.pvp.header.chat"));
rows.extend([ChatTimestamps, ChatCompact, ChatCopy, ChatSearch].map(Ok));
rows.push(Err("horizon.pvp.header.combat"));
rows.extend([CombatFeel, CombatIndicator, CombatSounds, CombatRules].map(Ok));
rows
}
impl Opt {
@@ -1054,10 +1287,19 @@ impl Opt {
OutlineColour | OutlineOpacity | OutlineThickness | OutlineFill => Some(Outline),
HitColour | HitOpacity => Some(Hit),
HudArmour | HudEffects | HudHeld | HudPing | HudCoords | HudServer | HudCombo
| HudBackground | NumericEnchants => None,
| HudFps | HudCps | HudKeys | HudClock | HudReach | HudSpeed | HudBackground
| HudTextColour | HudShadow | HudEditorKey | NumericEnchants => None,
HudOpacity => Some(HudBackground),
HudFpsCorner => Some(HudFps),
HudCpsCorner => Some(HudCps),
HudKeysCorner => Some(HudKeys),
HudClockCorner => Some(HudClock),
HudReachCorner => Some(HudReach),
HudSpeedCorner => Some(HudSpeed),
FireLower | ShieldSize | TotemSize | GlintColour | ClearWater | ClearLava => None,
ViewTime | ViewWeather => None,
ChatTimestamps | ChatCompact | ChatCopy | ChatSearch => None,
CombatFeel | CombatIndicator | CombatSounds | CombatRules => None,
HudPingCorner => Some(HudPing),
HudCoordsCorner => Some(HudCoords),
HudServerCorner => Some(HudServer),
@@ -1081,10 +1323,17 @@ impl Opt {
Opt::HudEffects => p.hud.effects,
Opt::HudHeld => p.hud.held,
Opt::HudBackground => p.hud.background,
Opt::HudShadow => p.hud.shadow,
Opt::HudPing => p.hud.ping,
Opt::HudCoords => p.hud.coords,
Opt::HudServer => p.hud.server,
Opt::HudCombo => p.hud.combo,
Opt::HudFps => p.hud.fps,
Opt::HudCps => p.hud.cps,
Opt::HudKeys => p.hud.keys,
Opt::HudClock => p.hud.clock,
Opt::HudReach => p.hud.reach,
Opt::HudSpeed => p.hud.speed,
Opt::NumericEnchants => p.tweaks.numeric_enchants,
Opt::ClearWater => p.tweaks.clear_water,
Opt::ClearLava => p.tweaks.clear_lava,
@@ -1092,6 +1341,9 @@ impl Opt {
Opt::ChatCompact => p.chat.compact,
Opt::ChatCopy => p.chat.copy,
Opt::ChatSearch => p.chat.search,
Opt::CombatIndicator => p.combat.indicator,
Opt::CombatSounds => p.combat.sounds,
Opt::CombatRules => p.combat.rules,
_ => return None,
})
}
@@ -1124,6 +1376,15 @@ impl Opt {
Opt::HudCoordsCorner => corner_label(p.hud.coords_corner),
Opt::HudServerCorner => corner_label(p.hud.server_corner),
Opt::HudComboCorner => corner_label(p.hud.combo_corner),
Opt::HudFpsCorner => corner_label(p.hud.fps_corner),
Opt::HudCpsCorner => corner_label(p.hud.cps_corner),
Opt::HudKeysCorner => corner_label(p.hud.keys_corner),
Opt::HudClockCorner => corner_label(p.hud.clock_corner),
Opt::HudReachCorner => corner_label(p.hud.reach_corner),
Opt::HudSpeedCorner => corner_label(p.hud.speed_corner),
Opt::HudOpacity => format!("{}%", p.hud.opacity),
Opt::HudTextColour => p.hud.text.label(),
Opt::HudEditorKey => crate::keybinds::display_name(&p.editor_key).plain(),
Opt::FireLower => match p.tweaks.fire_lower {
0 => crate::lang::get_or("Off", "Off"),
v => format!("{v}%"),
@@ -1134,6 +1395,10 @@ impl Opt {
Some(colour) => colour.label(),
None => crate::lang::get_or("Off", "Off"),
},
Opt::CombatFeel => match p.combat.legacy {
true => crate::lang::get_or("horizon.pvp.combat_feel.legacy", "Legacy (1.8.9)"),
false => crate::lang::get_or("horizon.pvp.combat_feel.modern", "Modern"),
},
Opt::ViewTime => p.tweaks.time.map_or_else(world_label, ViewTime::label),
Opt::ViewWeather => p
.tweaks
@@ -1191,6 +1456,11 @@ impl Opt {
Opt::HudHeld => u.held = !u.held,
Opt::HudHeldCorner => u.held_corner = corner(u.held_corner),
Opt::HudBackground => u.background = !u.background,
Opt::HudOpacity => u.opacity = step_by(u.opacity, HUD_OPACITIES, 10, back),
Opt::HudTextColour => u.text = u.text.step_solid(back),
Opt::HudShadow => u.shadow = !u.shadow,
// Bound through the controls' key capture (`Item::key_name`).
Opt::HudEditorKey => {}
Opt::HudPing => u.ping = !u.ping,
Opt::HudPingCorner => u.ping_corner = corner(u.ping_corner),
Opt::HudCoords => u.coords = !u.coords,
@@ -1199,6 +1469,18 @@ impl Opt {
Opt::HudServerCorner => u.server_corner = corner(u.server_corner),
Opt::HudCombo => u.combo = !u.combo,
Opt::HudComboCorner => u.combo_corner = corner(u.combo_corner),
Opt::HudFps => u.fps = !u.fps,
Opt::HudFpsCorner => u.fps_corner = corner(u.fps_corner),
Opt::HudCps => u.cps = !u.cps,
Opt::HudCpsCorner => u.cps_corner = corner(u.cps_corner),
Opt::HudKeys => u.keys = !u.keys,
Opt::HudKeysCorner => u.keys_corner = corner(u.keys_corner),
Opt::HudClock => u.clock = !u.clock,
Opt::HudClockCorner => u.clock_corner = corner(u.clock_corner),
Opt::HudReach => u.reach = !u.reach,
Opt::HudReachCorner => u.reach_corner = corner(u.reach_corner),
Opt::HudSpeed => u.speed = !u.speed,
Opt::HudSpeedCorner => u.speed_corner = corner(u.speed_corner),
Opt::NumericEnchants => p.tweaks.numeric_enchants = !p.tweaks.numeric_enchants,
Opt::FireLower => t.fire_lower = step_by(t.fire_lower, FIRE_LOWER, 10, back),
Opt::ShieldSize => t.shield_size = step_by(t.shield_size, SHIELD_SIZES, 10, back),
@@ -1216,6 +1498,10 @@ impl Opt {
Opt::ChatCompact => p.chat.compact = !p.chat.compact,
Opt::ChatCopy => p.chat.copy = !p.chat.copy,
Opt::ChatSearch => p.chat.search = !p.chat.search,
Opt::CombatFeel => p.combat.legacy = !p.combat.legacy,
Opt::CombatIndicator => p.combat.indicator = !p.combat.indicator,
Opt::CombatSounds => p.combat.sounds = !p.combat.sounds,
Opt::CombatRules => p.combat.rules = !p.combat.rules,
Opt::ViewWeather => {
let all: Vec<_> = std::iter::once(None)
.chain(ViewWeather::ALL.map(Some))
@@ -1518,4 +1804,32 @@ mod tests {
assert_eq!(en.get(key), Some(*english), "{key}");
}
}
#[test]
fn legacy_leaves_out_what_1_9_added_to_a_hit() {
use crate::particles::ParticleType as T;
let modern = Combat::default();
let legacy = Combat {
legacy: true,
..Combat::default()
};
let sounds = Combat {
sounds: true,
..legacy
};
for name in [
"minecraft:entity.player.attack.strong",
"entity.player.attack.sweep",
"minecraft:entity.player.attack.nodamage",
] {
assert!(sounds.mutes_sound(name), "{name}");
assert!(!legacy.mutes_sound(name), "only with the sounds option");
assert!(!modern.mutes_sound(name));
}
// 1.8.9 had the hurt sound: it stays.
assert!(!sounds.mutes_sound("minecraft:entity.player.hurt"));
assert!(legacy.hides_particle(T::SweepAttack) && legacy.hides_particle(T::DamageIndicator));
assert!(!legacy.hides_particle(T::Crit) && !legacy.hides_particle(T::EnchantedHit));
assert!(!modern.hides_particle(T::SweepAttack));
}
}
+451
View File
@@ -214,6 +214,320 @@ impl Combo {
}
}
/// Clicks per second: the presses of the last second, kept for the widgets that are on.
#[derive(Default)]
pub struct Clicks {
/// Press times in seconds, oldest first; at most [`Clicks::KEEP`].
times: std::collections::VecDeque<f64>,
}
impl Clicks {
/// More than any hand clicks in a second: the ring never grows past it.
const KEEP: usize = 64;
pub fn press(&mut self, now: f64) {
if self.times.len() == Self::KEEP {
self.times.pop_front();
}
self.times.push_back(now);
}
/// The presses in the second up to `now`.
pub fn per_second(&mut self, now: f64) -> u32 {
while self.times.front().is_some_and(|&t| now - t >= 1.0) {
self.times.pop_front();
}
self.times.len() as u32
}
}
/// Horizontal speed in blocks per second, from the player's own position sampled at most
/// every [`Speed::SAMPLE`] seconds (nothing is asked of the server).
#[derive(Default)]
pub struct Speed {
last: Option<([f64; 2], f64)>,
/// Tenths of a block per second.
tenths: u32,
}
impl Speed {
pub const SAMPLE: f64 = 0.25;
pub fn sample(&mut self, x: f64, z: f64, now: f64) -> u32 {
match self.last {
Some((_, at)) if now - at < Self::SAMPLE => {}
Some(([lx, lz], at)) => {
let d = ((x - lx).powi(2) + (z - lz).powi(2)).sqrt();
// A teleport or respawn isn't speed.
let v = d / (now - at);
self.tenths = if v > 200.0 {
0
} else {
(v * 10.0).round() as u32
};
self.last = Some(([x, z], now));
}
None => self.last = Some(([x, z], now)),
}
self.tenths
}
}
/// The reach display: how far the last hit this player made was, measured from the eyes to
/// the point the crosshair's ray met the target's box. It measures what the client already
/// computed for the attack and changes nothing about it.
#[derive(Default)]
pub struct Reach {
last: Option<(f64, f64)>,
}
impl Reach {
/// How long the last hit's distance stays shown.
pub const SHOWN: f64 = 3.0;
pub fn hit(&mut self, distance: f64, now: f64) {
self.last = Some((distance, now));
}
/// Hundredths of a block, while the last hit is recent.
pub fn hundredths(&self, now: f64) -> Option<u32> {
let (d, at) = self.last?;
(now - at <= Self::SHOWN).then(|| (d * 100.0).round() as u32)
}
}
/// `n` hundredths as "3.05".
pub fn hundredths(n: u32) -> String {
format!("{}.{:02}", n / 100, n % 100)
}
/// `n` tenths as "4.3".
pub fn tenths(n: u32) -> String {
format!("{}.{}", n / 10, n % 10)
}
/// The local time as "14:05".
pub fn clock(hour: u8, minute: u8) -> String {
format!("{hour:02}:{minute:02}")
}
/// The keystrokes widget's keys, in drawing order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Key {
Forward,
Left,
Back,
Right,
Attack,
Use,
Jump,
}
impl Key {
pub const ALL: [Key; 7] = [
Key::Forward,
Key::Left,
Key::Back,
Key::Right,
Key::Attack,
Key::Use,
Key::Jump,
];
/// The key mapping it shows.
pub fn mapping(self) -> &'static str {
match self {
Key::Forward => "key.forward",
Key::Left => "key.left",
Key::Back => "key.back",
Key::Right => "key.right",
Key::Attack => "key.attack",
Key::Use => "key.use",
Key::Jump => "key.jump",
}
}
}
/// The keystrokes' key size and the gap between keys, in GUI pixels.
pub const KEY: f32 = 22.0;
pub const KEY_GAP: f32 = 2.0;
/// The space bar's height.
pub const SPACE: f32 = 12.0;
/// Where each key of the keystrokes widget sits in its box: W above A S D, the two mouse
/// buttons under them, the space bar at the bottom, as `(x, y, w, h)`.
pub fn key_rect(key: Key) -> (f32, f32, f32, f32) {
let step = KEY + KEY_GAP;
let full = 3.0 * KEY + 2.0 * KEY_GAP;
let half = (full - KEY_GAP) / 2.0;
match key {
Key::Forward => (step, 0.0, KEY, KEY),
Key::Left => (0.0, step, KEY, KEY),
Key::Back => (step, step, KEY, KEY),
Key::Right => (2.0 * step, step, KEY, KEY),
Key::Attack => (0.0, 2.0 * step, half, KEY),
Key::Use => (half + KEY_GAP, 2.0 * step, half, KEY),
Key::Jump => (0.0, 3.0 * step, full, SPACE),
}
}
/// The keystrokes widget's size.
pub fn keys_size() -> (f32, f32) {
let (_, y, w, h) = key_rect(Key::Jump);
(w, y + h)
}
/// The HUD widgets, for their places on screen ([`Layout`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WidgetId {
Armour,
Effects,
Held,
Ping,
Coords,
Server,
Combo,
Fps,
Cps,
Keys,
Clock,
Reach,
Speed,
}
impl WidgetId {
pub const ALL: [WidgetId; 13] = [
WidgetId::Armour,
WidgetId::Effects,
WidgetId::Held,
WidgetId::Ping,
WidgetId::Coords,
WidgetId::Server,
WidgetId::Combo,
WidgetId::Fps,
WidgetId::Cps,
WidgetId::Keys,
WidgetId::Clock,
WidgetId::Reach,
WidgetId::Speed,
];
pub fn name(self) -> &'static str {
match self {
WidgetId::Armour => "armour",
WidgetId::Effects => "effects",
WidgetId::Held => "held",
WidgetId::Ping => "ping",
WidgetId::Coords => "coords",
WidgetId::Server => "server",
WidgetId::Combo => "combo",
WidgetId::Fps => "fps",
WidgetId::Cps => "cps",
WidgetId::Keys => "keys",
WidgetId::Clock => "clock",
WidgetId::Reach => "reach",
WidgetId::Speed => "speed",
}
}
pub fn index(self) -> usize {
self as usize
}
}
/// Where a widget sits: in its corner, stacked with the others there (`at` is `None`), or at a
/// place the player dragged it to, as fractions of the room the screen leaves around the box
/// (0 at the left or top edge, 1 at the right or bottom), so it stays on screen at any size.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Place {
pub at: Option<(f32, f32)>,
/// Its size in percent.
pub scale: u8,
}
impl Default for Place {
fn default() -> Self {
Self {
at: None,
scale: 100,
}
}
}
pub const SCALES: (u8, u8) = (50, 200);
/// Every widget's place.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Layout(pub [Place; 13]);
impl Layout {
pub fn get(&self, id: WidgetId) -> Place {
self.0[id.index()]
}
pub fn get_mut(&mut self, id: WidgetId) -> &mut Place {
&mut self.0[id.index()]
}
/// One `hudPlace` value: `armour,0.25,0.5,150`, or `armour,corner,,150`.
pub fn parse(&mut self, value: &str) {
let mut parts = value.split(',');
let Some(id) = parts
.next()
.and_then(|n| WidgetId::ALL.into_iter().find(|w| w.name() == n))
else {
return;
};
let (x, y, scale) = (parts.next(), parts.next(), parts.next());
let frac = |v: Option<&str>| {
v.and_then(|v| v.parse::<f32>().ok())
.filter(|v| v.is_finite())
.map(|v| v.clamp(0.0, 1.0))
};
let place = self.get_mut(id);
place.at = frac(x).zip(frac(y));
if let Some(s) = scale.and_then(|s| s.parse::<u8>().ok()) {
place.scale = s.clamp(SCALES.0, SCALES.1);
}
}
/// The `hudPlace` lines of the widgets that left their corner or their size.
pub fn serialize(&self, out: &mut String) {
use std::fmt::Write;
for id in WidgetId::ALL {
let p = self.get(id);
if p == Place::default() {
continue;
}
let _ = match p.at {
Some((x, y)) => writeln!(out, "hudPlace:{},{x:.4},{y:.4},{}", id.name(), p.scale),
None => writeln!(out, "hudPlace:{},corner,,{}", id.name(), p.scale),
};
}
}
}
/// A box `w` x `h` placed at fractions `(fx, fy)` of the room left on a `screen`.
pub fn from_fractions((fx, fy): (f32, f32), (w, h): (f32, f32), screen: (f32, f32)) -> (f32, f32) {
(
(fx * (screen.0 - w).max(0.0)).round(),
(fy * (screen.1 - h).max(0.0)).round(),
)
}
/// The fractions that put a `w` x `h` box at `(x, y)` on a `screen`, kept on screen.
pub fn to_fractions((x, y): (f32, f32), (w, h): (f32, f32), screen: (f32, f32)) -> (f32, f32) {
let frac = |v: f32, room: f32| {
if room > 0.0 {
(v / room).clamp(0.0, 1.0)
} else {
0.0
}
};
(frac(x, screen.0 - w), frac(y, screen.1 - h))
}
/// How near, in GUI pixels, an edge must come to another to snap to it.
pub const SNAP: f32 = 4.0;
/// Snaps a box's start `x` of length `w` along one axis of length `screen`: to the screen's
/// edges and middle, and to the edges of the `others` boxes (`(start, length)`), where one
/// is within [`SNAP`]. Returns the new start and the line it snapped to, if any.
pub fn snap(x: f32, w: f32, screen: f32, others: &[(f32, f32)]) -> (f32, Option<f32>) {
let mut best: Option<(f32, f32, f32)> = None;
let mut consider = |start: f32, line: f32| {
let d = (start - x).abs();
if d <= SNAP && best.is_none_or(|(b, _, _)| d < b) {
best = Some((d, start, line));
}
};
// The screen's edges, with the corners' margin, and its middle.
consider(2.0, 0.0);
consider(screen - 2.0 - w, screen);
consider((screen - w) / 2.0, screen / 2.0);
for &(o, ow) in others {
// Side by side, or lined up on the same edge.
consider(o + ow, o + ow);
consider(o - w, o);
consider(o, o);
consider(o + ow - w, o + ow);
}
match best {
Some((_, start, line)) => (start.clamp(0.0, (screen - w).max(0.0)), Some(line)),
None => (x.clamp(0.0, (screen - w).max(0.0)), None),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -338,4 +652,141 @@ mod tests {
assert_eq!(h, 18.0 + 10.0 + 20.0 + 2.0 * PAD - 2.0);
assert!(size(&[]) == (0.0, 0.0));
}
#[test]
fn clicks_count_the_presses_of_the_last_second() {
let mut c = Clicks::default();
for t in [0.0, 0.1, 0.5, 0.9] {
c.press(t);
}
assert_eq!(c.per_second(0.95), 4);
// 1.0 s after the first press it has left the window.
assert_eq!(c.per_second(1.0), 3);
assert_eq!(c.per_second(1.6), 1);
assert_eq!(c.per_second(5.0), 0);
// The ring never keeps more than 64 presses.
for i in 0..200 {
c.press(10.0 + f64::from(i) * 0.001);
}
assert_eq!(c.per_second(10.2), 64);
}
#[test]
fn speed_is_horizontal_blocks_per_second_between_samples() {
let mut s = Speed::default();
assert_eq!(s.sample(0.0, 0.0, 0.0), 0);
// Sprinting: 5.612 blocks per second along x, with a jump (y is ignored).
assert_eq!(s.sample(0.5, 0.0, 0.1), 0, "too soon for a new sample");
assert_eq!(s.sample(1.403, 0.0, 0.25), 56);
// 3 east and 4 south in a second: 5 blocks per second.
assert_eq!(s.sample(1.403 + 3.0, 4.0, 1.25), 50);
// A teleport reads as standing still.
assert_eq!(s.sample(1000.0, 4.0, 1.5), 0);
assert_eq!(tenths(56), "5.6");
}
#[test]
fn reach_shows_the_last_hit_for_three_seconds() {
let mut r = Reach::default();
assert_eq!(r.hundredths(0.0), None);
r.hit(2.954, 1.0);
assert_eq!(r.hundredths(1.5), Some(295));
assert_eq!(hundredths(295), "2.95");
assert_eq!(hundredths(300), "3.00");
assert_eq!(r.hundredths(4.1), None);
}
#[test]
fn the_clock_reads_hours_and_minutes() {
assert_eq!(clock(14, 5), "14:05");
assert_eq!(clock(0, 0), "00:00");
}
#[test]
fn keystrokes_keys_tile_their_box_without_overlap() {
let (w, h) = keys_size();
assert_eq!((w, h), (70.0, 3.0 * 24.0 + 12.0));
for (i, a) in Key::ALL.iter().enumerate() {
let (x, y, kw, kh) = key_rect(*a);
assert!(
x >= 0.0 && y >= 0.0 && x + kw <= w && y + kh <= h,
"{a:?} inside"
);
for b in &Key::ALL[i + 1..] {
let (bx, by, bw, bh) = key_rect(*b);
let apart = x + kw <= bx || bx + bw <= x || y + kh <= by || by + bh <= y;
assert!(apart, "{a:?} and {b:?} overlap");
}
}
}
#[test]
fn places_round_trip_and_only_moved_widgets_are_written() {
let mut l = Layout::default();
let mut text = String::new();
l.serialize(&mut text);
assert_eq!(text, "", "a vanilla layout writes nothing");
*l.get_mut(WidgetId::Keys) = Place {
at: Some((0.25, 1.0)),
scale: 150,
};
l.get_mut(WidgetId::Fps).scale = 75;
l.serialize(&mut text);
assert_eq!(
text,
"hudPlace:fps,corner,,75\nhudPlace:keys,0.2500,1.0000,150\n"
);
let mut back = Layout::default();
for line in text.lines() {
back.parse(line.split_once(':').unwrap().1);
}
assert_eq!(back, l);
// Out of range values are clamped, unknown widgets and bad numbers ignored.
back.parse("speed,-3,7,250");
assert_eq!(back.get(WidgetId::Speed).at, Some((0.0, 1.0)));
assert_eq!(back.get(WidgetId::Speed).scale, 200);
back.parse("radar,0.5,0.5,100");
back.parse("clock,NaN,0.5,100");
assert_eq!(back.get(WidgetId::Clock).at, None);
}
#[test]
fn fractions_keep_a_box_on_screen_at_any_size() {
let screen = (480.0, 270.0);
let at = to_fractions((100.0, 50.0), (80.0, 20.0), screen);
assert_eq!(from_fractions(at, (80.0, 20.0), screen), (100.0, 50.0));
// A box at the right edge stays at the right edge on a wider screen.
let right = to_fractions((400.0, 0.0), (80.0, 20.0), screen);
assert_eq!(right, (1.0, 0.0));
assert_eq!(
from_fractions(right, (80.0, 20.0), (960.0, 540.0)),
(880.0, 0.0)
);
// Dragged past the edge: kept inside.
assert_eq!(
to_fractions((-30.0, 900.0), (80.0, 20.0), screen),
(0.0, 1.0)
);
}
#[test]
fn boxes_snap_to_screen_edges_middle_and_each_other() {
// Near the left margin.
assert_eq!(snap(4.5, 50.0, 480.0, &[]), (2.0, Some(0.0)));
// Centred: the middle of 480 for a 50-wide box starts at 215.
assert_eq!(snap(213.0, 50.0, 480.0, &[]), (215.0, Some(240.0)));
// Beside another box (100..160): its start goes to 160.
assert_eq!(
snap(163.0, 50.0, 480.0, &[(100.0, 60.0)]),
(160.0, Some(160.0))
);
// Lined up with its left edge.
assert_eq!(
snap(98.0, 50.0, 480.0, &[(100.0, 60.0)]),
(100.0, Some(100.0))
);
// Too far from anything: stays, but never off screen.
assert_eq!(snap(300.0, 50.0, 480.0, &[(100.0, 60.0)]), (300.0, None));
assert_eq!(snap(470.0, 50.0, 480.0, &[]), (430.0, None));
}
}
+148 -3
View File
@@ -975,11 +975,32 @@ impl TextField {
}
}
/// `ScreenRectangle.intersection`: the part of both rectangles, or
/// `ScreenRectangle.empty()` (`0, 0, 0, 0`, which clips everything) when they
/// do not overlap.
fn intersect(a: [i32; 4], b: [i32; 4]) -> [i32; 4] {
let rect = [
a[0].max(b[0]),
a[1].max(b[1]),
a[2].min(b[2]),
a[3].min(b[3]),
];
if rect[0] < rect[2] && rect[1] < rect[3] {
rect
} else {
[0, 0, 0, 0]
}
}
/// Draws the calls with the HUD batch: sprites nine-sliced, textures from
/// the atlas (`textures/gui/x.png` is `gui/x`; tiled textures from their
/// corner), scissor clipping, and the tooltip at the mouse.
pub fn paint(batch: &mut HudBatch, atlas: &HudAtlas, draws: &[Draw]) {
let mut clip: Option<(usize, [i32; 4])> = None;
// `GuiGraphicsExtractor.ScissorStack`: a scissor clips what is drawn since
// it opened, cut to the screen while none is open and to the one around it
// otherwise; closing it puts the enclosing one back.
let screen = [0, 0, batch.width as i32, batch.height as i32];
let mut clips: Vec<(usize, [i32; 4])> = Vec::new();
let mut tooltip = None;
for d in draws {
match d {
@@ -1083,10 +1104,11 @@ pub fn paint(batch: &mut HudBatch, atlas: &HudAtlas, draws: &[Draw]) {
);
}
Draw::Scissor { x0, y0, x1, y1 } => {
clip = Some((batch.vertices.len(), [*x0, *y0, *x1, *y1]))
let outer = clips.last().map_or(screen, |&(_, rect)| rect);
clips.push((batch.vertices.len(), intersect(outer, [*x0, *y0, *x1, *y1])));
}
Draw::NoScissor => {
if let Some((start, [x0, y0, x1, y1])) = clip.take() {
if let Some((start, [x0, y0, x1, y1])) = clips.pop() {
batch.clip_since(start, x0 as f32, y0 as f32, x1 as f32, y1 as f32);
}
}
@@ -1282,3 +1304,126 @@ mod button_label_tests {
batch.vertices.len()
}
}
#[cfg(test)]
mod scissor_tests {
use super::*;
fn atlas() -> HudAtlas {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
/// The bounds of every quad's six vertices, in draw order.
fn quads(batch: &HudBatch) -> Vec<[f32; 4]> {
batch
.vertices
.as_chunks::<6>()
.0
.iter()
.map(|q| {
let (mut x0, mut y0) = (f32::MAX, f32::MAX);
let (mut x1, mut y1) = (f32::MIN, f32::MIN);
for v in q {
x0 = x0.min(v.pos[0]);
y0 = y0.min(v.pos[1]);
x1 = x1.max(v.pos[0]);
y1 = y1.max(v.pos[1]);
}
[x0, y0, x1, y1]
})
.collect()
}
fn fill(x0: i32, y0: i32, x1: i32, y1: i32) -> Draw {
Draw::Fill {
x0,
y0,
x1,
y1,
color: -1,
}
}
fn scissor(x0: i32, y0: i32, x1: i32, y1: i32) -> Draw {
Draw::Scissor { x0, y0, x1, y1 }
}
/// `GuiGraphicsExtractor.ScissorStack.push`: a scissor inside another is
/// intersected with it (`ScreenRectangle.intersection`), and the outer one
/// still clips what is drawn after the inner one closes.
#[test]
fn a_nested_scissor_is_intersected_with_the_one_around_it() {
let atlas = atlas();
let mut batch = HudBatch::new([320, 240]);
paint(
&mut batch,
&atlas,
&[
scissor(10, 10, 100, 100),
fill(0, 0, 200, 200),
scissor(50, 50, 300, 300),
fill(0, 0, 400, 400),
Draw::NoScissor,
fill(0, 0, 200, 200),
Draw::NoScissor,
],
);
assert_eq!(
quads(&batch),
[
[10.0, 10.0, 100.0, 100.0],
[50.0, 50.0, 100.0, 100.0],
[10.0, 10.0, 100.0, 100.0],
]
);
}
/// A scissor with no scissor around it is cut to the screen, as
/// `ScissorStack.push` intersects with the screen while the stack is empty.
#[test]
fn a_scissor_wider_than_the_screen_is_cut_to_it() {
let atlas = atlas();
let mut batch = HudBatch::new([320, 240]);
paint(
&mut batch,
&atlas,
&[
scissor(-50, -50, 500, 500),
fill(-100, -100, 600, 600),
Draw::NoScissor,
],
);
assert_eq!(quads(&batch), [[0.0, 0.0, 320.0, 240.0]]);
}
/// A scissor that misses the one around it intersects to
/// `ScreenRectangle.empty()`: nothing inside it is drawn, and the outer
/// scissor takes over again when it closes.
#[test]
fn a_scissor_outside_the_one_around_it_draws_nothing() {
let atlas = atlas();
let mut batch = HudBatch::new([320, 240]);
paint(
&mut batch,
&atlas,
&[
scissor(10, 10, 50, 50),
fill(0, 0, 200, 200),
scissor(60, 60, 90, 90),
fill(0, 0, 200, 200),
Draw::NoScissor,
fill(0, 0, 200, 200),
Draw::NoScissor,
fill(0, 0, 200, 200),
],
);
assert_eq!(
quads(&batch),
[
[10.0, 10.0, 50.0, 50.0],
[10.0, 10.0, 50.0, 50.0],
[0.0, 0.0, 200.0, 200.0],
]
);
}
}
+188 -5
View File
@@ -18,7 +18,7 @@ pub fn set_source_volumes(volumes: [f32; 11]) {
pub fn sound_source(event: &str) -> usize {
let e = event.trim_start_matches("minecraft:");
let index = |name: &str| SOUND_SOURCES.iter().position(|n| *n == name).unwrap_or(0);
const HOSTILE: [&str; 25] = [
const HOSTILE: [&str; 34] = [
"zombie",
"skeleton",
"creeper",
@@ -44,6 +44,16 @@ pub fn sound_source(event: &str) -> usize {
"silverfish",
"zombified_piglin",
"wither_skeleton",
"bogged",
"breeze",
"endermite",
"parched",
"warden",
"zombie_villager",
"vex",
"wither",
// Monster's common hurt/death (e.g. Giant) and other shared sounds.
"hostile",
];
if e == "block.potent_sulfur.noxious_gas" {
// PotentSulfurBlock.animateTick, its only caller, plays it as AMBIENT.
@@ -347,7 +357,7 @@ impl Settings {
.parent()
.map(|dir| crate::mod_list::ModList::load(&crate::logging::shared_dir(dir)))
.unwrap_or_default();
let settings = match fs::read(path) {
let mut settings = match fs::read(path) {
Ok(bytes) => {
let text = String::from_utf8_lossy(&bytes);
extras.read_old_options(&extras_text, &text);
@@ -367,6 +377,9 @@ impl Settings {
..Self::default()
},
};
// Horizon's own key bindings live in horizon-extras.txt, not in options.txt.
let emote = settings.extras.emote_key.clone();
settings.keys.set("key.emote", &emote);
settings.describe_for_crashes();
// Options.load: the backend asked for at startup, what a restart is measured from.
Self {
@@ -636,14 +649,17 @@ impl Settings {
pub fn with_option(&self, key: &str, value: &str) -> Result<Self, String> {
let mut file = self.to_file();
file.set_text(key, value)?;
Ok(Self {
let mut next = Self {
horizon: self.horizon.clone(),
controller: self.controller.clone(),
extras: self.extras.clone(),
mods: self.mods.clone(),
video_modes: self.video_modes.clone(),
..Self::from_file(file)
})
};
// Horizon's own bindings aren't in options.txt.
next.keys.set("key.emote", self.keys.get("key.emote"));
Ok(next)
}
/// The `options.txt` text (Options.save).
pub fn serialize(&self) -> String {
@@ -657,7 +673,9 @@ impl Settings {
if let Some(dir) = path.parent() {
self.horizon.save(dir);
self.controller.save(dir);
self.extras.save(dir);
let mut extras = self.extras.clone();
extras.emote_key = self.keys.get("key.emote").to_owned();
extras.save(dir);
self.mods.save(&crate::logging::shared_dir(dir));
}
}
@@ -814,6 +832,7 @@ pub enum Opt {
PadToggleSneak,
PadMoveDeadzone,
PadLookDeadzone,
PadTriggerThreshold,
PadGlyphs,
PadKeyboard,
/// `options.modelPart.*`: one skin layer (index into `options_file::MODEL_PARTS`).
@@ -855,6 +874,57 @@ mod tests {
horizon_narrator::Status::Off
);
}
/// `Monster.getSoundSource`: the verified families and inherited common sounds.
#[test]
fn hostile_families_keep_their_sound_category() {
for (event, source) in [
("entity.zombie.hurt", 5),
("entity.cow.hurt", 6),
("block.stone.break", 4),
("entity.player.hurt", 7),
("entity.arrow.hit", 7),
("music_disc.13", 2),
("item.goat_horn.sound.0", 2),
("weather.rain", 3),
("ambient.cave", 8),
] {
assert_eq!(sound_source(event), source, "{event}");
}
// Explicit sources still take precedence, including H331's arrow route.
let mut audio = crate::audio::Audio::silent(Path::new("/nonexistent/h068-audio"));
audio.capture = Some(Vec::new());
audio.play_on(6, "minecraft:entity.arrow.hit", Some([1.0; 3]), 1.0, 1.0);
audio.play_on(4, "minecraft:entity.warden.hurt", Some([1.0; 3]), 1.0, 1.0);
assert_eq!(
audio
.capture
.as_ref()
.unwrap()
.iter()
.map(|s| s.source)
.collect::<Vec<_>>(),
[6, 4]
);
for family in [
"bogged",
"breeze",
"endermite",
"parched",
"warden",
"zombie_villager",
"vex",
"wither",
"hostile",
] {
for suffix in ["hurt", "death"] {
for prefix in ["", "minecraft:"] {
let event = format!("{prefix}entity.{family}.{suffix}");
assert_eq!(sound_source(&event), 5, "{event}");
}
}
}
}
#[test]
fn three_d_skin_layers_move_from_options_txt_to_the_extras_file() {
// #8091 wrote the switch into options.txt; a player who had it on keeps
@@ -880,6 +950,119 @@ mod tests {
);
let _ = fs::remove_dir_all(&dir);
}
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
"horizon-{name}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn options_txt_lists_only_vanillas_key_mappings() {
// Options.keyMappings has the friends key, then social interactions; Horizon's emote key
// (#10092 put it between them) is not in the file.
let out = Settings::default().serialize();
assert!(!out.contains("emote"), "{out}");
assert!(out.contains(
"\nkey_key.friends:key.keyboard.o\nkey_key.socialInteractions:key.keyboard.p\n"
));
let mut s = Settings::default();
s.keys.set("key.emote", "key.keyboard.g");
assert!(!s.serialize().contains("emote"));
}
#[test]
fn the_emote_key_is_kept_in_the_extras_file() {
let dir = scratch("emote-key");
let options = dir.join("options.txt");
// Untouched: no extras file is made for it.
Settings::default().save(&options);
assert!(!dir.join(crate::extras::FILE).exists());
assert_eq!(
Settings::load(&options).keys.get("key.emote"),
"key.keyboard.b"
);
// Rebound in Controls: saved to horizon-extras.txt, and options.txt stays vanilla's.
let mut s = Settings::load(&options);
s.keys.set("key.emote", "key.keyboard.g");
s.save(&options);
assert!(!fs::read_to_string(&options).unwrap().contains("emote"));
let extras = fs::read_to_string(dir.join(crate::extras::FILE)).unwrap();
assert!(
extras.lines().any(|l| l == "emoteKey:key.keyboard.g"),
"{extras}"
);
let back = Settings::load(&options);
assert_eq!(back.keys.get("key.emote"), "key.keyboard.g");
// horizon-ctl options-set rebuilds from options.txt text and keeps it.
assert_eq!(
back.with_option("fov", "90").unwrap().keys.get("key.emote"),
"key.keyboard.g"
);
// Reset to B and back to the default: the file says so.
let mut s = back;
s.keys.set(
"key.emote",
crate::keybinds::KeyBinds::default_of("key.emote"),
);
s.save(&options);
assert_eq!(
Settings::load(&options).keys.get("key.emote"),
"key.keyboard.b"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn the_emote_key_moves_from_options_txt_to_the_extras_file() {
// #10092 wrote `key_key.emote` into options.txt; a rebound key is kept, the next
// options.txt is vanilla's again.
let dir = scratch("emote-key-move");
let options = dir.join("options.txt");
fs::write(
&options,
"version:4000\nfov:0.5\nkey_key.emote:key.keyboard.h\nkey_key.jump:key.keyboard.j\n",
)
.unwrap();
let s = Settings::load(&options);
assert_eq!(s.keys.get("key.emote"), "key.keyboard.h");
assert_eq!(s.keys.get("key.jump"), "key.keyboard.j");
s.save(&options);
assert!(!fs::read_to_string(&options).unwrap().contains("emote"));
assert_eq!(
Settings::load(&options).keys.get("key.emote"),
"key.keyboard.h"
);
// Once horizon-extras.txt has its own line, a stale options.txt one is ignored.
fs::write(dir.join(crate::extras::FILE), "emoteKey:key.keyboard.k\n").unwrap();
fs::write(&options, "version:4000\nkey_key.emote:key.keyboard.h\n").unwrap();
assert_eq!(
Settings::load(&options).keys.get("key.emote"),
"key.keyboard.k"
);
// A value that is no key is not adopted; an unbound emote key is.
fs::remove_file(dir.join(crate::extras::FILE)).unwrap();
fs::write(&options, "version:4000\nkey_key.emote:banana\n").unwrap();
assert_eq!(
Settings::load(&options).keys.get("key.emote"),
"key.keyboard.b"
);
fs::write(
&options,
"version:4000\nkey_key.emote:key.keyboard.unknown\n",
)
.unwrap();
assert_eq!(
Settings::load(&options).keys.get("key.emote"),
"key.keyboard.unknown"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_option_set_keeps_horizon_files() {
let mut s = Settings::parse("fov:70\n");
@@ -0,0 +1,683 @@
//! What Horizon's searchable settings screens share (`graphics_ui`, `controller_ui`): the frame's
//! geometry, its list of pages, groups and rows, and how the keyboard moves through them. Which
//! settings a screen has, and what they do, stay in that screen; the look comes from
//! `graphics_style`.
use crate::{
graphics_style as style,
hud::{HudAtlas, HudBatch},
lang,
text::Text,
ui,
};
/// The screen's parts in GUI pixels. Down the left: the mark, the search
/// field, the page list, and Undo and Done at the foot. On the right: the
/// plate with the open page's name and its list, and the strip under it that
/// describes the hovered setting. `list_x`, `list_w`, `top` and `bottom` are
/// the list's view.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Columns {
pub(crate) side_x: f32,
pub(crate) side_y: f32,
pub(crate) plate: [f32; 4],
pub(crate) dock: [f32; 4],
pub(crate) list_x: f32,
pub(crate) list_w: f32,
pub(crate) top: f32,
pub(crate) bottom: f32,
}
impl Columns {
pub(crate) fn of(w: f32, h: f32) -> Self {
let side_w = style::CONTROL_W;
let gap = if w >= 560.0 { 16.0 } else { 8.0 };
let pw = (w - 16.0 - side_w - gap).min(432.0).floor();
let side_x = ((w - side_w - gap - pw) / 2.0).floor();
let px = side_x + side_w + gap;
// A short screen (a 720p window at scale 3) gives the margin to the list.
let side_y = if h >= style::TITLED { 24.0 } else { 8.0 };
let dock = [px, h - 8.0 - style::DOCK_H, pw, style::DOCK_H];
let plate = [px, side_y, pw, dock[1] - 4.0 - side_y];
let list_x = px + 8.0;
Self {
side_x,
side_y,
plate,
dock,
list_x,
list_w: pw - 16.0 - style::SCROLLER_W - 2.0,
top: side_y + 30.0,
bottom: plate[1] + plate[3] - 6.0,
}
}
/// The search field, under the mark.
pub(crate) fn search(&self) -> [f32; 4] {
[
self.side_x,
self.side_y + 26.0,
style::CONTROL_W,
style::SEARCH_H,
]
}
/// The search field's clear button, at its right end.
pub(crate) fn clear(&self) -> [f32; 4] {
let [x, y, w, h] = self.search();
[x + w - h, y, h, h]
}
/// Room for vanilla's scroller, whose thumb is 32 high and 8 short of its track.
pub(crate) fn scrolls(&self) -> bool {
self.bottom - self.top >= 40.0
}
pub(crate) fn bar_x(&self) -> f32 {
self.plate[0] + self.plate[2] - 8.0 - style::SCROLLER_W
}
/// A page in the page list, under the search field.
pub(crate) fn page(&self, i: usize) -> [f32; 4] {
[
self.side_x,
self.side_y + 56.0 + i as f32 * 18.0,
style::CONTROL_W,
16.0,
]
}
/// Done (`0`), and Undo over it (`1`): under the page list, level with the strip.
pub(crate) fn button(&self, i: usize) -> [f32; 4] {
let foot = self.dock[1] + self.dock[3] - style::BUTTON_H;
let y = if i == 0 {
foot
} else {
foot - 4.0 - style::BUTTON_H
};
[self.side_x, y, style::CONTROL_W, style::BUTTON_H]
}
/// A row's control column: its button, tick box or slider.
pub(crate) fn track(&self) -> (f32, f32) {
let x = self.list_x + self.list_w - style::INSET - style::CONTROL_W;
(x, style::CONTROL_W)
}
/// A slider's value for the pointer at `x`: the handle's middle follows it.
pub(crate) fn slider_at(&self, x: f32) -> f32 {
let (tx, tw) = self.track();
((x - tx - 5.0) / (tw - 10.0)).clamp(0.0, 1.0)
}
/// A row's whole width at `y`.
pub(crate) fn row(&self, y: f32) -> [f32; 4] {
[self.list_x, y, self.list_w, style::ROW]
}
}
/// A line of the list at `y` in its content: a page's name (only while
/// searching, which shows every page), a group's name with the height of the
/// panel its rows sit on, or a setting.
#[derive(Clone, Copy)]
pub(crate) struct Line<P, S> {
pub(crate) y: f32,
pub(crate) page: P,
pub(crate) group: Option<(&'static str, f32)>,
pub(crate) setting: Option<S>,
}
impl<P, S> Line<P, S> {
pub(crate) fn h(&self) -> f32 {
match (&self.setting, self.group) {
(Some(_), _) => style::ROW,
(None, Some(_)) => style::GROUP_ROW,
(None, None) => style::PAGE_ROW,
}
}
}
/// Lays lines out from the top.
pub(crate) struct Lines<P, S> {
lines: Vec<Line<P, S>>,
y: f32,
}
impl<P: Copy, S: Copy> Lines<P, S> {
pub(crate) fn new() -> Self {
Self {
lines: Vec::new(),
y: 0.0,
}
}
/// A page's name over its matches, while searching.
pub(crate) fn page(&mut self, page: P) {
if !self.lines.is_empty() {
self.y += style::PAGE_GAP;
}
self.lines.push(Line {
y: self.y,
page,
group: None,
setting: None,
});
self.y += style::PAGE_ROW;
}
/// A named group of rows.
pub(crate) fn group(&mut self, page: P, name: &'static str, rows: Vec<S>) {
self.lines.push(Line {
y: self.y,
page,
group: Some((name, rows.len() as f32 * style::ROW)),
setting: None,
});
self.y += style::GROUP_ROW;
for setting in rows {
self.lines.push(Line {
y: self.y,
page,
group: None,
setting: Some(setting),
});
self.y += style::ROW;
}
self.y += style::GROUP_GAP;
}
/// A group of rows under its page's own name (`list`'s `page_name`), for pages named at run
/// time, such as a shader pack's screens.
pub(crate) fn titled(&mut self, page: P, rows: Vec<S>) {
self.group(page, "", rows);
}
/// The lines and the content's height.
pub(crate) fn finish(self) -> (Vec<Line<P, S>>, f32) {
(self.lines, (self.y - style::GROUP_GAP).max(0.0))
}
}
/// The world or the menu's background, veiled.
pub(crate) fn backdrop(batch: &mut HudBatch, atlas: &HudAtlas, in_world: bool) {
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world);
style::fill(batch, atlas, [0.0, 0.0, w, h], style::VEIL);
}
/// The mark and the screen's name over the search field.
pub(crate) fn mark(batch: &mut HudBatch, atlas: &HudAtlas, cols: &Columns, title: &str) {
let (x, y) = (cols.side_x, cols.side_y);
style::fill(batch, atlas, [x, y + 2.0, 6.0, 6.0], style::ACCENT);
let horizon = Text::literal("Horizon");
batch.text_styled(atlas, &horizon, x + 10.0, y, style::WHITE, true);
let title = Text::literal(title);
batch.text_styled(atlas, &title, x, y + 10.0, style::MUTED, true);
}
/// A page in the page list: the open page on a plate with the accent's bar beside it, the
/// others bare text. `has`: something to show under it.
pub(crate) fn page_tab(
batch: &mut HudBatch,
atlas: &HudAtlas,
rect: [f32; 4],
name: &str,
(has, open, focused): (bool, bool, bool),
cursor: (f32, f32),
) {
let [px, py, pw, ph] = rect;
crate::widgets::record(name, rect, has);
let hover = has && ui::hovered(cursor, px, py, pw, ph);
crate::widgets::narratable(|| {
crate::widgets::Narratable::button(name.to_owned(), rect, has)
.hovered(hover)
.focused(focused)
});
crate::widgets::widget_cursor(hover, has);
if has {
crate::widgets::target_as(rect, crate::widgets::Kind::Tab(open));
}
if open {
style::fill(batch, atlas, rect, style::OPEN);
style::fill(batch, atlas, [px, py, 2.0, ph], style::ACCENT);
}
let color = match (open || hover, has) {
(true, _) => style::WHITE,
(false, true) => style::SOFT,
(false, false) => style::MUTED,
};
let ty = py + ((ph - 8.0) / 2.0).floor();
let name = Text::literal(style::fit(atlas, name, pw - 12.0));
batch.text_styled(atlas, &name, px + 8.0, ty, color, true);
if focused {
style::ring(batch, atlas, rect, style::WHITE);
}
}
/// The search field, with its hint or clear button.
pub(crate) fn search_field(
search: &mut ui::EditBox,
batch: &mut HudBatch,
atlas: &HudAtlas,
cols: &Columns,
cursor: (f32, f32),
focused: bool,
) {
let rect = cols.search();
style::well(batch, atlas, rect);
search.focused = focused;
let [x, y, _, h] = rect;
let clear = cols.clear();
(search.x, search.y) = (x + 5.0, y + ((h - 8.0) / 2.0).floor());
search.width = clear[0] - search.x;
search.text_color = style::WHITE;
// The clear button isn't the field's: a click at the field's end must not press it.
let frame = [x, y, clear[0] - x, h];
search.frame = Some(frame);
search.draw(batch, atlas, None);
if search.value.is_empty() && !focused {
let hint = Text::literal(search.message.clone());
batch.text_styled(atlas, &hint, x + 5.0, search.y, style::MUTED, true);
}
if !search.value.is_empty() {
let hover = ui::hovered(cursor, clear[0], clear[1], clear[2], clear[3]);
crate::widgets::widget_cursor(hover, true);
let color = if hover { style::WHITE } else { style::MUTED };
let cy = y + ((h - 8.0) / 2.0).floor();
ui::centered_text(
batch,
atlas,
&Text::literal("×"),
clear[0],
cy,
clear[2],
color,
);
}
if focused {
style::ring(batch, atlas, frame, style::WHITE);
}
}
/// The plate, with the open page's name (or the search's) over its list.
pub(crate) fn plate(batch: &mut HudBatch, atlas: &HudAtlas, cols: &Columns, heading: &str) {
let [px, py, pw, _] = cols.plate;
style::panel(batch, atlas, cols.plate);
let heading = Text::literal(style::fit(atlas, heading, pw - 24.0));
batch.text_styled(atlas, &heading, px + 12.0, py + 10.0, style::WHITE, true);
style::fill(
batch,
atlas,
[px + 8.0, py + 24.0, pw - 16.0, 1.0],
style::HEAD_RULE,
);
}
/// The list, clipped to its view: each group's panel, then its names and rows on it. `row`
/// draws a setting at its `y`; `page_name` names a page, and a group without a name of its own
/// (`Lines::titled`), in the player's language.
pub(crate) fn list<P: Copy, S: Copy>(
batch: &mut HudBatch,
atlas: &HudAtlas,
cols: &Columns,
lines: &[Line<P, S>],
scroll: f32,
page_name: impl Fn(P) -> String,
mut row: impl FnMut(&mut HudBatch, S, f32),
) {
let start = batch.vertices.len();
let mark = crate::widgets::targets_mark();
let row_y = |line: &Line<P, S>| cols.top + line.y - scroll;
let shows = |y: f32, h: f32| y + h > cols.top && y < cols.bottom;
for line in lines {
let y = row_y(line);
if let Some((_, panel)) = line.group
&& shows(y + style::GROUP_ROW, panel)
{
let rect = [cols.list_x, y + style::GROUP_ROW, cols.list_w, panel];
style::group(batch, atlas, rect);
}
}
// A group's first row, which has no rule over it.
let mut first = false;
for line in lines {
let y = row_y(line);
let after_name = std::mem::replace(&mut first, line.group.is_some());
if !shows(y, line.h()) {
continue;
}
let Some(setting) = line.setting else {
let (name, color, dy) = match line.group {
Some(("", _)) => (page_name(line.page), style::MUTED, 3.0),
Some((name, _)) => (lang::get(name), style::MUTED, 3.0),
None => (page_name(line.page), style::ACCENT, 4.0),
};
let name = Text::literal(name);
batch.text_styled(atlas, &name, cols.list_x + 2.0, y + dy, color, true);
continue;
};
if !after_name {
let rule = [cols.list_x + 8.0, y, cols.list_w - 16.0, 1.0];
style::fill(batch, atlas, rule, style::ROW_RULE);
}
row(batch, setting, y);
}
if lines.is_empty() {
let none = Text::literal(lang::get("No settings match."));
batch.text_styled(
atlas,
&none,
cols.list_x + 2.0,
cols.top + 4.0,
style::MUTED,
true,
);
}
batch.clip_since(
start,
cols.list_x,
cols.top,
cols.list_x + cols.list_w,
cols.bottom,
);
crate::widgets::clip_targets(mark, cols.top, cols.bottom);
}
/// A control's label as its name and its value ("Render Distance" and "12 chunks").
pub(crate) fn name_and_value(label: &str) -> (String, Option<String>) {
// `options.generic_value` ("%s: %s") joins vanilla's; Horizon's use ": " too.
let format = lang::get("options.generic_value");
let sep = format
.split("%s")
.nth(1)
.filter(|sep| !sep.is_empty() && label.contains(*sep))
.unwrap_or(": ");
match label.split_once(sep) {
Some((name, value)) => (name.to_owned(), Some(value.to_owned())),
None => (label.to_owned(), None),
}
}
/// A slider's position one step on: a step of its own, or a pixel of its `width` wide track.
pub(crate) fn slider_step(pos: f32, steps: Option<u32>, width: f32, forward: bool) -> f32 {
if let Some(steps) = steps {
let steps = steps as f32;
let current = (pos * steps).round();
let next = if forward {
current + 1.0
} else {
current - 1.0
};
(next / steps).clamp(0.0, 1.0)
} else {
let delta = 1.0 / (width - 8.0).max(1.0);
if forward {
(pos + delta).min(1.0)
} else {
(pos - delta).max(0.0)
}
}
}
/// A setting's row as the screen reads it.
pub(crate) struct RowView<'a> {
/// The whole caption ("Render Distance: 12 chunks"), for the narrator.
pub(crate) label: &'a str,
pub(crate) name: &'a str,
pub(crate) value: Option<&'a str>,
pub(crate) switch: Option<bool>,
pub(crate) slider: Option<f32>,
/// Can be used now.
pub(crate) live: bool,
pub(crate) hover: bool,
pub(crate) focused: bool,
/// Its slider is being dragged.
pub(crate) held: bool,
}
/// A setting's row at `y`, its name on the left and its control on the right.
pub(crate) fn row(batch: &mut HudBatch, atlas: &HudAtlas, cols: &Columns, y: f32, view: &RowView) {
let &RowView {
label,
name,
value,
switch,
slider,
live,
hover,
focused,
held,
} = view;
let rect = cols.row(y);
let (tx, tw) = cols.track();
let right = tx + tw;
let control = [
tx,
y + (style::ROW - style::CONTROL_H) / 2.0,
tw,
style::CONTROL_H,
];
let active = live && (hover || focused || held);
if active {
let lit = [rect[0] + 2.0, y + 1.0, rect[2] - 4.0, style::ROW - 2.0];
style::fill(batch, atlas, lit, style::HOVER);
}
crate::widgets::widget_cursor(hover, live);
// The control socket's widget tree, the narrator and a controller's focus.
let kind = match slider {
Some(value) => crate::widgets::Kind::Slider {
value,
track: [tx + 5.0, tw - 10.0],
},
None => crate::widgets::Kind::Button,
};
crate::widgets::record_as(label, rect, live, kind);
crate::widgets::narratable(|| {
match (switch, slider) {
(Some(on), _) => crate::widgets::Narratable::checkbox(name.to_owned(), on, rect, live),
(_, Some(_)) => crate::widgets::Narratable::slider(label.to_owned(), rect, live),
_ => crate::widgets::Narratable::button(label.to_owned(), rect, live),
}
.hovered(hover)
.focused(focused)
});
if live {
crate::widgets::target_as(rect, kind);
}
let color = if live { style::WHITE } else { style::MUTED };
let soft = if live { style::SOFT } else { style::MUTED };
let ty = y + ((style::ROW - 8.0) / 2.0).floor();
let lit = live && (hover || held);
let left = rect[0] + style::INSET;
// An action (Calibrate...) is a button across the row, as vanilla's lists have them.
if switch.is_none() && slider.is_none() && value.is_none() {
let wide = [left, control[1], right - left, style::CONTROL_H];
style::button(batch, atlas, wide, &Text::literal(name), (lit, live, false));
} else {
let value = value.unwrap_or_default();
let vw = atlas.font.width(value);
// Where the control starts, and the value's text for a slider at rest.
let start = match (switch, slider) {
(Some(_), _) => right - style::CONTROL_H,
(None, Some(_)) if active => tx,
(None, Some(_)) => right - vw,
(None, None) => right - vw - 18.0,
};
match (switch, slider) {
(Some(on), _) => style::checkbox(batch, atlas, right, y, on, live),
// A slider shows its track, the value on it, while it is pointed at, focused or held.
(None, Some(position)) => {
let value = Text::literal(value);
if active {
style::slider(batch, atlas, control, &value, position, (lit, live));
} else {
batch.text_styled(atlas, &value, start, ty, soft, true);
}
}
(None, None) => {
let value = Text::literal(value);
style::cycler(
batch,
atlas,
[start, y + 3.0, vw + 18.0, 14.0],
&value,
(lit, live),
);
}
}
// The name, cut short before the control where a translation runs long.
let shown = Text::literal(style::fit(atlas, name, start - 6.0 - left));
batch.text_styled(atlas, &shown, left, ty, color, true);
}
if focused {
style::ring(
batch,
atlas,
[rect[0] + 1.0, y, rect[2] - 2.0, style::ROW],
style::WHITE,
);
}
}
/// Vanilla's scroller, inside the panel's right edge, sized as `ui::Scroll` drags it.
pub(crate) fn scroller(
batch: &mut HudBatch,
atlas: &HudAtlas,
cols: &Columns,
content: f32,
scroll: f32,
) {
if !cols.scrolls() {
return;
}
let Some((y, bar)) = ui::scrollbar_thumb(cols.top, cols.bottom, content, scroll) else {
return;
};
let x = cols.bar_x();
let height = cols.bottom - cols.top;
crate::widgets::scroll_area(
[
cols.list_x,
cols.top,
x + style::SCROLLER_W - cols.list_x,
height,
],
scroll,
content - height,
);
let track = [x, cols.top, style::SCROLLER_W, height];
style::scroller(batch, atlas, track, [x, y, style::SCROLLER_W, bar]);
}
/// The strip's text under its first line.
pub(crate) fn dock_note(
batch: &mut HudBatch,
atlas: &HudAtlas,
cols: &Columns,
text: String,
color: u32,
) {
let [x, y, w, _] = cols.dock;
let lines = atlas.font.split(&Text::literal(text), w - 24.0);
for (i, line) in lines.iter().take(2).enumerate() {
batch.text_styled(
atlas,
line,
x + 12.0,
y + 20.0 + i as f32 * 10.0,
color,
true,
);
}
}
/// Done or Undo at the foot of the page list.
pub(crate) fn foot_button(
batch: &mut HudBatch,
atlas: &HudAtlas,
rect: [f32; 4],
label: &Text,
cursor: (f32, f32),
(focused, primary): (bool, bool),
) {
let [x, y, w, h] = rect;
let hovered = ui::hovered(cursor, x, y, w, h);
let hover = hovered || focused;
crate::widgets::record(&label.plain(), rect, true);
crate::widgets::narratable(|| {
crate::widgets::Narratable::button(label.plain(), rect, true)
.hovered(hovered)
.focused(focused)
});
crate::widgets::widget_cursor(hovered, true);
crate::widgets::target(rect);
style::button(batch, atlas, rect, label, (hover, true, primary));
}
/// Of the rows (their target, `y` and whether they can take the focus), those the keys reach.
/// Tab reaches all. The arrows (`near`) only reach the rows in view and the next live one past
/// either edge, which scrolls in, over any greyed ones: a row farther out sits under the tabs or
/// the buttons and would take the step from them.
pub(crate) fn reach<T>(
rows: &[(T, f32, bool)],
cols: &Columns,
near: bool,
) -> std::ops::Range<usize> {
let in_view = |y: f32| y + style::ROW > cols.top && y < cols.bottom;
match rows.iter().position(|r| in_view(r.1)) {
Some(first) if near => {
let last = rows.iter().rposition(|r| in_view(r.1)).unwrap_or(first);
let lo = rows[..first].iter().rposition(|r| r.2).unwrap_or(first);
let hi = rows[last + 1..]
.iter()
.position(|r| r.2)
.map_or(last, |i| last + 1 + i);
lo..hi + 1
}
None if near => 0..0,
_ => 0..rows.len(),
}
}
/// Where Tab or Shift+Tab goes among `n` controls.
pub(crate) fn tab_step(n: usize, current: Option<usize>, shift: bool) -> usize {
match (current, shift) {
(Some(i), false) => (i + 1) % n,
(Some(i), true) => (i + n - 1) % n,
(None, false) => 0,
(None, true) => n - 1,
}
}
/// Where an arrow key goes among the controls. Nothing focused in view: going down, the first
/// setting from the view's top on (the next past its bottom where greyed rows fill it); going
/// up, the last one down to its bottom. `is_row`: a control that is a setting's row.
pub(crate) fn arrow_step<T: Copy>(
controls: &[(T, [f32; 4])],
current: Option<usize>,
key: winit::keyboard::KeyCode,
cols: &Columns,
is_row: impl Fn(T) -> bool,
) -> Option<usize> {
use crate::gamepad::Button as B;
use winit::keyboard::KeyCode as K;
let dir = match key {
K::ArrowUp => B::DPadUp,
K::ArrowDown => B::DPadDown,
K::ArrowLeft => B::DPadLeft,
_ => B::DPadRight,
};
match current {
Some(i) => {
let rects: Vec<[f32; 4]> = controls.iter().map(|f| f.1).collect();
crate::gamepad::focus_step_rect(controls[i].1, dir, &rects)
}
None => {
let mut rows = controls.iter().enumerate().filter(|(_, (t, _))| is_row(*t));
let pick = if key == K::ArrowUp {
rows.rfind(|(_, (_, [_, y, ..]))| *y + style::ROW <= cols.bottom)
} else {
rows.find(|(_, (_, [_, y, ..]))| *y >= cols.top)
};
pick.map(|(i, _)| i)
}
}
}
/// Scroll just enough to bring a row at `rect` into the list's view.
pub(crate) fn scroll_into_view(
scroll: &mut ui::Scroll,
[_, y, _, h]: [f32; 4],
cols: &Columns,
content: f32,
) {
if y < cols.top {
scroll.amount -= cols.top - y;
} else if y + h > cols.bottom {
scroll.amount += y + h - cols.bottom;
}
scroll.clamp(cols.top, cols.bottom, content);
}
@@ -191,49 +191,6 @@ impl ShaderOptions {
.map(|c| Text::legacy(&c.replace("\\n", "\n")))
}
/// `option_label` within `width` as `measure` sizes it: the name shortened (`Bloom Up...: 2`)
/// when the whole doesn't fit, and whether it was.
pub fn option_label_within(
&self,
name: &str,
width: f32,
measure: impl Fn(&Text) -> f32,
) -> (Text, bool) {
let full = self.option_label(name);
if measure(&full) <= width {
return (full, false);
}
// The pack's text, cut a character at a time with the `§` codes it holds kept.
let key = format!("option.{name}");
let caption = self.lang.get(&key).unwrap_or(name);
let value = self.value_text(name);
let mut chars: Vec<char> = caption.chars().collect();
loop {
while chars.len() >= 2 && chars[chars.len() - 2] == '§' {
chars.truncate(chars.len() - 2);
}
if chars.pop().is_none() {
return (full, true);
}
// Without the spaces and codes it ends with.
let mut end = chars.len();
loop {
if end >= 2 && chars[end - 2] == '§' {
end -= 2;
} else if end > 0 && chars[end - 1].is_whitespace() {
end -= 1;
} else {
break;
}
}
let cut: String = chars[..end].iter().collect();
let label = Text::option_name_value(Text::legacy(&format!("{cut}...")), value.clone());
if measure(&label) <= width {
return (label, true);
}
}
}
/// `Name: value`, in the pack's words, the value yellow when it is not the default.
pub fn option_label(&self, name: &str) -> Text {
Text::option_name_value(
@@ -242,8 +199,13 @@ impl ShaderOptions {
)
}
/// Option `name`'s caption in the pack's words.
pub fn option_name(&self, name: &str) -> Text {
self.named(&format!("option.{name}"), name)
}
/// The value of option `name` as the pack names it, yellow when it is not the default.
fn value_text(&self, name: &str) -> Text {
pub fn value_text(&self, name: &str) -> Text {
let Some(option) = self.options.get(name) else {
return Text::literal(String::new());
};
@@ -350,7 +312,7 @@ mod tests {
}
#[test]
fn single_resets_comments_and_fitted_labels() {
fn single_resets_and_comments() {
let mut o = options();
o.lang = Lang::parse(
"option.LEVEL=Level of detail\noption.LEVEL.comment=How much detail.\\nMore costs more.\n",
@@ -364,18 +326,6 @@ mod tests {
Some("How much detail.\nMore costs more.")
);
assert!(o.comment("option.AO").is_none());
// One unit a character.
let measure = |t: &Text| t.plain().chars().count() as f32;
assert!(!o.option_label_within("LEVEL", 40.0, measure).1);
let (fitted, cut) = o.option_label_within("LEVEL", 12.0, measure);
assert!(cut);
assert_eq!(fitted.plain(), "Level...: 2");
o.lang = Lang::parse("option.LEVEL=§aLevel §lof detail§r\n");
let (fitted, _) = o.option_label_within("LEVEL", 12.0, measure);
assert_eq!(fitted.plain(), "Level...: 2");
assert_eq!(fitted.spans[0].style, Text::legacy("§aL").spans[0].style);
let (fitted, _) = o.option_label_within("LEVEL", 14.0, measure);
assert_eq!(fitted.plain(), "Level of...: 2");
}
#[test]
File diff suppressed because it is too large. Load diff
+171 -15
View File
@@ -237,6 +237,7 @@ pub struct Resolver {
done: std::sync::mpsc::Receiver<(NameOrId, Option<ResolvedProfile>)>,
send: std::sync::mpsc::Sender<(NameOrId, Option<ResolvedProfile>)>,
last_sweep: std::time::Instant,
heads: HeadProfiles,
}
struct Entry {
touched: std::time::Instant,
@@ -304,6 +305,7 @@ impl Resolver {
done,
send,
last_sweep: std::time::Instant::now(),
heads: HeadProfiles::default(),
}
}
/// `CacheBuilder.expireAfterAccess` with `maximumSize`.
@@ -465,6 +467,64 @@ pub fn dynamic_nbt(profile: &horizon_world::nbt::Tag) -> Option<NameOrId> {
}
}
const MAX_HEAD_PROFILES: usize = 4096;
#[derive(Debug, PartialEq)]
struct HeadProfile {
info: ProfileInfo,
skin: Option<(String, String)>,
}
fn prepare_head(profile: &serde_json::Value) -> HeadProfile {
let info = parse_profile(profile);
let skin = info.textures.as_ref().and_then(|(value, signature)| {
let url = unpack(value, *signature, &TEXTURE_URIS).skin?;
let location = skin_location(&texture_hash(&url)?);
Some((url, location))
});
HeadProfile { info, skin }
}
#[derive(Default)]
struct HeadProfiles {
entries: std::collections::HashMap<serde_json::Value, std::sync::Arc<HeadProfile>>,
nbt: std::collections::HashMap<horizon_world::nbt::Tag, std::sync::Arc<serde_json::Value>>,
resolved: [std::collections::HashMap<String, std::sync::Arc<HeadProfile>>; 2],
}
impl HeadProfiles {
fn get(&mut self, profile: &serde_json::Value) -> std::sync::Arc<HeadProfile> {
if let Some(parsed) = self.entries.get(profile) {
return parsed.clone();
}
if self.entries.len() >= MAX_HEAD_PROFILES {
self.entries.clear();
}
let parsed = std::sync::Arc::new(prepare_head(profile));
self.entries.insert(profile.clone(), parsed.clone());
parsed
}
}
impl Resolver {
/// Cache by NBT value rather than address: equipment can be replaced or
/// mutated in place, and neither must leave a stale profile behind.
pub fn head_profile_nbt(
&mut self,
profile: &horizon_world::nbt::Tag,
) -> std::sync::Arc<serde_json::Value> {
if let Some(json) = self.heads.nbt.get(profile) {
return json.clone();
}
if self.heads.nbt.len() >= MAX_HEAD_PROFILES {
self.heads.nbt.clear();
}
let json = std::sync::Arc::new(crate::scoreboard::tag_to_json(profile));
self.heads.nbt.insert(profile.clone(), json.clone());
json
}
}
/// `PlayerSkinRenderCache.getOrDefault` for a head: the resolved skin once
/// its texture is in the atlas (`atlas`), else `partialProfile`'s default.
pub fn head_skin(
@@ -478,32 +538,54 @@ pub fn head_skin(
{
return sprite;
}
let p = parse_profile(profile);
let property = p.textures.or_else(|| {
let key = p.dynamic.as_ref()?;
let p = resolver.heads.get(profile);
// Dynamic resolution is deliberately not cached: pending answers and the
// resolver's expiring service results must still advance on every draw.
let resolved = p.info.dynamic.as_ref().and_then(|key| {
if p.info.textures.is_some() {
return None;
}
match resolver.state(key) {
Resolve::Done(Some(profile)) => profile.textures(),
Resolve::Done(Some(profile)) => {
let (_, value, signature) = profile
.properties
.iter()
.find(|(n, _, _)| n == "textures")?;
let cache = &mut resolver.heads.resolved[usize::from(signature.is_some())];
if let Some(parsed) = cache.get(value) {
return Some(parsed.clone());
}
if cache.len() >= MAX_HEAD_PROFILES {
cache.clear();
}
let property = if signature.is_some() {
serde_json::json!({"name": "textures", "value": value, "signature": ""})
} else {
serde_json::json!({"name": "textures", "value": value})
};
let parsed = std::sync::Arc::new(prepare_head(
&serde_json::json!({"properties": [property]}),
));
cache.insert(value.clone(), parsed.clone());
Some(parsed)
}
_ => None,
}
});
if let Some((value, signature)) = property
&& let Some(url) = unpack(&value, signature, &TEXTURE_URIS).skin
&& let Some(hash) = texture_hash(&url)
{
let location = skin_location(&hash);
match downloads.state(Kind::Skin, &url) {
Download::Ready if atlas(&location) => {
downloads.drawn(&location);
return location;
if let Some((url, location)) = resolved.as_deref().unwrap_or(&p).skin.as_ref() {
match downloads.state(Kind::Skin, url) {
Download::Ready if atlas(location) => {
downloads.drawn(location);
return location.clone();
}
// Its slot was evicted: offer the image again.
Download::Ready => {
downloads.again(&location);
downloads.again(location);
}
_ => {}
}
}
crate::tab_list::default_skin(p.id).to_owned()
crate::tab_list::default_skin(p.info.id).to_owned()
}
/// `PlayerSkin.Patch.apply` for a head: the sprite of a profile's `texture`
@@ -1137,6 +1219,80 @@ pub fn sha1(data: &[u8]) -> [u8; 20] {
#[cfg(test)]
mod tests {
#[test]
fn head_profile_cache_matches_uncached_and_is_bounded() {
use base64::Engine;
let mut cache = super::HeadProfiles::default();
for (url, slim) in [
("https://textures.minecraft.net/texture/abc", false),
("https://textures.minecraft.net/texture/abc", true),
("https://evil.example/texture/abc", false),
] {
let payload = serde_json::json!({"textures": {
"SKIN": {"url": url, "metadata": {"model": if slim { "slim" } else { "classic" }}},
"CAPE": {"url": "http://textures.minecraft.net/texture/cape"}
}});
let value = base64::engine::general_purpose::STANDARD.encode(payload.to_string());
for signed in [false, true] {
let mut property = serde_json::json!({"name": "textures", "value": value});
if signed {
property["signature"] = serde_json::Value::Null;
}
let profile = serde_json::json!({"properties": [property]});
let parsed = cache.get(&profile);
assert_eq!(*parsed, super::prepare_head(&profile));
let textures = super::unpack(
&value,
if signed {
super::Signature::Signed
} else {
super::Signature::Unsigned
},
&super::TEXTURE_URIS,
);
assert_eq!(textures.slim, slim && !url.contains("evil"));
assert_eq!(textures.cape.is_some(), !url.contains("evil"));
assert_eq!(parsed.skin.is_some(), !url.contains("evil"));
assert!(std::sync::Arc::ptr_eq(&parsed, &cache.get(&profile)));
}
}
for profile in [
serde_json::json!({"properties": [{"name": "textures", "value": "!bad"}]}),
serde_json::json!({"name": "Notch"}),
serde_json::json!({}),
] {
let parsed = cache.get(&profile);
assert_eq!(*parsed, super::prepare_head(&profile));
assert!(parsed.skin.is_none());
assert!(std::sync::Arc::ptr_eq(&parsed, &cache.get(&profile)));
}
cache.entries.clear();
for i in 0..super::MAX_HEAD_PROFILES {
cache.get(&serde_json::json!({"id": i}));
}
assert_eq!(cache.entries.len(), super::MAX_HEAD_PROFILES);
cache.get(&serde_json::json!({}));
assert_eq!(cache.entries.len(), 1);
}
#[test]
fn head_profile_nbt_cache_tracks_value_changes() {
let mut resolver = super::Resolver::new();
let mut tag = horizon_world::nbt::Tag::String("Notch".into());
let first = resolver.head_profile_nbt(&tag);
assert_eq!(*first, crate::scoreboard::tag_to_json(&tag));
assert!(std::sync::Arc::ptr_eq(
&first,
&resolver.head_profile_nbt(&tag)
));
tag = horizon_world::nbt::Tag::String("Alex".into());
assert_eq!(*resolver.head_profile_nbt(&tag), serde_json::json!("Alex"));
for i in 0..super::MAX_HEAD_PROFILES {
resolver.head_profile_nbt(&horizon_world::nbt::Tag::Int(i as i32));
}
assert!(resolver.heads.nbt.len() < super::MAX_HEAD_PROFILES);
}
/// A profile's `texture` names a pack texture, never a file outside the
/// packs: bad characters and `..` segments draw nothing.
#[test]
+197 -15
View File
@@ -22,6 +22,11 @@ thread_local! {
static NOTES: RefCell<Vec<(f32, String)>> = const { RefCell::new(Vec::new()) };
}
/// The most spans a thread holds before they are taken ([`take_raw`]): a worker thread
/// that records spans (`lod_reduce`, `lt_*`) while they are on for every thread is never
/// taken from, so it drops what it held instead of growing for as long as they stay on.
const UNTAKEN_MAX: usize = 1 << 14;
/// The shortest step a [`note`] keeps, in milliseconds.
pub const NOTE_MS: f32 = 10.0;
/// The notes a thread keeps between two [`take_notes`]: its slowest steps.
@@ -53,7 +58,7 @@ pub fn record_here(on: bool) {
/// Whether this thread records spans: all of them on, or [`record_here`].
#[inline]
pub fn recording_here() -> bool {
ENABLED.load(Ordering::Relaxed) || HERE.with(Cell::get)
ENABLED.load(Ordering::Relaxed) || HERE.with(Cell::get) || trace::on()
}
/// The thread's CPU time when spans are on for every thread (`HORIZON_SPIKES`): only they
/// print it.
@@ -101,16 +106,41 @@ impl Drop for Guard {
.and_then(|start| Some((thread_cpu()?, start)))
.map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0);
DEPTH.with(|d| d.set(depth));
SPANS.with(|s| {
s.borrow_mut().push(Span {
name,
ms,
cpu_ms,
depth,
})
trace::span(name, started, ms);
push(Span {
name,
ms,
cpu_ms,
depth,
});
}
}
/// Keeps a finished span for the thread's next [`take_raw`].
fn push(span: Span) {
SPANS.with(|s| {
let mut s = s.borrow_mut();
if s.len() >= UNTAKEN_MAX {
s.clear();
}
s.push(span);
});
}
/// Attach per-tick counts without interpreting them as durations.
pub fn counters(counts: &[(&str, u64)]) {
if !enabled() {
return;
}
NOTES.with(|n| {
n.borrow_mut().push((
0.0,
counts
.iter()
.map(|(name, count)| format!("{name}={count}"))
.collect::<Vec<_>>()
.join(", "),
))
});
}
/// Notes that one step inside a span took `ms` milliseconds doing `what` (one player's
/// packets, say), when this thread records spans and the step took at least [`NOTE_MS`]: a
/// span says where a slow tick went, its notes whose doing it was. Only the slowest few are
@@ -163,13 +193,12 @@ impl Laps {
.zip(*cpu)
.map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0);
let depth = DEPTH.with(Cell::get);
SPANS.with(|s| {
s.borrow_mut().push(Span {
name,
ms,
cpu_ms,
depth,
})
trace::span(name, *started, ms);
push(Span {
name,
ms,
cpu_ms,
depth,
});
(*started, *cpu) = (now, now_cpu);
}
@@ -271,6 +300,159 @@ pub fn describe(spans: &[Span]) -> String {
list.join(", ")
}
/// The run's timeline: every span ([`time`], [`guard`], [`Laps::lap`]) on every thread, as
/// Chrome trace events that Perfetto (ui.perfetto.dev) opens as they are. `HORIZON_TRACE=FILE`
/// writes it from the start; [`start`](trace::start) and [`stop`](trace::stop) write one for a
/// while (`horizon-trace` on a dedicated server's console, `trace` on the control socket). Spans
/// show on their threads where they ran, nested by time, so what ran beside what, and what a
/// thread waited for, can be read off. Off, a span costs one relaxed load more.
pub mod trace {
use std::{
cell::Cell,
fs::File,
io::{BufWriter, Write as _},
path::Path,
sync::{
Mutex, PoisonError,
atomic::{AtomicBool, AtomicU32, Ordering},
},
time::Instant,
};
static ON: AtomicBool = AtomicBool::new(false);
static SINK: Mutex<Option<Sink>> = Mutex::new(None);
/// Counts the traces started: a thread names itself again in each one.
static TRACES: AtomicU32 = AtomicU32::new(0);
static NEXT_THREAD: AtomicU32 = AtomicU32::new(1);
thread_local! {
/// This thread's id in traces (0: none yet).
static THREAD: Cell<u32> = const { Cell::new(0) };
/// The trace this thread last named itself in.
static NAMED_IN: Cell<u32> = const { Cell::new(0) };
}
/// How often a trace's buffer goes to the file, at most: a run that ends without
/// [`stop`] loses no more than this.
const FLUSH_EVERY: std::time::Duration = std::time::Duration::from_secs(1);
struct Sink {
file: BufWriter<File>,
origin: Instant,
/// Until when it records ([`start`]'s `seconds`).
until: Option<Instant>,
flushed: Instant,
/// Events written: the next one is preceded by a comma.
events: u64,
}
impl Sink {
fn event(&mut self, event: std::fmt::Arguments) {
let comma = if self.events == 0 { "" } else { ",\n" };
let _ = write!(self.file, "{comma}{{\"pid\":1,{event}}}");
self.events += 1;
}
}
/// Whether a trace is being written.
#[inline]
pub fn on() -> bool {
ON.load(Ordering::Relaxed)
}
/// Starts a trace written to `path` (replacing a trace being written), for `seconds` or
/// until [`stop`].
pub fn start(path: &Path, seconds: Option<u32>) -> std::io::Result<()> {
let mut file = BufWriter::with_capacity(1 << 18, File::create(path)?);
file.write_all(b"[\n")?;
let now = Instant::now();
let sink = Sink {
file,
origin: now,
until: seconds.map(|s| now + std::time::Duration::from_secs(u64::from(s))),
flushed: now,
events: 0,
};
let mut slot = SINK.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(old) = slot.take() {
close(old);
}
*slot = Some(sink);
TRACES.fetch_add(1, Ordering::Relaxed);
ON.store(true, Ordering::Relaxed);
Ok(())
}
/// Starts the trace `HORIZON_TRACE` names, if it names one.
pub fn start_from_env() {
if let Some(path) = std::env::var_os("HORIZON_TRACE")
&& let Err(e) = start(Path::new(&path), None)
{
log::warn!("Horizon: HORIZON_TRACE: {e}");
}
}
/// Ends the trace being written: the file is complete JSON. The events written so far
/// and whether one was being written.
pub fn stop() -> Option<u64> {
ON.store(false, Ordering::Relaxed);
let sink = SINK.lock().unwrap_or_else(PoisonError::into_inner).take()?;
let events = sink.events;
close(sink);
Some(events)
}
/// Whether the trace being written has run its time ([`start`]'s `seconds`): the caller
/// then [`stop`]s it.
pub fn due() -> bool {
on() && SINK
.lock()
.unwrap_or_else(PoisonError::into_inner)
.as_ref()
.and_then(|s| s.until)
.is_some_and(|until| Instant::now() >= until)
}
fn close(mut sink: Sink) {
let _ = sink.file.write_all(b"\n]\n");
let _ = sink.file.flush();
}
/// A span of this thread from `started`, `ms` long.
pub(super) fn span(name: &'static str, started: Instant, ms: f32) {
if !on() {
return;
}
let tid = THREAD.with(|t| {
if t.get() == 0 {
t.set(NEXT_THREAD.fetch_add(1, Ordering::Relaxed));
}
t.get()
});
let trace = TRACES.load(Ordering::Relaxed);
let mut slot = SINK.lock().unwrap_or_else(PoisonError::into_inner);
let Some(sink) = slot.as_mut() else {
return;
};
if NAMED_IN.with(|n| n.replace(trace)) != trace {
let name = std::thread::current()
.name()
.unwrap_or("unnamed")
.replace(['"', '\\'], "_");
sink.event(format_args!(
r#""ph":"M","name":"thread_name","tid":{tid},"args":{{"name":"{name}"}}"#
));
}
let ts = started.saturating_duration_since(sink.origin).as_secs_f64() * 1e6;
sink.event(format_args!(
r#""ph":"X","name":"{name}","tid":{tid},"ts":{ts:.3},"dur":{:.3}"#,
f64::from(ms) * 1e3
));
let now = Instant::now();
if now.duration_since(sink.flushed) >= FLUSH_EVERY {
let _ = sink.file.flush();
sink.flushed = now;
}
}
}
/// The start's timeline: `HORIZON_STARTUP_TRACE=FILE` writes every named step of
/// the start (resource tables, the renderer, the title, a world's open, a
/// server's join, a dimension change) on whichever thread ran it, one Chrome
@@ -8,7 +8,7 @@ use crate::{
gamepad::{Button as PadButton, GlyphStyle},
graphics_style,
hud::{HudAtlas, HudBatch, rgba},
lang,
lang, pad_glyph,
text::Text,
ui,
};
@@ -411,30 +411,23 @@ impl SplitProfiles {
None => tr("horizon.splitscreen.profiles.move", "Move where you play"),
};
let keys = [PadButton::LeftBumper, PadButton::RightBumper];
let key_width = |b: PadButton| width(b.label(style)) + 4.0;
let key_width = |b: PadButton| pad_glyph::width(atlas, b, style);
let total = keys.iter().map(|&b| key_width(b) + 4.0).sum::<f32>() + 2.0 + width(&words);
let (mut x, y) = (((batch.width - total) / 2.0).floor(), 30.0);
for b in keys {
let [r, g, bl] = b.color(style);
let kw = key_width(b);
// A light edge around the dark key: it stands out on the menu's dark background.
batch.fill(
atlas,
x - 2.0,
y - 3.0,
kw + 2.0,
13.0,
rgba(170, 170, 170, 255),
);
batch.fill(atlas, x - 1.0, y - 2.0, kw, 11.0, rgba(40, 40, 40, 255));
batch.text(
atlas,
b.label(style),
x + 1.0,
y,
rgba(r, g, bl, 255),
false,
);
// A light edge around a dark key: it stands out on the menu's dark background.
if pad_glyph::art(atlas, b, style).is_none() {
batch.fill(
atlas,
x - 2.0,
y - 3.0,
kw + 2.0,
pad_glyph::HEIGHT + 2.0,
rgba(170, 170, 170, 255),
);
}
pad_glyph::draw(batch, atlas, b, style, x, y);
x += kw + 4.0;
}
batch.text(atlas, &words, x + 2.0, y, rgba(240, 240, 240, 255), true);
+120 -39
View File
@@ -263,6 +263,7 @@ struct MeshSettings {
nether: bool,
shader_pack_lighting: bool,
separate_ao: bool,
shader_pack: bool,
zoom: BiomeZoom,
blend_radius: i32,
smooth_lighting: bool,
@@ -517,6 +518,9 @@ pub struct Streaming {
/// OptiFine/Iris separate ambient occlusion: vertex RGB has pure tint and alpha holds AO factor
/// (`Mesher::separate_ao`).
pub separate_ao: bool,
/// A `shaders/` pack draws the terrain: fluid tops split as Iris splits them
/// (`Mesher::shader_pack`).
pub shader_pack: bool,
/// `BiomeManager`'s zoom seed (the hashed world seed) and `biomeBlendRadius`.
pub biome_zoom: BiomeZoom,
pub biome_blend: i32,
@@ -540,6 +544,12 @@ pub struct Streaming {
/// Chunks come from a server (`insert_remote`/`forget`): nothing is
/// generated and columns are only unloaded when the server says so.
pub remote: bool,
/// This server sends bulk block edits as whole columns whose light is
/// from before its relight (a Horizon server): a resent resident column
/// is lit here. Any other server's packet carries the light vanilla
/// applies, so it is not lit again (a proxy's next server resends its
/// whole world at the same coordinates).
pub relight_resent: bool,
/// More areas to keep loaded (centre chunk, radius), e.g. around the
/// players of a server. Each is a square, like vanilla's ticket levels:
/// chunks finish out to `radius + 1` (Chebyshev) and generation reaches
@@ -832,7 +842,14 @@ impl<G: ChunkGenerator> Source for Jobs<G> {
Job::Mesh(..) => 5,
_ => 6,
};
(kind, crate::spans::thread_cpu().unwrap_or_default())
// The other jobs (saves, light views, freed meshes) are many and short: counted, not
// timed, so the clock reads don't cost more than they do.
let cpu = if kind == 6 {
std::time::Duration::ZERO
} else {
crate::spans::thread_cpu().unwrap_or_default()
};
(kind, cpu)
});
let _tag = horizon_threads::heap_tag(match &job.job {
Job::Generate(..) => "stream.generate",
@@ -861,8 +878,13 @@ impl<G: ChunkGenerator> Source for Jobs<G> {
} else {
kind
};
let cpu = crate::spans::thread_cpu().unwrap_or_default();
job_stats::add(kind, cpu.saturating_sub(started).as_nanos() as u64);
let nanos = if kind == 6 {
0
} else {
let cpu = crate::spans::thread_cpu().unwrap_or_default();
cpu.saturating_sub(started).as_nanos() as u64
};
job_stats::add(kind, nanos);
}
if let Some(done) = done {
self.shared.done.send(done);
@@ -964,6 +986,7 @@ impl<G: ChunkGenerator> Jobs<G> {
nether_shading: settings.nether,
shader_pack_lighting: settings.shader_pack_lighting,
separate_ao: settings.separate_ao,
shader_pack: settings.shader_pack,
zoom: settings.zoom,
blend_radius: settings.blend_radius,
smooth_lighting: settings.smooth_lighting,
@@ -1077,6 +1100,7 @@ impl Streaming {
nether_shading: false,
shader_pack_lighting: false,
separate_ao: false,
shader_pack: false,
biome_zoom: BiomeZoom::new(0),
biome_blend: 2,
smooth_lighting: true,
@@ -1090,6 +1114,7 @@ impl Streaming {
generated_total: 0,
meshed_total: 0,
remote: false,
relight_resent: false,
extra: Vec::new(),
cover: None,
mesh: true,
@@ -1136,14 +1161,15 @@ impl Streaming {
}
/// A resident column a server sent again whole (it changed it in bulk):
/// its new blocks taken, the sections that did not change kept as they
/// were, and its light and its neighbours' worked out again here, off
/// the game thread, as light is for the blocks a server changes one at a
/// time; the sections that changed remesh (with theirs) once lit. Until
/// then the sections that changed show the light the packet carried (a
/// Horizon server sends the light from before its relight, then the
/// new light; another server's is already right, which matters where
/// the neighbours this light needs aren't all here).
pub fn replace_remote(&mut self, world: &mut World, mut chunk: Chunk) {
/// were, and (for a Horizon server's bulk edit) its light and its
/// neighbours' worked out again here, off the game thread, as light is for
/// the blocks a server changes one at a time; the sections that changed
/// remesh (with theirs) once lit. Until then the sections that changed
/// show the light the packet carried (a Horizon server sends the light
/// from before its relight, then the new light; another server's is already
/// right, which matters where the neighbours this light needs aren't all
/// here).
pub fn replace_remote(&mut self, world: &mut World, chunk: Chunk) {
let key = (chunk.x, chunk.z);
let Some(old) = world.chunks.get(&key).cloned() else {
return self.insert_remote(world, chunk);
@@ -1151,34 +1177,7 @@ impl Streaming {
if !self.lit.contains(&key) {
return self.insert_remote(world, chunk);
}
// The cells whose blocks changed, by section: they remesh with the neighbours within a block of them (as
// vanilla's `setBlocksDirty`), not every section round each section changed (which, for the few blocks a
// section often changes in a bulk edit, is mostly sections that did not).
let mut cells = crate::light::LightChanges::default();
cells.keyed(world.layout());
let kept = keep_unchanged_sections(&old, &mut chunk, &mut cells);
chunk.light_loaded = old.light_loaded;
chunk.lit = true;
world.chunks.insert(key, Arc::new(chunk));
world.revision = world.revision.wrapping_add(1);
// A section with new biomes and the same blocks remeshes now (its tint), with its neighbours, whose tint
// blends across the border: above and below too, as a block's tint can sample the biome quart of the
// section next to it (`BiomeManager.getBiome`'s zoom reaches a quart beyond the block).
Self::light_updated(world, key.0, key.1, &kept.biomes);
// A section with the same blocks and new light takes the packet's light (vanilla's
// `handleLevelChunkWithLight` always applies it) and remeshes as a light update would.
Self::light_updated(world, key.0, key.1, &kept.light);
if !kept.blocks {
return;
}
for dz in -1..=1 {
for dx in -1..=1 {
world.dirty_light.insert((key.0 + dx, key.1 + dz));
}
}
cells.dirty_sections(|section| {
world.dirty_sections.insert(section);
});
take_resent_column(world, key, &old, chunk, self.relight_resent);
}
/// A server's light update for a resident column: the sections whose
/// light changed and their neighbours remesh
@@ -2072,6 +2071,7 @@ impl Streaming {
nether: self.nether_shading,
shader_pack_lighting: self.shader_pack_lighting,
separate_ao: self.separate_ao,
shader_pack: self.shader_pack,
zoom: self.biome_zoom,
blend_radius: self.biome_blend,
smooth_lighting: self.smooth_lighting,
@@ -3027,6 +3027,51 @@ fn keep_unchanged_sections(
}
out
}
/// Takes the server's new `chunk` over the resident column `old`: the sections
/// whose blocks did not change keep `old`'s (with `chunk`'s biomes and light),
/// and the sections whose blocks changed remesh. `relight` says the packet's
/// light is from before the server's relight (a Horizon server's bulk edit), so
/// the column and its neighbours are lit here; another server's packet already
/// carries the light vanilla applies, so no light job is queued for it.
fn take_resent_column(
world: &mut World,
key: (i32, i32),
old: &Chunk,
mut chunk: Chunk,
relight: bool,
) {
// The cells whose blocks changed, by section: they remesh with the neighbours within a block of them (as
// vanilla's `setBlocksDirty`), not every section round each section changed (which, for the few blocks a
// section often changes in a bulk edit, is mostly sections that did not).
let mut cells = crate::light::LightChanges::default();
cells.keyed(world.layout());
let kept = keep_unchanged_sections(old, &mut chunk, &mut cells);
chunk.light_loaded = old.light_loaded;
chunk.lit = true;
world.chunks.insert(key, Arc::new(chunk));
world.revision = world.revision.wrapping_add(1);
// A section with new biomes and the same blocks remeshes now (its tint), with its neighbours, whose tint
// blends across the border: above and below too, as a block's tint can sample the biome quart of the
// section next to it (`BiomeManager.getBiome`'s zoom reaches a quart beyond the block).
Streaming::light_updated(world, key.0, key.1, &kept.biomes);
// A section with the same blocks and new light takes the packet's light (vanilla's
// `handleLevelChunkWithLight` always applies it) and remeshes as a light update would.
Streaming::light_updated(world, key.0, key.1, &kept.light);
if !kept.blocks {
return;
}
if relight {
for dz in -1..=1 {
for dx in -1..=1 {
world.dirty_light.insert((key.0 + dx, key.1 + dz));
}
}
}
cells.dirty_sections(|section| {
world.dirty_sections.insert(section);
});
}
/// Whether two sections' packed light (4,096 cells) holds the same values.
fn same_light(a: &crate::chunk::Light, b: &crate::chunk::Light) -> bool {
a.same_as(b)
@@ -4196,6 +4241,42 @@ mod tests {
);
}
}
fn resident_column(world: &mut World, light: u8) -> Chunk {
let mut chunk = Chunk::empty(2, -3);
chunk.set(1, 10, 1, 1);
Arc::make_mut(&mut chunk.sections[0]).light = crate::chunk::Light::Uniform(light);
chunk.lit = true;
world.chunks.insert((2, -3), Arc::new(chunk.clone()));
chunk
}
/// A server's resent column uses the light in its packet, as vanilla's
/// `handleLevelChunkWithLight` does: only a Horizon server's bulk edit,
/// whose packet light is from before its relight, is relit here. A proxy's
/// next server resends its whole world at the same coordinates, and
/// relighting every column and its neighbours is work that world never
/// asked for (#10273).
#[test]
fn a_resent_column_is_relit_only_for_a_horizon_servers_bulk_edit() {
for relight in [false, true] {
let mut world = World::new(horizon_world::registry::BlockStateId(0), 0);
let old = resident_column(&mut world, 0x50);
let mut new = old.clone();
new.set(1, 10, 1, 2);
Arc::make_mut(&mut new.sections[0]).light = crate::chunk::Light::Uniform(0xF0);
take_resent_column(&mut world, (2, -3), &old, new, relight);
let chunk = &world.chunks[&(2, -3)];
assert_eq!(chunk.block(1, 10, 1).0, 2);
// The packet's light is what the column shows.
assert_eq!(chunk.sections[0].light.get(0), 0xF0);
// The changed section remeshes either way.
assert!(world.dirty_sections.contains(&(2, 0, -3)));
// Only a Horizon bulk edit queues light work, for the column and
// its eight neighbours.
assert_eq!(world.dirty_light.len(), if relight { 9 } else { 0 });
}
}
}
#[cfg(test)]
+18 -7
View File
@@ -124,10 +124,18 @@ pub fn face(
}
}
/// `Hud.extractTabList`: whether the list shows. A single-player world
/// shows it only with another listed player or a `list` objective.
pub fn visible(key_down: bool, local_server: bool, listed: usize, objective: bool) -> bool {
key_down && !(local_server && listed <= 1 && !objective)
/// `Hud.extractTabList`: whether the list shows. `Hud.extractRenderState`
/// only calls it inside `if (!isHidden)`, so F1 takes the list away whatever
/// else holds it up. A single-player world shows it only with another listed
/// player or a `list` objective.
pub fn visible(
hud_shown: bool,
key_down: bool,
local_server: bool,
listed: usize,
objective: bool,
) -> bool {
hud_shown && key_down && !(local_server && listed <= 1 && !objective)
}
/// `Options.getBackgroundColor(553648127)`: the row background.
@@ -702,8 +710,11 @@ mod tests {
assert_eq!(ping_sprite(1000), "icon/ping_1");
// UUID.hashCode of 0 is 0: the first default skin.
assert_eq!(default_skin(0), "entity/player/slim/alex");
assert!(!visible(true, true, 1, false));
assert!(visible(true, true, 1, true));
assert!(visible(true, false, 1, false));
assert!(!visible(true, true, true, 1, false));
assert!(visible(true, true, true, 1, true));
assert!(visible(true, true, false, 1, false));
// F1 (`Hud.isHidden`) takes the list away however it was held up.
assert!(!visible(false, true, false, 2, false));
assert!(!visible(false, true, true, 1, true));
}
}
+14 -3
View File
@@ -417,6 +417,11 @@ fn arena_vertex(v: u32) -> ArenaCorner {
let c = arena_page[v * 3u + 2u];
return ArenaCorner(vec3(a.x, a.y, b.x), vec3(b.y, c.x, c.y));
}
// The offset a block corner adds on one component: `side` on the face's axis (rel 0), `du`
// on the next axis (rel 1), `dw` on the one after (rel 2).
fn corner_offset(rel: u32, side: u32, du: u32, dw: u32) -> u32 {
return select(select(dw, du, rel == 1u), side, rel == 0u);
}
// `packed::packed_vertex`: corner `corner` of the record whose words are lo (0 to 2) and
// hi (3 to 5).
fn packed_corner(lo: vec3<u32>, hi: vec3<u32>, corner: u32) -> ArenaCorner {
@@ -430,9 +435,15 @@ fn packed_corner(lo: vec3<u32>, hi: vec3<u32>, corner: u32) -> ArenaCorner {
let du = select(0u, 1u, step == 1u || step == 2u);
let dw = select(0u, 1u, step >= 2u);
// No dynamic component stores: FXC (DirectX 12) rejects them (X3500). A component's offset
// from the axis (0: the axis, 1: the next, 2: the one after) picks what it gets.
let rel = (vec3(0u, 1u, 2u) + vec3(3u - axis)) % vec3(3u);
let pos = block + select(select(vec3(dw), vec3(du), rel == vec3(1u)), vec3(side), rel == vec3(0u));
// from the axis (0: the axis, 1: the next, 2: the one after) picks what it gets. Scalar
// selects only: a vector select becomes GLSL's mix(uvec3, uvec3, bvec3), which old AMD
// OpenGL drivers (Radeon HD 7400M, driver 15.301) resolve to the float overload and reject.
let offset = vec3(
corner_offset((3u - axis) % 3u, side, du, dw),
corner_offset((4u - axis) % 3u, side, du, dw),
corner_offset((5u - axis) % 3u, side, du, dw),
);
let pos = block + offset;
let sel = lo.z >> 24u;
let us = (sel >> (2u * corner)) & 1u;
let vs = (sel >> (2u * corner + 1u)) & 1u;
+93 -5
View File
@@ -614,7 +614,12 @@ fn button_with_room(
room: f32,
narration: impl FnOnce([f32; 4]) -> crate::widgets::Narratable,
) {
crate::widgets::record(&label.plain(), [x, y, w, h], active);
let plain = label.plain();
crate::widgets::record(&plain, [x, y, w, h], active);
// An icon button has no label to record, and A presses it all the same.
if active && plain.trim().is_empty() {
crate::widgets::target([x, y, w, h]);
}
crate::widgets::narratable(|| narration([x, y, w, h]).hovered(hover));
crate::widgets::widget_cursor(hover, active);
let sprite = if !active {
@@ -1013,6 +1018,31 @@ pub fn tooltip_menu(
);
tooltip_box(batch, atlas, lines, x as f32, y as f32, w, h);
}
/// A widget's tooltip while the controller's focus is on it (Horizon's: vanilla has no gamepad
/// input, and the hidden pointer mid-widget would put it over the widget).
pub fn tooltip_under(batch: &mut HudBatch, atlas: &HudAtlas, lines: &[Text], rect: [f32; 4]) {
if lines.is_empty() {
return;
}
let (w, h) = tooltip_size(atlas, lines);
let (x, y) = tooltip_under_position((batch.width, batch.height), rect, (w, h));
tooltip_box(batch, atlas, lines, x, y, w, h);
}
/// Where `tooltip_under` puts lines of `size`: the frame's top left a pixel under the widget's
/// bottom left, over the widget when the screen ends first, and always on the screen.
fn tooltip_under_position(screen: (f32, f32), rect: [f32; 4], size: (f32, f32)) -> (f32, f32) {
// The frame reaches this far past the lines on every side.
const FRAME: f32 = 4.0;
let [x, y, _, height] = rect;
let right = screen.0 - size.0 - FRAME;
let below = y + height + 1.0 + FRAME;
let top = if below + size.1 + FRAME <= screen.1 {
below
} else {
y - 1.0 - FRAME - size.1
};
((x + FRAME).min(right).max(FRAME), top.max(FRAME))
}
/// `MenuTooltipPositioner.positionTooltip`: the tooltip's top left with the
/// pointer at `cursor`, the widget it belongs to at `rect`, and the screen.
/// `MARGIN` 5 and `MOUSE_OFFSET_X` 12 on the horizontal, and the
@@ -1123,6 +1153,9 @@ pub struct EditBox {
/// `getMessage`: what the narrator calls the box ("<message> edit box:
/// <value>").
pub message: String,
/// Where a borderless box drawn in a frame of its own focuses: a controller's outline goes
/// round the frame, not over the text.
pub frame: Option<[f32; 4]>,
}
/// The focused text field of a screen that keeps its values as `String`s
/// (the world list's search, world names, seeds, and the server screens): the `EditBox` state that
@@ -1385,6 +1418,7 @@ impl EditBox {
suggestion: None,
text_color: rgba(224, 224, 224, 255),
message: String::new(),
frame: None,
}
}
pub fn inner_width(&self) -> f32 {
@@ -1604,7 +1638,8 @@ impl EditBox {
pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, format: Option<&Text>) {
self.layout(atlas);
crate::widgets::target_as(
[self.x, self.y, self.width, self.height],
self.frame
.unwrap_or([self.x, self.y, self.width, self.height]),
crate::widgets::Kind::Field,
);
crate::widgets::narratable(|| {
@@ -1816,9 +1851,43 @@ mod tests {
assert_eq!(scrolled_left(10.0, 40.0, 1_000), 10.0 - offset);
}
/// The label of a widget it does not fit is clipped to the widget's box
/// instead of being drawn past it (the bug: `so_so`'s 590 px Create World
/// label ran over the button beside it).
/// A controller reaches an icon button only through its target, and can't press a disabled one.
#[test]
fn an_active_icon_button_is_a_focus_target_and_a_disabled_one_is_not() {
let atlas = atlas();
let mut batch = HudBatch::new([640, 480]);
// Whatever this thread drew before is the last frame's, then gone.
crate::widgets::end_frame(u64::MAX - 1);
button(
&mut batch,
&atlas,
10.0,
20.0,
20.0,
20.0,
&Text::empty(),
true,
false,
);
button(
&mut batch,
&atlas,
40.0,
20.0,
20.0,
20.0,
&Text::empty(),
false,
false,
);
crate::widgets::end_frame(u64::MAX);
let targets: Vec<[f32; 4]> = crate::widgets::last_targets()
.iter()
.map(|t| t.rect)
.collect();
assert_eq!(targets, [[10.0, 20.0, 20.0, 20.0]]);
}
#[test]
fn a_glyph_leaves_a_label_that_fits_centred() {
let atlas = atlas();
@@ -2297,6 +2366,25 @@ mod tests {
assert!(!delete_words(&mut v, 1));
assert_eq!(v, "stone");
}
#[test]
fn a_pad_focused_tooltip_hangs_from_its_widgets_bottom_left() {
let screen = (427.0, 240.0);
let widget = [100.0, 100.0, 150.0, 20.0];
// Frame at 100, 121: lines 4 further in.
assert_eq!(
tooltip_under_position(screen, widget, (80.0, 10.0)),
(104.0, 125.0)
);
// The screen's right edge moves it left, its bottom puts it over the widget.
assert_eq!(
tooltip_under_position(screen, [400.0, 100.0, 20.0, 20.0], (80.0, 10.0)),
(343.0, 125.0)
);
assert_eq!(
tooltip_under_position(screen, [100.0, 215.0, 150.0, 20.0], (80.0, 10.0)),
(104.0, 200.0)
);
}
/// `MenuTooltipPositioner.positionTooltip`: the pointer's 12 px offset,
/// the 5 px screen margin, and the 3 to 5 px the tooltip keeps from the
/// widget's top or bottom edge.
+80 -2
View File
@@ -201,9 +201,14 @@ pub fn set_action_glyphs(on: bool) {
ACTION_GLYPHS.set(on);
}
/// How much of a declared button's left the glyph takes from its label.
/// How much of a declared button's left the glyph takes from its label: a face button's, the only
/// kind declared buttons show, and no family's is wider than its art.
pub fn action_glyph_room() -> f32 {
if ACTION_GLYPHS.get() { 14.0 } else { 0.0 }
if ACTION_GLYPHS.get() {
crate::pad_glyph::FACE_WIDTH + 3.0
} else {
0.0
}
}
/// An interactive rectangle (GUI pixels) a controller can focus and click.
@@ -244,6 +249,41 @@ pub fn clip_targets(mark: usize, y0: f32, y1: f32) {
});
}
/// How many labelled widgets and targets the frame has so far, for [`clip_frame`].
pub fn frame_mark() -> (usize, usize) {
let labelled = WIDGETS.with_borrow(|(current, _, _)| current.len());
(labelled, targets_mark())
}
/// Drop the labelled widgets and targets since `mark` whose middle isn't in `y0..y1` (GUI pixels):
/// what a scrolling body clipped away, where a press wouldn't land.
pub fn clip_frame((labelled, targets): (usize, usize), y0: f32, y1: f32) {
let shown = |y: f32, h: f32| (y0..y1).contains(&(y + h / 2.0));
WIDGETS.with_borrow_mut(|(current, _, _)| {
let mut at = 0;
current.retain(|w| {
at += 1;
at <= labelled || shown(w.y, w.h)
});
});
TARGETS.with_borrow_mut(|(current, _, _)| {
let mut at = 0;
current.retain(|t| {
at += 1;
at <= targets || shown(t.rect[1], t.rect[3])
});
});
}
/// A prompt comes up over what the frame drew so far: what it covers can't be reached, by the
/// pointer or a controller, so its widgets, targets, declared buttons and lists go.
pub fn cover_frame() {
WIDGETS.with_borrow_mut(|(current, _, _)| current.clear());
TARGETS.with_borrow_mut(|(current, _, _)| current.clear());
ACTIONS.with_borrow_mut(|(current, _)| current.clear());
SCROLL_AREAS.with_borrow_mut(|(current, _)| current.clear());
}
/// This frame drew a list with something to scroll, in `rect`, scrolled `amount`
/// of `max`: a focus step goes through its hidden rows before it leaves
/// (`gamepad::list_step`).
@@ -1349,4 +1389,42 @@ mod tests {
"the clipped row is gone, earlier ones stay"
);
}
#[test]
fn a_scrolled_body_loses_what_it_clips_and_nothing_before_it() {
let _ = take();
target([0.0, 0.0, 5.0, 5.0]);
record("warning", [0.0, 0.0, 5.0, 5.0], true);
let mark = frame_mark();
record("shown", [0.0, 10.0, 5.0, 10.0], true);
target([0.0, 10.0, 5.0, 10.0]);
// Half in view is still pressed at its middle, which a mouse could reach.
record("half", [0.0, 25.0, 5.0, 10.0], true);
target([0.0, 25.0, 5.0, 10.0]);
record("gone", [0.0, 40.0, 5.0, 10.0], true);
target([0.0, 40.0, 5.0, 10.0]);
clip_frame(mark, 8.0, 32.0);
end_frame(101);
let names: Vec<String> = last_labelled().into_iter().map(|w| w.label).collect();
assert_eq!(names, ["warning", "shown", "half"]);
assert_eq!(last_targets().len(), 3);
}
#[test]
fn a_prompt_covers_what_was_drawn_before_it() {
let _ = take();
record("under", [0.0, 0.0, 5.0, 5.0], true);
target([0.0, 10.0, 5.0, 5.0]);
declare_action(Action::Done, [0.0, 0.0, 5.0, 5.0], true);
scroll_area([0.0, 0.0, 5.0, 5.0], 0.0, 5.0);
cover_frame();
record("over", [0.0, 20.0, 5.0, 5.0], true);
set_action_screen(7);
end_frame(102);
let names: Vec<String> = last_labelled().into_iter().map(|w| w.label).collect();
assert_eq!(names, ["over"]);
assert!(last_targets().is_empty());
assert!(last_actions(7).is_empty());
assert!(last_scroll_areas().is_empty());
}
}
@@ -65,7 +65,11 @@ struct Taa {
jitter: vec4<f32>,
};
@group(0) @binding(2) var history: texture_2d<f32>;
@group(0) @binding(3) var depth: texture_depth_2d;
// The world's depth as an unfilterable float texture: naga's GLSL backend
// cannot emit `textureLoad` from a depth texture, and a depth view bound as
// `TextureSampleType::Float { filterable: false }` gives the same texel on
// every backend.
@group(0) @binding(3) var depth: texture_2d<f32>;
@group(0) @binding(4) var<uniform> taa: Taa;
// Catmull-Rom over the history in 5 bilinear taps: sharper than one under motion.
@@ -113,7 +117,7 @@ fn sample_history(uv: vec2<f32>) -> vec3<f32> {
let c = textureLoad(world, q, 0).rgb;
lo = min(lo, c);
hi = max(hi, c);
near = max(near, textureLoad(depth, q, 0));
near = max(near, textureLoad(depth, q, 0).r);
}
}
let ndc = vec2(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0);
+13 -1
View File
@@ -254,7 +254,11 @@ fn normalize_end(data: &mut [u8]) {
}
let disk = u16_at(data, end + 4);
let with_directory = u16_at(data, end + 6);
if disk == with_directory && u16_at(data, end + 8) == count && u16_at(data, end + 10) == count {
if disk == 0
&& with_directory == 0
&& u16_at(data, end + 8) == count
&& u16_at(data, end + 10) == count
{
return;
}
data[end + 4..end + 10].fill(0);
@@ -311,6 +315,14 @@ mod tests {
assert_eq!(zip.read("a/b.txt").unwrap(), b"hello hello hello hello");
}
#[test]
fn a_file_is_opened_with_equal_nonzero_disk_numbers() {
let mut bytes = archive();
let end = bytes.len() - END_HEADER;
bytes[end + 4..end + 8].fill(0xFF);
let zip = opened("end-disks", &bytes).unwrap();
assert_eq!(zip.read("a/b.txt").unwrap(), b"hello hello hello hello");
}
#[test]
fn a_file_that_is_no_archive_does_not_open() {
assert!(opened("empty", b"").is_err());
assert!(opened("garbage", b"PK not really").is_err());
+6 -4
View File
@@ -54,6 +54,8 @@ sha2 = "0.10.9"
sha1 = "0.10"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1.0.151", features = ["raw_value"] }
# server.toml's [combat], which the dedicated server reads itself.
toml = "1.1"
# hlsl-out: the gfx.rs tests translate every shader as wgpu's DirectX 12 backend does. A normal feature,
# not a dev-dependency's, so builds, tests and examples share one build of naga, wgpu and this crate.
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] }
@@ -83,6 +85,8 @@ fs4 = { version = "1.1.0", default-features = false, features = ["sync"] }
rustix = { version = "1", default-features = false, features = ["std", "time", "process", "fs"] }
[target.'cfg(windows)'.dependencies]
# Resolve virtualized folders to shell-compatible physical paths.
dunce = "1.0.5"
# Use the registered URI handler without routing links through Explorer/cmd.
open = { version = "5.4.5", features = ["shellexecute-on-windows"] }
# DirectX 12, where Vulkan has no adapter or device, or by choice (`graphicsApi`, graphics.rs).
@@ -102,10 +106,6 @@ objc2-foundation = { version = "0.3", default-features = false, features = ["std
# DirectX 12 driver (`graphicsApi`, graphics.rs).
wgpu = { version = "30.0.1", default-features = false, features = ["gles"] }
[target.'cfg(windows)'.build-dependencies]
# The icon resource in the .exe (build.rs).
winresource = "0.1"
[features]
default = ["audio", "controllers"]
# Sound output. Without it (and `controllers`) the program links neither libasound nor libudev on
@@ -148,6 +148,8 @@ path = "examples/native_gui_overlay_probe.rs"
[build-dependencies]
horizon-mod-api-gen = { path = "../horizon-mod-api-gen" }
# The build script runs on the host, but embeds resources based on the target OS.
winresource = "0.1"
[lints]
workspace = true
@@ -72,10 +72,7 @@
"horizon.mods.settings": "Instellings",
"horizon.mods.in_world": " (los die wêreld om te verander)",
"horizon.mods.open_folder": "Maak Mod-lêergids oop",
"horizon.shader_packs.empty": "Geen shader packs: plaas dit in die shaderpacks-lêergids",
"horizon.shader_options.open": "Shader-opsies...",
"horizon.shader_options.profile": "Profiel",
"horizon.shader_options.loading": "Lees tans die shader-pakket se opsies...",
"horizon.agent.copy_details": "Kopieer verbindingbesonderhede",
"horizon.multiplayer.join": "Sluit aan",
"horizon.multiplayer.cancel_reconnecting": "Kanselleer Herkoppel",
@@ -326,7 +323,6 @@
"horizon.osk.close": "Maak toe",
"horizon.extras.chat_animation.tooltip": "'n Nuwe kletslyn gly van links af terwyl dit vervaag, in plaas daarvan om heel te lyk.",
"horizon.extras.chat_indicator.tooltip": "Die gekleurde balk aan die linkerkant van 'n kletslyn.",
"horizon.extras.wheel_cycles_settings.tooltip": "Die rolwiel oor 'n knoppie in die instellings verander die waarde daarvan, soos in vanielje. Af, die wiel blaai net deur die lys.",
"horizon.extras.pack_browser.tooltip": "Select Resource Packs kry 'n Voeg by-knoppie wat Modrinth deursoek en 'n pakket in jou pakke-lêergids installeer. Af, die speletjie kontak nooit Modrinth nie.",
"horizon.extras.splitscreen.tooltip": "In 'n wêreld kan 'n ander beheerder as 'n nuwe speler aansluit: druk A wanneer dit vra, kies dan 'n profiel en waar om te speel.",
"horizon.splitscreen.setup.monitor_unknown": "'n monitor",
@@ -415,6 +411,7 @@
"Frame Generation": "Raam Generasie",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Toon 'n opgemaakte raam tussen elke twee regte: gladder, 'n bietjie meer vertraging.",
"Shadow Cache": "Skadu-kas",
"Shader Packs...": "Shader-pakke...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Hergebruik die pakskadukaart wanneer son, uitsig en wêreld ooreenstem. Af by verstek.",
"Find BlueMap": "Vind BlueMap",
"On servers, finds their BlueMap web map for far terrain. Next join.": "Op bedieners, vind hul BlueMap-webkaart vir ver terrein. Sluit volgende aan.",
@@ -471,9 +468,26 @@
"horizon.extras.cosmetics_mine.tooltip": "Versteek: elke Horizon-speler sien jou sonder jou skoonheidsmiddels, jy ingesluit. Dieselfde skakelaar as die lanseerder se klerekas.",
"horizon.extras.cosmetics_others": "Ander spelers se skoonheidsmiddels",
"horizon.extras.cosmetics_others.tooltip": "Wat ander Horizon-spelers dra: alles, net hul naamplaatjiestyle, of niks. Versteek, die speletjie vra nooit wat hulle dra nie.",
"horizon.extras.cosmetics_auras": "Ander se aura's en roetes",
"horizon.extras.cosmetics_auras.tooltip": "Auras en roetes wat ander spelers dra. Af by verstek.",
"horizon.extras.cosmetics_hide_fx": "Versteek ander spelers se spore en auras",
"horizon.extras.cosmetics_hide_fx.tooltip": "Ander spelers se spore en auras bly versteek; hul ander kosmetiese items wys steeds. By verstek af.",
"horizon.extras.cosmetics.shown": "Getoon",
"horizon.extras.cosmetics.hidden": "Versteek",
"horizon.extras.cosmetics.name_tags": "Slegs naamplaatjies"
"horizon.extras.cosmetics.name_tags": "Slegs naamplaatjies",
"Installed": "Geïnstalleer",
"Apply": "Pas toe",
"Reset all options": "Stel alle opsies terug",
"A Horizon shader pack.": "'n Horizon-skadupakket.",
"An OptiFine or Iris shader pack.": "'n OptiFine- of Iris-skadupakket.",
"In use: press to turn shaders off.": "In gebruik: druk om skadus af te skakel.",
"Press to use it.": "Druk om dit te gebruik.",
"Put shader pack .zip files or folders in it.": "Sit skadupakket-.zip-lêers of -vouers daarin.",
"Puts every option of this pack back to its default.": "Stel elke opsie van hierdie pakket terug na sy verstek.",
"Sets many options at once, as the pack groups them.": "Stel baie opsies op een slag, soos die pakket hulle groepeer.",
"No shader packs yet: open the pack folder and put some in it.": "Nog geen skadupakkette nie: maak die pakketvouer oop en sit 'n paar daarin.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Kies 'n skadupakket. As jy die een in gebruik kies, word skadus afgeskakel.",
"Changed options apply with Apply, or when you leave.": "Gewysigde opsies word toegepas met Pas toe, of wanneer jy verlaat.",
"Pack settings": "Pakketopsies",
"Built-in settings": "Ingeboude opsies",
"%s settings": "%s-opsies",
"Settings made by the pack's author: they change only this pack.": "Opsies deur die pakket se skepper: hulle verander net hierdie pakket."
}
@@ -77,10 +77,7 @@
"horizon.mods.settings": "الإعدادات",
"horizon.mods.in_world": " (اترك العالم ليتغير)",
"horizon.mods.open_folder": "افتح مجلد التعديل",
"horizon.shader_packs.empty": "لا توجد حزم تظليل: ضعها في مجلدshaderpacks",
"horizon.shader_options.open": "خيارات التظليل...",
"horizon.shader_options.profile": "الملف الشخصي",
"horizon.shader_options.loading": "قراءة خيارات حزمة التظليل...",
"horizon.agent.copy_details": "نسخ تفاصيل الاتصال",
"horizon.multiplayer.join": "انضم",
"horizon.multiplayer.cancel_reconnecting": "إلغاء إعادة الاتصال",
@@ -341,7 +338,6 @@
"horizon.osk.close": "إغلاق",
"horizon.extras.chat_animation.tooltip": "ينزلق خط الدردشة الجديد من اليسار بينما يتلاشى للداخل، بدلاً من أن يظهر كاملاً.",
"horizon.extras.chat_indicator.tooltip": "الشريط الملون الموجود على يسار خط الدردشة.",
"horizon.extras.wheel_cycles_settings.tooltip": "عجلة التمرير فوق زر في الإعدادات تغير قيمته، كما هو الحال في الفانيليا. مع إيقاف التشغيل، تقوم العجلة بتمرير القائمة فقط.",
"horizon.extras.pack_browser.tooltip": "تحديد حزم الموارد يحصل على زر \"إضافة\" الذي يبحث في Modrinth ويقوم بتثبيت حزمة في مجلد الحزم الخاص بك. مع إيقاف التشغيل، لن تتصل اللعبة أبدًا بـ Modrinth.",
"horizon.extras.splitscreen.tooltip": "في عالم ما، يمكن لوحدة تحكم أخرى الانضمام كلاعب جديد: اضغط على A عندما يُطلب منك ذلك، ثم اختر ملفًا شخصيًا ومكان اللعب.",
"horizon.splitscreen.setup.monitor": "مراقب %s",
@@ -432,6 +428,7 @@
"Frame Generation": "جيل الإطار",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "يُظهر إطارًا مكوّنًا بين كل إطارين حقيقيين: أكثر سلاسة وتأخرًا قليلًا.",
"Shadow Cache": "ذاكرة التخزين المؤقت الظل",
"Shader Packs...": "حزم التظليل...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "يعيد استخدام خريطة ظل الحزمة عندما تتطابق الشمس والعرض والعالم. إيقاف بشكل افتراضي.",
"Find BlueMap": "ابحث عن بلو ماب",
"On servers, finds their BlueMap web map for far terrain. Next join.": "على الخوادم، يتم العثور على خريطة الويب BlueMap الخاصة بهم للتضاريس البعيدة. الانضمام التالي.",
@@ -490,9 +487,26 @@
"horizon.extras.cosmetics_mine.tooltip": "مخفي: يراك كل لاعب في Horizon بدون مستحضرات التجميل الخاصة بك، بما في ذلك أنت. نفس مفتاح خزانة المشغل.",
"horizon.extras.cosmetics_others": "مستحضرات التجميل للاعبين الآخرين",
"horizon.extras.cosmetics_others.tooltip": "ما يرتديه لاعبو Horizon الآخرون: كل شيء، فقط أنماط بطاقة الاسم الخاصة بهم، أو لا شيء. مخفيًا، اللعبة لا تسأل أبدًا عما يرتدونه.",
"horizon.extras.cosmetics_auras": "هالات ومسارات الآخرين",
"horizon.extras.cosmetics_auras.tooltip": "الهالات والمسارات التي يرتديها اللاعبون الآخرون. إيقاف بشكل افتراضي.",
"horizon.extras.cosmetics_hide_fx": "إخفاء آثار وهالات اللاعبين الآخرين",
"horizon.extras.cosmetics_hide_fx.tooltip": "تبقى آثار وهالات اللاعبين الآخرين مخفية؛ وتظل مستحضراتهم الأخرى ظاهرة. معطّل افتراضيًا.",
"horizon.extras.cosmetics.shown": "معروض",
"horizon.extras.cosmetics.hidden": "مخفي",
"horizon.extras.cosmetics.name_tags": "علامات الاسم فقط"
"horizon.extras.cosmetics.name_tags": "علامات الاسم فقط",
"Installed": "المثبّتة",
"Apply": "تطبيق",
"Reset all options": "إعادة ضبط كل الخيارات",
"A Horizon shader pack.": "حزمة شيدر من Horizon.",
"An OptiFine or Iris shader pack.": "حزمة شيدر من OptiFine أو Iris.",
"In use: press to turn shaders off.": "قيد الاستخدام: اضغط لإيقاف الشيدرات.",
"Press to use it.": "اضغط لاستخدامها.",
"Put shader pack .zip files or folders in it.": "ضع ملفات .zip أو مجلدات حزم الشيدر فيه.",
"Puts every option of this pack back to its default.": "يعيد كل خيار في هذه الحزمة إلى قيمته الافتراضية.",
"Sets many options at once, as the pack groups them.": "يضبط عدة خيارات دفعة واحدة، كما تجمعها الحزمة.",
"No shader packs yet: open the pack folder and put some in it.": "لا توجد حزم شيدر بعد: افتح مجلد الحزم وضع بعضها فيه.",
"Pick a shader pack. Picking the one in use turns shaders off.": "اختر حزمة شيدر. اختيار الحزمة قيد الاستخدام يوقف الشيدرات.",
"Changed options apply with Apply, or when you leave.": "تُطبَّق الخيارات المعدّلة بزر تطبيق، أو عند المغادرة.",
"Pack settings": "إعدادات الحزمة",
"Built-in settings": "الإعدادات المدمجة",
"%s settings": "إعدادات %s",
"Settings made by the pack's author: they change only this pack.": "إعدادات وضعها مؤلف الحزمة: تؤثر على هذه الحزمة فقط."
}
@@ -71,10 +71,7 @@
"horizon.mods.settings": "Parametrlər",
"horizon.mods.in_world": " (Dəyişmək üçün dünyanı tərk et)",
"horizon.mods.open_folder": "Mod Qovluğunu açın",
"horizon.shader_packs.empty": "Şeyder paketləri yoxdur: onları shaderpacks qovluğuna qoyun",
"horizon.shader_options.open": "Shader Seçimləri...",
"horizon.shader_options.profile": "Profil",
"horizon.shader_options.loading": "Şeyder paketinin seçimləri oxunur...",
"horizon.agent.copy_details": "Bağlantı təfərrüatlarını kopyalayın",
"horizon.multiplayer.join": "Qoşulun",
"horizon.multiplayer.cancel_reconnecting": "Yenidən qoşulmanı ləğv edin",
@@ -317,7 +314,6 @@
"horizon.osk.close": "Bağlayın",
"horizon.extras.chat_animation.tooltip": "Yeni söhbət xətti bütöv görünmək əvəzinə soldan içəri sürüşür.",
"horizon.extras.chat_indicator.tooltip": "Söhbət xəttinin solunda olan rəngli bar.",
"horizon.extras.wheel_cycles_settings.tooltip": "Parametrlərdəki düymənin üzərindəki sürüşdürmə çarxı vanildə olduğu kimi dəyərini dəyişir. Söndürülmüş, təkər yalnız siyahını sürüşdürür.",
"horizon.extras.pack_browser.tooltip": "Resurs Paketlərini seçin Modrinth-də axtarış aparan və paketlər qovluğuna paket quraşdıran Əlavə et düyməsini alır. Off, oyun Modrinthlə heç vaxt əlaqə saxlamır.",
"horizon.extras.splitscreen.tooltip": "Dünyada başqa bir nəzarətçi yeni oyunçu kimi qoşula bilər: soruşduqda A düyməsini basın, sonra profil və harada oynayacağınızı seçin.",
"horizon.splitscreen.setup.monitor_unknown": "monitor",
@@ -407,6 +403,7 @@
"Frame Generation": "Çərçivə Yaradılması",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Hər iki real arasında düzəldilmiş çərçivəni göstərir: daha hamar, bir az daha gecikmə.",
"Shadow Cache": "Kölgə önbelleği",
"Shader Packs...": "Shader Paketləri...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Günəş, görünüş və dünya uyğunlaşdıqda paket kölgə xəritəsindən təkrar istifadə edir. Defolt olaraq söndürülür.",
"Find BlueMap": "BlueMap tapın",
"On servers, finds their BlueMap web map for far terrain. Next join.": "Serverlərdə uzaq ərazilər üçün BlueMap veb xəritəsini tapır. Növbəti qoşulun.",
@@ -462,9 +459,26 @@
"horizon.extras.cosmetics_mine.tooltip": "Gizli: hər Horizon oyunçu sizi kosmetikanız olmadan görür. Başlatma şkafı ilə eyni açar.",
"horizon.extras.cosmetics_others": "Digər oyunçuların kosmetikası",
"horizon.extras.cosmetics_others.tooltip": "Digər Horizon oyunçular nə geyinirlər: hər şey, yalnız ad etiketi üslubları və ya heç nə. Gizli, oyun heç vaxt nə geyindiklərini soruşmur.",
"horizon.extras.cosmetics_auras": "Başqalarının auraları və izləri",
"horizon.extras.cosmetics_auras.tooltip": "Digər oyunçuların geydiyi auralar və izlər. Defolt olaraq söndürülür.",
"horizon.extras.cosmetics_hide_fx": "Digər oyunçuların izlərini və auralarını gizlət",
"horizon.extras.cosmetics_hide_fx.tooltip": "Digər oyunçuların izləri və auraları gizli qalır; digər kosmetikaları görünməyə davam edir. Defolt olaraq söndürülüb.",
"horizon.extras.cosmetics.shown": "Göstərildi",
"horizon.extras.cosmetics.hidden": "Gizli",
"horizon.extras.cosmetics.name_tags": "Yalnız ad etiketləri"
"horizon.extras.cosmetics.name_tags": "Yalnız ad etiketləri",
"Installed": "Quraşdırılmış",
"Apply": "Tətbiq et",
"Reset all options": "Bütün seçimləri sıfırla",
"A Horizon shader pack.": "Horizon şeyder paketi.",
"An OptiFine or Iris shader pack.": "OptiFine və ya Iris şeyder paketi.",
"In use: press to turn shaders off.": "İstifadədədir: şeyderləri söndürmək üçün basın.",
"Press to use it.": "İstifadə etmək üçün basın.",
"Put shader pack .zip files or folders in it.": "Şeyder paketlərinin .zip fayllarını və ya qovluqlarını bura qoyun.",
"Puts every option of this pack back to its default.": "Bu paketin bütün seçimlərini ilkin dəyərinə qaytarır.",
"Sets many options at once, as the pack groups them.": "Paketin qruplaşdırdığı kimi, bir çox seçimi birdən təyin edir.",
"No shader packs yet: open the pack folder and put some in it.": "Hələ şeyder paketi yoxdur: paket qovluğunu açıb bir neçəsini qoyun.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Şeyder paketi seçin. İstifadədə olanı seçmək şeyderləri söndürür.",
"Changed options apply with Apply, or when you leave.": "Dəyişdirilmiş seçimlər Tətbiq et ilə və ya çıxdıqda tətbiq olunur.",
"Pack settings": "Paket seçimləri",
"Built-in settings": "Daxili seçimlər",
"%s settings": "%s seçimləri",
"Settings made by the pack's author: they change only this pack.": "Paketin müəllifinin yaratdığı seçimlər: yalnız bu paketə təsir edir."
}
@@ -74,10 +74,7 @@
"horizon.mods.settings": "Көйләүҙәр",
"horizon.mods.in_world": " (донъяны үҙгәртергә ҡалдырырға)",
"horizon.mods.open_folder": "Мод папкаһын асыу",
"horizon.shader_packs.empty": "Шейдер пакеттары юҡ: уларҙы шейдерпакеттар папкаһына һалығыҙ",
"horizon.shader_options.open": "Шейдер варианттары...",
"horizon.shader_options.profile": "Профиль",
"horizon.shader_options.loading": "Шейдер пакетының варианттарын уҡыу...",
"horizon.agent.copy_details": "Тоташыу тураһында мәғлүмәтте күсерергә",
"horizon.multiplayer.join": "Ҡушылыу",
"horizon.multiplayer.cancel_reconnecting": "Яңынан тоташтырыуҙы юҡҡа сығарыу",
@@ -333,7 +330,6 @@
"horizon.osk.close": "Ябыҡ",
"horizon.extras.chat_animation.tooltip": "Яңы чат һыҙығы һулдан шыуып инә, ә ул һүнә, урынына бөтөн күренә.",
"horizon.extras.chat_indicator.tooltip": "Чат һыҙығының һул яғында төҫлө һыҙыҡ.",
"horizon.extras.wheel_cycles_settings.tooltip": "Көйләүҙәрҙәге төймә өҫтөндәге прокрутка тәгәрмәсе үҙенең ҡиммәтен үҙгәртә, ванильдәге кеүек. Һүндерелгән, тәгәрмәс исемлекте генә йөрөтә.",
"horizon.extras.pack_browser.tooltip": "Һайлау ресурс пакеттары ала өҫтәү төймәһе, эҙләү Modrinth һәм һеҙҙең пакеттар папкаһына пакет ҡуя. Һүндерелгән, уйын бер ҡасан да бәйләнешкә инә Modrinth.",
"horizon.extras.splitscreen.tooltip": "Донъяла, икенсе контроллер яңы уйынсы булараҡ ҡушыла ала: баҫығыҙ А, ҡасан ул һорай, һуңынан профиль һайлап һәм ҡайҙа уйнау.",
"horizon.splitscreen.setup.monitor": "Монитор %s",
@@ -427,6 +423,7 @@
"Frame Generation": "Кадр быуын",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Һәр ике ысын араһында ҡоролған кадр күрһәтә: шымараҡ, бер аҙ күберәк лаг.",
"Shadow Cache": "Күләгә кэш",
"Shader Packs...": "Шейдер пакеттары...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Ҡояш, ҡараш һәм донъя тап килгәндә пакет күләгә картаһын ҡабаттан ҡуллана. Һүндерелгән по умолчанию.",
"Find BlueMap": "Зәңгәр картаны табығыҙ",
"On servers, finds their BlueMap web map for far terrain. Next join.": "Серверҙарҙа, алыҫ ерҙәр өсөн уларҙы BlueMap веб-картаһын таба. Киләһе ҡушылыу.",
@@ -488,9 +485,26 @@
"horizon.extras.cosmetics_mine.tooltip": "Йәшерен: һәр Horizon уйынсы һеҙҙең косметикаһыҙ күрә, һеҙ ҙә индерелгән. Шул уҡ переключатель стартер&#8217;s Гардероб.",
"horizon.extras.cosmetics_others": "Башҡа уйынсыларҙың косметикаһы",
"horizon.extras.cosmetics_others.tooltip": "Башҡа ниндәй Horizon уйынсылар кейә: барыһы ла, тик уларҙы исем биркаһы стилдәре, йәки бер нәмә лә. Йәшерен, уйын бер ҡасан да һорамай, улар нимә кейә.",
"horizon.extras.cosmetics_auras": "Башҡаларҙың ауралары һәм эҙҙәре",
"horizon.extras.cosmetics_auras.tooltip": "Аура һәм эҙҙәр башҡа уйынсылар кейә. Һүндерелгән по умолчанию.",
"horizon.extras.cosmetics_hide_fx": "Башҡа уйынсыларҙың эҙҙәрен һәм ауралары йәшереү",
"horizon.extras.cosmetics_hide_fx.tooltip": "Башҡа уйынсыларҙың эҙҙәре һәм ауралары йәшерен ҡала; уларҙың башҡа косметикаһы күренә. Ғәҙәттә һүндерелгән.",
"horizon.extras.cosmetics.shown": "Күрһәтелгән",
"horizon.extras.cosmetics.hidden": "Йәшерен",
"horizon.extras.cosmetics.name_tags": "Исем билдәләре генә"
"horizon.extras.cosmetics.name_tags": "Исем билдәләре генә",
"Installed": "Урынлаштырылған",
"Apply": "Ҡулланырға",
"Reset all options": "Бөтә көйләүҙәрҙе ташларға",
"A Horizon shader pack.": "Horizon шейдер пакеты.",
"An OptiFine or Iris shader pack.": "OptiFine йәки Iris шейдер пакеты.",
"In use: press to turn shaders off.": "Ҡулланыла: шейдерҙарҙы һүндереү өсөн баҫығыҙ.",
"Press to use it.": "Ҡулланыу өсөн баҫығыҙ.",
"Put shader pack .zip files or folders in it.": "Шейдер пакеттарының .zip файлдарын йәки папкаларын шунда һалығыҙ.",
"Puts every option of this pack back to its default.": "Был пакеттың һәр көйләүен ғәҙәти хәленә ҡайтара.",
"Sets many options at once, as the pack groups them.": "Пакет төркөмләгәнсә, күп көйләүҙе бер юлы урынлаштыра.",
"No shader packs yet: open the pack folder and put some in it.": "Шейдер пакеттары әлегә юҡ: пакеттар папкаһын асып, берәй нисәһен һалығыҙ.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Шейдер пакетын һайлағыҙ. Ҡулланылғанын һайлау шейдерҙарҙы һүндерә.",
"Changed options apply with Apply, or when you leave.": "Үҙгәртелгән көйләүҙәр «Ҡулланырға» менән йәки сыҡҡанда ҡулланыла.",
"Pack settings": "Пакет көйләүҙәре",
"Built-in settings": "Эске көйләүҙәр",
"%s settings": "%s көйләүҙәре",
"Settings made by the pack's author: they change only this pack.": "Пакет авторы төҙөгән көйләүҙәр: улар тик был пакетты үҙгәртә."
}
@@ -72,10 +72,7 @@
"horizon.mods.settings": "Налады",
"horizon.mods.in_world": " (пакінуць свет змяніцца)",
"horizon.mods.open_folder": "Адкрыць тэчку Mod",
"horizon.shader_packs.empty": "Пакетаў шэйдэраў няма: змесціце іх у тэчку шэйдэраў",
"horizon.shader_options.open": "Параметры шэйдара...",
"horizon.shader_options.profile": "Профіль",
"horizon.shader_options.loading": "Чытанне параметраў пакета шэйдараў...",
"horizon.agent.copy_details": "Скапіруйце звесткі аб падключэнні",
"horizon.multiplayer.join": "Далучайцеся",
"horizon.multiplayer.cancel_reconnecting": "Адмяніць паўторнае падключэнне",
@@ -326,7 +323,6 @@
"horizon.osk.close": "Блізка",
"horizon.extras.chat_animation.tooltip": "Новы радок чата слізгае злева, пакуль ён знікае, замест таго, каб выглядаць цалкам.",
"horizon.extras.chat_indicator.tooltip": "Каляровая паласа злева ад радка чата.",
"horizon.extras.wheel_cycles_settings.tooltip": "Кола пракруткі над кнопкай у наладах змяняе яе значэнне, як у vanilla. Выключана, кола толькі пракручвае спіс.",
"horizon.extras.pack_browser.tooltip": "Select Resource Packs атрымлівае кнопку «Дадаць», якая выконвае пошук у Modrinth і ўсталёўвае пакет у вашу тэчку пакетаў. Выключана, гульня ніколі не звязваецца з Modrinth.",
"horizon.extras.splitscreen.tooltip": "У свеце іншы кантролер можа далучыцца як новы гулец: націсніце A, калі ён запытае, затым выберыце профіль і дзе гуляць.",
"horizon.splitscreen.setup.monitor": "Манітор %s",
@@ -417,6 +413,7 @@
"Frame Generation": "Генерацыя фрэймаў",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Паказвае прыдуманую рамку паміж двума сапраўднымі: больш гладкая, з крыху большым адставаннем.",
"Shadow Cache": "Ценявы кэш",
"Shader Packs...": "Пакеты шэйдэраў...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Паўторна выкарыстоўвае карту ценяў зграі, калі сонца, выгляд і свет супадаюць. Выключана па змаўчанні.",
"Find BlueMap": "Знайдзіце BlueMap",
"On servers, finds their BlueMap web map for far terrain. Next join.": "На серверах знаходзіць вэб-карту BlueMap для далёкай мясцовасці. Далей далучыцца.",
@@ -474,9 +471,26 @@
"horizon.extras.cosmetics_mine.tooltip": "Схаваны: кожны гулец Horizon бачыць вас без вашай касметыкі, у тым ліку і вас. The same switch as the launcher's Wardrobe.",
"horizon.extras.cosmetics_others": "Касметыка іншых гульцоў",
"horizon.extras.cosmetics_others.tooltip": "Што носяць іншыя гульцы Horizon: усё, толькі стылі тэгаў з імёнамі або нічога. Hidden, the game never asks what they wear.",
"horizon.extras.cosmetics_auras": "Чужыя аўры і шлейфы",
"horizon.extras.cosmetics_auras.tooltip": "Auras and trails other players wear. Выключана па змаўчанні.",
"horizon.extras.cosmetics_hide_fx": "Схаваць сляды і аўры іншых гульцоў",
"horizon.extras.cosmetics_hide_fx.tooltip": "Сляды і аўры іншых гульцоў схаваныя; іх астатняя касметыка бачная. Па змаўчанні выкл.",
"horizon.extras.cosmetics.shown": "Паказана",
"horizon.extras.cosmetics.hidden": "Схаваны",
"horizon.extras.cosmetics.name_tags": "Толькі біркі з імёнамі"
"horizon.extras.cosmetics.name_tags": "Толькі біркі з імёнамі",
"Installed": "Усталяваныя",
"Apply": "Ужыць",
"Reset all options": "Скінуць усе налады",
"A Horizon shader pack.": "Пакет шэйдараў Horizon.",
"An OptiFine or Iris shader pack.": "Пакет шэйдараў OptiFine або Iris.",
"In use: press to turn shaders off.": "Выкарыстоўваецца: націсніце, каб выключыць шэйдары.",
"Press to use it.": "Націсніце, каб выкарыстаць.",
"Put shader pack .zip files or folders in it.": "Пакладзіце ў яе .zip-файлы або папкі пакетаў шэйдараў.",
"Puts every option of this pack back to its default.": "Вяртае ўсе налады гэтага пакета да прадвызначаных.",
"Sets many options at once, as the pack groups them.": "Задае адразу многія налады так, як іх групуе пакет.",
"No shader packs yet: open the pack folder and put some in it.": "Пакетаў шэйдараў пакуль няма: адкрыйце папку пакетаў і пакладзіце туды некалькі.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Выберыце пакет шэйдараў. Выбар пакета, які выкарыстоўваецца, выключае шэйдары.",
"Changed options apply with Apply, or when you leave.": "Змененыя налады ўжываюцца кнопкай «Ужыць» або пры выхадзе.",
"Pack settings": "Налады пакета",
"Built-in settings": "Убудаваныя налады",
"%s settings": "Налады %s",
"Settings made by the pack's author: they change only this pack.": "Налады, зробленыя аўтарам пакета: яны змяняюць толькі гэты пакет."
}
@@ -70,10 +70,7 @@
"horizon.mods.settings": "Настройки",
"horizon.mods.in_world": " (оставете света да се промени)",
"horizon.mods.open_folder": "Отворете папката на Mod",
"horizon.shader_packs.empty": "Без шейдър пакети: поставете ги в папката shaderpacks",
"horizon.shader_options.open": "Опции за шейдър...",
"horizon.shader_options.profile": "Профил",
"horizon.shader_options.loading": "Четене на опциите на шейдър пакета...",
"horizon.agent.copy_details": "Копиране на подробности за връзката",
"horizon.multiplayer.join": "Присъединете се",
"horizon.multiplayer.cancel_reconnecting": "Отказ Повторно свързване",
@@ -324,7 +321,6 @@
"horizon.osk.close": "затвори",
"horizon.extras.chat_animation.tooltip": "Нова линия за чат се плъзга отляво, докато избледнява, вместо да се показва цяла.",
"horizon.extras.chat_indicator.tooltip": "Цветната лента отляво на линия за чат.",
"horizon.extras.wheel_cycles_settings.tooltip": "Колелцето за превъртане над бутон в настройките променя стойността му, както при vanilla. Изключено, колелото само превърта списъка.",
"horizon.extras.pack_browser.tooltip": "Select Resource Packs получава бутон за добавяне, който търси в Modrinth и инсталира пакет във вашата папка с пакети. Off, играта никога не се свързва с Modrinth.",
"horizon.extras.splitscreen.tooltip": "В един свят друг контролер може да се присъедини като нов играч: натиснете A, когато поиска, след това изберете профил и къде да играете.",
"horizon.splitscreen.setup.monitor": "Монитор %s",
@@ -470,9 +466,27 @@
"horizon.extras.cosmetics_mine.tooltip": "Скрит: всеки играч на Horizon ви вижда без вашата козметика, включително и вие. Същият превключвател като гардероба на стартера.",
"horizon.extras.cosmetics_others": "Козметика за други играчи",
"horizon.extras.cosmetics_others.tooltip": "Какво носят другите играчи на Horizon: всичко, само техните стилове на имената или нищо. Скрито, играта никога не пита какво носят.",
"horizon.extras.cosmetics_auras": "Аури и следи на други",
"horizon.extras.cosmetics_auras.tooltip": "Аури и пътеки, които другите играчи носят. Изключено по подразбиране.",
"horizon.extras.cosmetics_hide_fx": "Скриване на следите и аурите на другите играчи",
"horizon.extras.cosmetics_hide_fx.tooltip": "Следите и аурите на другите играчи остават скрити; другите им козметики се виждат. Изключено по подразбиране.",
"horizon.extras.cosmetics.shown": "Показано",
"horizon.extras.cosmetics.hidden": "Скрити",
"horizon.extras.cosmetics.name_tags": "Само етикети с имена"
"horizon.extras.cosmetics.name_tags": "Само етикети с имена",
"Shader Packs...": "Шейдър пакети...",
"Installed": "Инсталирани",
"Apply": "Приложи",
"Reset all options": "Нулирай всички опции",
"A Horizon shader pack.": "Пакет шейдъри на Horizon.",
"An OptiFine or Iris shader pack.": "Пакет шейдъри на OptiFine или Iris.",
"In use: press to turn shaders off.": "В употреба: натиснете, за да изключите шейдърите.",
"Press to use it.": "Натиснете, за да го използвате.",
"Put shader pack .zip files or folders in it.": "Сложете в нея .zip файлове или папки с пакети шейдъри.",
"Puts every option of this pack back to its default.": "Връща всяка опция на този пакет към стойността по подразбиране.",
"Sets many options at once, as the pack groups them.": "Задава много опции наведнъж, както ги групира пакетът.",
"No shader packs yet: open the pack folder and put some in it.": "Още няма пакети шейдъри: отворете папката с пакети и сложете няколко.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Изберете пакет шейдъри. Изборът на използвания го изключва.",
"Changed options apply with Apply, or when you leave.": "Променените опции се прилагат с Приложи или при излизане.",
"Pack settings": "Настройки на пакета",
"Built-in settings": "Вградени настройки",
"%s settings": "Настройки на %s",
"Settings made by the pack's author: they change only this pack.": "Настройки, направени от автора на пакета: променят само този пакет."
}
@@ -72,10 +72,7 @@
"horizon.mods.settings": "Arventennoù",
"horizon.mods.in_world": " (lezel ar bed da cheñch)",
"horizon.mods.open_folder": "Digeriñ an teuliad mod",
"horizon.shader_packs.empty": "Pakad skeudennoù ebet : lakait anezho e teuliad ar pakadoù skeudennoù",
"horizon.shader_options.open": "Dibarzhioù skeudenniñ...",
"horizon.shader_options.profile": "Profil",
"horizon.shader_options.loading": "O lenn dibaboù ar pakad skeudennoù...",
"horizon.agent.copy_details": "Eilañ munudoù ar c'hennask",
"horizon.multiplayer.join": "Kemer perzh",
"horizon.multiplayer.cancel_reconnecting": "Nullañ an adkennaskañ",
@@ -325,7 +322,6 @@
"horizon.osk.close": "Serriñ",
"horizon.extras.chat_animation.tooltip": "Ur linenn flapañ nevez a zeu eus an tu kleiz e-keit ma vez o vont da get, e-lec'h dont war wel a-bezh.",
"horizon.extras.chat_indicator.tooltip": "Ar varrenn livet a-gleiz d'ul linenn flapañ.",
"horizon.extras.wheel_cycles_settings.tooltip": "Ar rod riklañ war ur bouton en arventennoù a gemm e dalvoudegezh, evel e vanilha. Diweredekaet, ne ra ar rod nemet riklañ ar roll.",
"horizon.extras.pack_browser.tooltip": "Dibab pakadoù arc'hwelioù a resev ur bouton Ouzhpennañ a glask Modrinth hag a staliañ ur pakad en ho teuliad pakadoù. Diweredekaet, ne vez ket darempredet ar c'hoari gant Modrinth.",
"horizon.extras.splitscreen.tooltip": "En ur bed e c'hall ur c'hontroller all mont e-barzh evel c'hoarier nevez : pouezit war A pa c'houlenn, ha dibabit ur profil ha pelec'h c'hoari.",
"horizon.splitscreen.setup.monitor": "Heuliañ %s",
@@ -419,6 +415,7 @@
"Frame Generation": "Krouiñ frammoù",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Diskouez a ra ur framm savet etre pep daou hini gwirion : eeunoc'h, un tamm muioc'h a zilez.",
"Shadow Cache": "Grubuilh skeud",
"Shader Packs...": "Pakadoù skeudennoù...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Adimplij ar gartenn skeud pakad pa glot an heol, ar gwel hag ar bed. Diweredekaet dre ziouer.",
"Find BlueMap": "Kavout BlueMap",
"On servers, finds their BlueMap web map for far terrain. Next join.": "War ar servijerioù e kaver o gartenn web BlueMap evit an tachennoù pell. Kemer perzh da heul.",
@@ -473,9 +470,26 @@
"horizon.extras.cosmetics_mine.tooltip": "Kuzhet : pep c'hoarier Horizon a wel ac'hanoc'h hep ho kosmetikoù, c'hwi en o zouez. Ar memes treuzfurmadur hag armel al lañser.",
"horizon.extras.cosmetics_others": "Kosmetikoù ar c'hoarierien all",
"horizon.extras.cosmetics_others.tooltip": "Ar pezh a vez gwisket gant ar c'hoarierien Horizon all : pep tra, o doareoù tikedenn anv hepken, pe netra. Kuzhet, ar c'hoari ne c'houlenn ket biskoazh petra a wiskont.",
"horizon.extras.cosmetics_auras": "Auraoù ha roudoù tud all",
"horizon.extras.cosmetics_auras.tooltip": "Auraoù ha roudoù a vez gwisket gant c'hoarierien all. Diweredekaet dre ziouer.",
"horizon.extras.cosmetics_hide_fx": "Kuzhat roudoù hag aouraoù ar c'hoarierien all",
"horizon.extras.cosmetics_hide_fx.tooltip": "Kuzhet e chom roudoù hag aouraoù ar c'hoarierien all; diskouezet e vez o c'hinkladurioù all. Diweredekaet dre ziouer.",
"horizon.extras.cosmetics.shown": "Diskouezet",
"horizon.extras.cosmetics.hidden": "Kuzhet",
"horizon.extras.cosmetics.name_tags": "Tikedennoù anvioù hepken"
"horizon.extras.cosmetics.name_tags": "Tikedennoù anvioù hepken",
"Installed": "Staliet",
"Apply": "Arloañ",
"Reset all options": "Adderaouekaat an holl zibarzhioù",
"A Horizon shader pack.": "Ur pakad skeudennerioù Horizon.",
"An OptiFine or Iris shader pack.": "Ur pakad skeudennerioù OptiFine pe Iris.",
"In use: press to turn shaders off.": "Implijet: pouezit evit lazhañ ar skeudennerioù.",
"Press to use it.": "Pouezit evit e implijout.",
"Put shader pack .zip files or folders in it.": "Lakait e-barzh restroù .zip pe teuliadoù pakadoù skeudennerioù.",
"Puts every option of this pack back to its default.": "Adlakaat a ra pep dibarzh eus ar pakad-mañ d'e dalvoudegezh dre ziouer.",
"Sets many options at once, as the pack groups them.": "Lakaat a ra kalz dibarzhioù war un dro, evel ma vez strollet gant ar pakad.",
"No shader packs yet: open the pack folder and put some in it.": "Pakad skeudennerioù ebet c'hoazh: digorit teuliad ar pakadoù ha lakait un nebeut e-barzh.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Dibabit ur pakad skeudennerioù. Dibab an hini implijet a laz ar skeudennerioù.",
"Changed options apply with Apply, or when you leave.": "An dibarzhioù cheñchet a vez arloet gant Arloañ, pe pa guitait.",
"Pack settings": "Arventennoù ar pakad",
"Built-in settings": "Arventennoù enframmet",
"%s settings": "Arventennoù %s",
"Settings made by the pack's author: they change only this pack.": "Arventennoù graet gant oberer ar pakad: cheñch a reont nemet ar pakad-mañ."
}
@@ -58,10 +58,7 @@
"horizon.mods.settings": "Postavke",
"horizon.mods.in_world": " (ostavi svijet da se promijeni)",
"horizon.mods.open_folder": "Otvorite Mod folder",
"horizon.shader_packs.empty": "Nema paketa shadera: stavite ih u mapu shaderpacks",
"horizon.shader_options.open": "Opcije shadera...",
"horizon.shader_options.profile": "Profil",
"horizon.shader_options.loading": "Čitanje opcija paketa shadera...",
"horizon.agent.copy_details": "Kopiraj detalje veze",
"horizon.multiplayer.join": "Pridružite se",
"horizon.multiplayer.cancel_reconnecting": "Otkaži ponovno povezivanje",
@@ -281,7 +278,6 @@
"horizon.osk.close": "Zatvori",
"horizon.extras.chat_animation.tooltip": "Nova linija ćaskanja klizi s lijeve strane dok se gasi, umjesto da izgleda kao cijela.",
"horizon.extras.chat_indicator.tooltip": "Traka u boji lijevo od linije za ćaskanje.",
"horizon.extras.wheel_cycles_settings.tooltip": "Točkić za pomeranje preko dugmeta u podešavanjima menja svoju vrednost, kao u vaniliji. Isključeno, kotačić samo pomiče listu.",
"horizon.extras.pack_browser.tooltip": "Select Resource Packs dobija dugme Dodaj koje pretražuje Modrinth i instalira paket u fasciklu sa paketima. Isključeno, igra nikada ne kontaktira Modrinth.",
"horizon.extras.splitscreen.tooltip": "U svijetu se drugi kontrolor može pridružiti kao novi igrač: pritisnite A kada to zatraži, a zatim odaberite profil i gdje ćete igrati.",
"horizon.splitscreen.setup.monitor_unknown": "monitor",
@@ -415,9 +411,27 @@
"horizon.extras.cosmetics_mine.tooltip": "Skriveno: svaki Horizon igrač vas vidi bez vaše kozmetike, uključujući i vas. Isti prekidač kao Ormar lansera.",
"horizon.extras.cosmetics_others": "Kozmetika drugih igrača",
"horizon.extras.cosmetics_others.tooltip": "Šta drugi Horizon igrači nose: sve, samo stilove oznaka sa imenom ili ništa. Skriveno, igra nikad ne pita šta nose.",
"horizon.extras.cosmetics_auras": "Aure i tragovi drugih",
"horizon.extras.cosmetics_auras.tooltip": "Aure i staze koje drugi igrači nose. Podrazumevano isključeno.",
"horizon.extras.cosmetics_hide_fx": "Sakrij tragove i aure drugih igrača",
"horizon.extras.cosmetics_hide_fx.tooltip": "Tragovi i aure drugih igrača ostaju skriveni; njihova ostala kozmetika se i dalje vidi. Isključeno po zadanom.",
"horizon.extras.cosmetics.shown": "Prikazano",
"horizon.extras.cosmetics.hidden": "Skriveno",
"horizon.extras.cosmetics.name_tags": "Samo oznake sa imenom"
"horizon.extras.cosmetics.name_tags": "Samo oznake sa imenom",
"Shader Packs...": "Shader paketi...",
"Installed": "Instalirani",
"Apply": "Primijeni",
"Reset all options": "Resetuj sve opcije",
"A Horizon shader pack.": "Horizon paket šejdera.",
"An OptiFine or Iris shader pack.": "OptiFine ili Iris paket šejdera.",
"In use: press to turn shaders off.": "U upotrebi: pritisni da isključiš šejdere.",
"Press to use it.": "Pritisni da ga koristiš.",
"Put shader pack .zip files or folders in it.": "Stavi u njega .zip datoteke ili mape paketa šejdera.",
"Puts every option of this pack back to its default.": "Vraća svaku opciju ovog paketa na zadanu vrijednost.",
"Sets many options at once, as the pack groups them.": "Postavlja mnogo opcija odjednom, kako ih paket grupiše.",
"No shader packs yet: open the pack folder and put some in it.": "Još nema paketa šejdera: otvori mapu paketa i stavi nekoliko u nju.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Odaberi paket šejdera. Odabir paketa koji se koristi isključuje šejdere.",
"Changed options apply with Apply, or when you leave.": "Promijenjene opcije se primjenjuju pomoću Primijeni ili kada izađeš.",
"Pack settings": "Postavke paketa",
"Built-in settings": "Ugrađene postavke",
"%s settings": "Postavke za %s",
"Settings made by the pack's author: they change only this pack.": "Postavke koje je napravio autor paketa: mijenjaju samo ovaj paket."
}
@@ -69,10 +69,7 @@
"horizon.mods.settings": "Configuració",
"horizon.mods.in_world": " (deixar el món per canviar)",
"horizon.mods.open_folder": "Obriu la carpeta de modificacions",
"horizon.shader_packs.empty": "Sense paquets d'ombres: col·loqueu-los a la carpeta shaderpacks",
"horizon.shader_options.open": "Opcions d'ombrejat...",
"horizon.shader_options.profile": "Perfil",
"horizon.shader_options.loading": "Llegint les opcions del paquet shader...",
"horizon.agent.copy_details": "Copia els detalls de la connexió",
"horizon.multiplayer.join": "Uneix-te",
"horizon.multiplayer.cancel_reconnecting": "Cancel·la la tornada a connectar",
@@ -319,7 +316,6 @@
"horizon.osk.close": "Tancar",
"horizon.extras.chat_animation.tooltip": "Una nova línia de xat es desplaça des de l'esquerra mentre s'esvaeix, en lloc de semblar sencera.",
"horizon.extras.chat_indicator.tooltip": "La barra de colors a l'esquerra d'una línia de xat.",
"horizon.extras.wheel_cycles_settings.tooltip": "La roda de desplaçament sobre un botó a la configuració canvia el seu valor, com a la vainilla. Desactivada, la roda només desplaça la llista.",
"horizon.extras.pack_browser.tooltip": "Select Resource Packs obté un botó Afegeix que cerca Modrinth i instal·la un paquet a la carpeta de paquets. Desactivat, el joc mai contacta amb Modrinth.",
"horizon.extras.splitscreen.tooltip": "En un món, un altre controlador pot unir-se com a jugador nou: premeu A quan ho demani, després trieu un perfil i on jugar.",
"horizon.splitscreen.setup.monitor_unknown": "un monitor",
@@ -463,9 +459,27 @@
"horizon.extras.cosmetics_mine.tooltip": "Ocult: tots els jugadors d'Horizon et veuen sense els teus cosmètics, tu inclòs. El mateix interruptor que l'armari del llançador.",
"horizon.extras.cosmetics_others": "Cosmètica d'altres jugadors",
"horizon.extras.cosmetics_others.tooltip": "Què porten altres jugadors d'Horizon: tot, només els seus estils d'etiquetes de nom o res. Amagat, el joc mai pregunta què porten.",
"horizon.extras.cosmetics_auras": "Les aures i els camins dels altres",
"horizon.extras.cosmetics_auras.tooltip": "Aures i rastres que porten altres jugadors. Desactivat per defecte.",
"horizon.extras.cosmetics_hide_fx": "Amaga les esteles i les aures dels altres jugadors",
"horizon.extras.cosmetics_hide_fx.tooltip": "Les esteles i les aures dels altres jugadors queden amagades; els seus altres cosmètics es continuen veient. Desactivat per defecte.",
"horizon.extras.cosmetics.shown": "Es mostra",
"horizon.extras.cosmetics.hidden": "Ocult",
"horizon.extras.cosmetics.name_tags": "Només etiquetes de nom"
"horizon.extras.cosmetics.name_tags": "Només etiquetes de nom",
"Shader Packs...": "Paquets d'ombres...",
"Installed": "Instal·lats",
"Apply": "Aplica",
"Reset all options": "Restableix totes les opcions",
"A Horizon shader pack.": "Un paquet de shaders d'Horizon.",
"An OptiFine or Iris shader pack.": "Un paquet de shaders d'OptiFine o Iris.",
"In use: press to turn shaders off.": "En ús: prem per desactivar els shaders.",
"Press to use it.": "Prem per fer-lo servir.",
"Put shader pack .zip files or folders in it.": "Hi pots posar fitxers .zip o carpetes de paquets de shaders.",
"Puts every option of this pack back to its default.": "Torna totes les opcions d'aquest paquet al valor per defecte.",
"Sets many options at once, as the pack groups them.": "Defineix moltes opcions alhora, tal com les agrupa el paquet.",
"No shader packs yet: open the pack folder and put some in it.": "Encara no hi ha cap paquet de shaders: obre la carpeta de paquets i hi poses algun.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Tria un paquet de shaders. Triar el que està en ús desactiva els shaders.",
"Changed options apply with Apply, or when you leave.": "Les opcions canviades s'apliquen amb Aplica, o quan surts.",
"Pack settings": "Configuració del paquet",
"Built-in settings": "Configuració integrada",
"%s settings": "Configuració de %s",
"Settings made by the pack's author: they change only this pack.": "Configuració feta per l'autor del paquet: només canvia aquest paquet."
}
@@ -67,11 +67,7 @@
"horizon.mods.settings": "Nastavení",
"horizon.mods.in_world": " (nechat svět změnit)",
"horizon.mods.open_folder": "Otevřete složku Mod",
"horizon.shader_packs.empty": "Žádné balíčky shaderů: vložte je do složky shaderpacks",
"horizon.shader_packs.kind_horizon": " (Horizont)",
"horizon.shader_options.open": "Možnosti stínování...",
"horizon.shader_options.profile": "Profil",
"horizon.shader_options.loading": "Čtení možností sady shaderů...",
"horizon.agent.copy_details": "Kopírovat podrobnosti o připojení",
"horizon.multiplayer.join": "Připojte se",
"horizon.multiplayer.cancel_reconnecting": "Zrušit opětovné připojení",
@@ -311,7 +307,6 @@
"horizon.osk.close": "Zavřít",
"horizon.extras.chat_animation.tooltip": "Nová čára chatu se vsune zleva, zatímco se mizí, místo aby vypadala celá.",
"horizon.extras.chat_indicator.tooltip": "Barevný pruh nalevo od chatovací linky.",
"horizon.extras.wheel_cycles_settings.tooltip": "Rolovací kolečko nad tlačítkem v nastavení mění jeho hodnotu, jako u vanilky. Vypnuto, kolečko pouze posouvá seznam.",
"horizon.extras.pack_browser.tooltip": "Select Resource Packs dostane tlačítko Přidat, které prohledá Modrinth a nainstaluje balíček do vaší složky balíčků. Vypnuto, hra nikdy nekontaktuje Modrinth.",
"horizon.extras.splitscreen.tooltip": "Ve světě se může jako nový hráč připojit další ovladač: stiskněte A, když se zeptá, pak vyberte profil a kde hrát.",
"horizon.splitscreen.setup.monitor_unknown": "monitor",
@@ -398,6 +393,7 @@
"Frame Generation": "Generování snímků",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Zobrazuje vytvořený rám mezi každým dvěma skutečnými: hladší, trochu více zpoždění.",
"Shadow Cache": "Stínová mezipaměť",
"Shader Packs...": "Shader Pack...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Znovu použije mapu stínu balíčku, když se slunce, pohled a svět shodují. Ve výchozím nastavení vypnuto.",
"Find BlueMap": "Najděte BlueMap",
"On servers, finds their BlueMap web map for far terrain. Next join.": "Na serverech najde jejich webovou mapu BlueMap pro vzdálený terén. Další připojení.",
@@ -452,9 +448,26 @@
"horizon.extras.cosmetics_mine.tooltip": "Skryté: každý hráč Horizon vás vidí bez vaší kosmetiky, včetně vás. Stejný vypínač jako skříň odpalovacího zařízení.",
"horizon.extras.cosmetics_others": "Kosmetika ostatních hráčů",
"horizon.extras.cosmetics_others.tooltip": "Co nosí ostatní hráči Horizon: všechno, jen styly jmenovek nebo nic. Skryto, hra se nikdy neptá, co nosí.",
"horizon.extras.cosmetics_auras": "Aury a stezky ostatních",
"horizon.extras.cosmetics_auras.tooltip": "Aury a stezky, které nosí ostatní hráči. Ve výchozím nastavení vypnuto.",
"horizon.extras.cosmetics_hide_fx": "Skrýt stopy a aury ostatních hráčů",
"horizon.extras.cosmetics_hide_fx.tooltip": "Stopy a aury ostatních hráčů zůstanou skryté; jejich ostatní kosmetika je dál vidět. Ve výchozím stavu vypnuto.",
"horizon.extras.cosmetics.shown": "Zobrazeno",
"horizon.extras.cosmetics.hidden": "Skrytá",
"horizon.extras.cosmetics.name_tags": "Pouze jmenovky"
"horizon.extras.cosmetics.name_tags": "Pouze jmenovky",
"Installed": "Nainstalované",
"Apply": "Použít",
"Reset all options": "Obnovit všechny možnosti",
"A Horizon shader pack.": "Balíček shaderů Horizon.",
"An OptiFine or Iris shader pack.": "Balíček shaderů OptiFine nebo Iris.",
"In use: press to turn shaders off.": "Používá se: stisknutím vypnete shadery.",
"Press to use it.": "Stisknutím jej použijete.",
"Put shader pack .zip files or folders in it.": "Vložte do ní soubory .zip nebo složky balíčků shaderů.",
"Puts every option of this pack back to its default.": "Vrátí všechny možnosti tohoto balíčku na výchozí hodnoty.",
"Sets many options at once, as the pack groups them.": "Nastaví mnoho možností najednou, tak jak je balíček seskupuje.",
"No shader packs yet: open the pack folder and put some in it.": "Zatím žádné balíčky shaderů: otevřete složku balíčků a vložte do ní nějaké.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Vyberte balíček shaderů. Výběr používaného balíčku shadery vypne.",
"Changed options apply with Apply, or when you leave.": "Změněné možnosti se použijí tlačítkem Použít nebo při odchodu.",
"Pack settings": "Nastavení balíčku",
"Built-in settings": "Vestavěná nastavení",
"%s settings": "Nastavení %s",
"Settings made by the pack's author: they change only this pack.": "Nastavení vytvořená autorem balíčku: mění jen tento balíček."
}
@@ -73,10 +73,7 @@
"horizon.mods.settings": "Настройкӑсем",
"horizon.mods.in_world": " (тӗнчене улӑштарма хӑвар)",
"horizon.mods.open_folder": "Мод папкине уҫӑр",
"horizon.shader_packs.empty": "Шейдер пакетӗсем ҫук: вӗсене шейдер пакетӗсем папкӑна лартӑр",
"horizon.shader_options.open": "Шейдер опцийӗсем...",
"horizon.shader_options.profile": "Профиль",
"horizon.shader_options.loading": "Шейдер пакетӗн опцийӗсене вулатӑп...",
"horizon.agent.copy_details": "Ҫыхӑну даннӑйӗсене копилесе илӗр",
"horizon.multiplayer.join": "Пӗрлешӗр",
"horizon.multiplayer.cancel_reconnecting": "Ҫӗнӗрен ҫыхӑнассине пӑрахӑҫла",
@@ -330,7 +327,6 @@
"horizon.osk.close": "Хуп",
"horizon.extras.chat_animation.tooltip": "Ҫӗнӗ чат йӗрки сулахай енчен шуса кӗрет, вӑл вара пӗтӗмӗшпех курӑнмасть.",
"horizon.extras.chat_indicator.tooltip": "Чат йӗркин сулахай енчи тӗслӗ йӗр.",
"horizon.extras.wheel_cycles_settings.tooltip": "Настройкӑсенчи кнопка урлӑ ҫаврӑнакан ҫаврашка унӑн хакне улӑштарать, ваниль ҫинчи пекех. Сӳнтерсен, урапа списока ҫеҫ куҫарать.",
"horizon.extras.pack_browser.tooltip": "Ресурс пакетӗсене суйласа илсен, хушма кнопка пулать, вӑл Modrinth шырать те сирӗн пакетсен папкине пакет вырнаҫтарать. Ҫук, вӑйӑ нихҫан та Modrinth ҫыхӑнмасть.",
"horizon.extras.splitscreen.tooltip": "Тӗнчере тепӗр контроллер ҫӗнӗ вылякан пулса хутшӑнма пултарать: вӑл ыйтсан А пусмалла, унтан профиль суйласа илмелле тата ӑҫта вылямаллине суйласа илмелле.",
"horizon.splitscreen.setup.monitor": "Монитор %s",
@@ -423,6 +419,7 @@
"Frame Generation": "Кадр генерацийӗ",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Кашни икӗ чӑн-чӑн хушшинче тунӑ кадра кӑтартать: тикӗсрех, кӑштах кая юлса.",
"Shadow Cache": "Мӗлке кэшӗ",
"Shader Packs...": "Шейдер пакетӗсем...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Хӗвел, курӑну тата тӗнче пӗр пек чухне мӗлке карттипе тепӗр хут усӑ курать. Выключен по умолчанию.",
"Find BlueMap": "BlueMap тупӑр",
"On servers, finds their BlueMap web map for far terrain. Next join.": "Серверсем ҫинче инҫетри ҫӗр ҫинчи BlueMap веб-карттине тупать. Тепӗр хут хутшӑнӑр.",
@@ -484,9 +481,26 @@
"horizon.extras.cosmetics_mine.tooltip": "Пытарнӑ: кашни Horizon вылякан сире косметикӑсӑр курать, эсир те ҫав шутра. Пуҫкаҫӑн гардеробӗнчи пекех переключатель.",
"horizon.extras.cosmetics_others": "Ытти вылякансен косметики",
"horizon.extras.cosmetics_others.tooltip": "Ытти Horizon вылякансем мӗн тӑхӑнаҫҫӗ: пурте, вӗсен ячӗсен стилӗсем ҫеҫ, е нимӗн те мар. Вӑрттӑн, вӑйӑ нихҫан та вӗсем мӗн тӑхӑннине ыйтмасть.",
"horizon.extras.cosmetics_auras": "Ыттисен аурисем тата йӗрӗсем",
"horizon.extras.cosmetics_auras.tooltip": "Ытти вылякансем тӑхӑнакан аурӑсемпе йӗрсем. Выключен по умолчанию.",
"horizon.extras.cosmetics_hide_fx": "Ытти вӑййисен йӗрӗсене тата аурисене пытар",
"horizon.extras.cosmetics_hide_fx.tooltip": "Ытти вӑййисен йӗрӗсем тата аурисем пытарӑнса юлаҫҫӗ; вӗсен ытти косметики курӑнать. Йӑлана кура сӳнтернӗ.",
"horizon.extras.cosmetics.shown": "Кӑтартнӑ",
"horizon.extras.cosmetics.hidden": "Пытарнӑ",
"horizon.extras.cosmetics.name_tags": "Ят паллисем кӑна"
"horizon.extras.cosmetics.name_tags": "Ят паллисем кӑна",
"Installed": "Лартнă",
"Apply": "Усă курасси",
"Reset all options": "Пур ĕнерлевсене таçтан лартасси",
"A Horizon shader pack.": "Horizon шейдер пакечĕ.",
"An OptiFine or Iris shader pack.": "OptiFine е Iris шейдер пакечĕ.",
"In use: press to turn shaders off.": "Усă курăнать: шейдерсене сӳнтермелли пусăр.",
"Press to use it.": "Усă курма пусăр.",
"Put shader pack .zip files or folders in it.": "Шейдер пакечĕсен .zip файлĕсене е папкисене унта хурăр.",
"Puts every option of this pack back to its default.": "Ку пакетăн пур ĕнерлевне те пуçламăш хакне таврăнтарать.",
"Sets many options at once, as the pack groups them.": "Пакет ушкăнланă евĕр нумай ĕнерлеве пĕр харăсах лартать.",
"No shader packs yet: open the pack folder and put some in it.": "Шейдер пакечĕсем халлĕхе çук: пакетсен папкине уçса темиçе хурăр.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Шейдер пакечĕ суйлăр. Усă куракана суйласан шейдерсем сӳнеççĕ.",
"Changed options apply with Apply, or when you leave.": "Улшăннă ĕнерлевсем «Усă курасси» пусăмпа е тухнă чухне усă курăнаççĕ.",
"Pack settings": "Пакет ĕнерлевĕсем",
"Built-in settings": "Йĕркеленĕ ĕнерлевсем",
"%s settings": "%s ĕнерлевĕсем",
"Settings made by the pack's author: they change only this pack.": "Пакет авторĕ тунă ĕнерлевсем: вĕсем ҫак пакета çеç улăштараççĕ."
}
@@ -67,10 +67,7 @@
"horizon.mods.settings": "Gosodiadau",
"horizon.mods.in_world": " (gadewch y byd i newid)",
"horizon.mods.open_folder": "Agor Ffolder Mod",
"horizon.shader_packs.empty": "Dim pecynnau lliwiwr: rhowch nhw yn y ffolder shaderpacks",
"horizon.shader_options.open": "Opsiynau Shader...",
"horizon.shader_options.profile": "Proffil",
"horizon.shader_options.loading": "Darllen opsiynau'r pecyn lliwiwr...",
"horizon.agent.copy_details": "Copïo Manylion Cysylltiad",
"horizon.multiplayer.join": "Ymuno",
"horizon.multiplayer.cancel_reconnecting": "Canslo Ailgysylltu",
@@ -317,7 +314,6 @@
"horizon.osk.close": "Cau",
"horizon.extras.chat_animation.tooltip": "Mae llinell sgwrsio newydd yn llithro i mewn o'r chwith tra mae'n pylu i mewn, yn lle ymddangos yn gyfan.",
"horizon.extras.chat_indicator.tooltip": "Y bar lliw ar ochr chwith llinell sgwrsio.",
"horizon.extras.wheel_cycles_settings.tooltip": "Mae'r olwyn sgrolio dros fotwm yn y gosodiadau yn newid ei werth, fel yn y fanila. I ffwrdd, mae'r olwyn yn sgrolio'r rhestr yn unig.",
"horizon.extras.pack_browser.tooltip": "Mae Dewis Pecynnau Adnoddau yn cael botwm Ychwanegu sy'n chwilio Modrinth ac yn gosod pecyn yn eich ffolder pecynnau. I ffwrdd, nid yw'r gêm byth yn cysylltu â Modrinth.",
"horizon.extras.splitscreen.tooltip": "Mewn byd, gall rheolydd arall ymuno fel chwaraewr newydd: pwyswch A pan fydd yn gofyn, yna dewiswch broffil a ble i chwarae.",
"horizon.splitscreen.setup.monitor": "Monitro %s",
@@ -407,6 +403,7 @@
"Frame Generation": "Cynhyrchu Ffrâm",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Yn dangos ffrâm wedi'i gwneud i fyny rhwng pob dau go iawn: llyfnach, ychydig yn fwy oedi.",
"Shadow Cache": "Cache Cysgod",
"Shader Packs...": "Pecynnau Shader...",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Yn ailddefnyddio'r map cysgodion pecyn pan fydd yr haul, yr olygfa a'r byd yn cyd-fynd. Wedi'i ddiffodd yn ddiofyn.",
"Find BlueMap": "Dewch o hyd i BlueMap",
"On servers, finds their BlueMap web map for far terrain. Next join.": "Ar weinyddion, yn dod o hyd i'w map gwe BlueMap ar gyfer tir pell. Ymunwch nesaf.",
@@ -459,9 +456,26 @@
"horizon.extras.cosmetics_mine.tooltip": "Cudd: mae pob chwaraewr Horizon yn eich gweld heb eich colur, fe wnaethoch chi gynnwys. Yr un switsh â Wardrob y lansiwr.",
"horizon.extras.cosmetics_others": "Colur chwaraewyr eraill",
"horizon.extras.cosmetics_others.tooltip": "Beth mae chwaraewyr Horizon eraill yn ei wisgo: popeth, dim ond eu steil tag enw, neu ddim byd. Yn gudd, nid yw'r gêm byth yn gofyn beth maen nhw'n ei wisgo.",
"horizon.extras.cosmetics_auras": "Auras a llwybrau eraill",
"horizon.extras.cosmetics_auras.tooltip": "Auras a llwybrau mae chwaraewyr eraill yn eu gwisgo. Wedi'i ddiffodd yn ddiofyn.",
"horizon.extras.cosmetics_hide_fx": "Cuddio llwybrau ac awrâu chwaraewyr eraill",
"horizon.extras.cosmetics_hide_fx.tooltip": "Mae llwybrau ac awrâu chwaraewyr eraill yn aros yn gudd; mae eu colur arall yn dal i ddangos. I ffwrdd yn ddiofyn.",
"horizon.extras.cosmetics.shown": "Dangosir",
"horizon.extras.cosmetics.hidden": "Cudd",
"horizon.extras.cosmetics.name_tags": "Tagiau enw yn unig"
"horizon.extras.cosmetics.name_tags": "Tagiau enw yn unig",
"Installed": "Wedi'u gosod",
"Apply": "Gweithredu",
"Reset all options": "Ailosod pob dewis",
"A Horizon shader pack.": "Pecyn shaders Horizon.",
"An OptiFine or Iris shader pack.": "Pecyn shaders OptiFine neu Iris.",
"In use: press to turn shaders off.": "Yn cael ei ddefnyddio: pwyswch i ddiffodd shaders.",
"Press to use it.": "Pwyswch i'w ddefnyddio.",
"Put shader pack .zip files or folders in it.": "Rhowch ffeiliau .zip neu ffolderi pecynnau shaders ynddo.",
"Puts every option of this pack back to its default.": "Yn rhoi pob dewis o'r pecyn hwn yn ôl i'w ragosodiad.",
"Sets many options at once, as the pack groups them.": "Yn gosod llawer o ddewisiadau ar unwaith, fel mae'r pecyn yn eu grwpio.",
"No shader packs yet: open the pack folder and put some in it.": "Dim pecynnau shaders eto: agorwch ffolder y pecynnau a rhowch rai ynddo.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Dewiswch becyn shaders. Mae dewis yr un sy'n cael ei ddefnyddio yn diffodd shaders.",
"Changed options apply with Apply, or when you leave.": "Mae dewisiadau a newidiwyd yn cael eu gweithredu gyda Gweithredu, neu pan fyddwch yn gadael.",
"Pack settings": "Gosodiadau'r pecyn",
"Built-in settings": "Gosodiadau adeiledig",
"%s settings": "Gosodiadau %s",
"Settings made by the pack's author: they change only this pack.": "Gosodiadau a wnaed gan awdur y pecyn: maent yn newid y pecyn hwn yn unig."
}
@@ -60,10 +60,7 @@
"horizon.mods.settings": "Indstillinger",
"horizon.mods.in_world": " (lad verden ændre sig)",
"horizon.mods.open_folder": "Åbn Mod-mappe",
"horizon.shader_packs.empty": "Ingen shader-pakker: læg dem i shaderpacks-mappen",
"horizon.shader_options.open": "Indstillinger for skygge...",
"horizon.shader_options.profile": "Profil",
"horizon.shader_options.loading": "Læser shader-pakkens muligheder...",
"horizon.agent.copy_details": "Kopier forbindelsesoplysninger",
"horizon.multiplayer.join": "Deltag",
"horizon.multiplayer.cancel_reconnecting": "Annuller Gentilslutning",
@@ -301,7 +298,6 @@
"horizon.osk.close": "Luk",
"horizon.extras.chat_animation.tooltip": "En ny chatlinje glider ind fra venstre, mens den toner ind, i stedet for at virke hel.",
"horizon.extras.chat_indicator.tooltip": "Den farvede bjælke til venstre for en chatlinje.",
"horizon.extras.wheel_cycles_settings.tooltip": "Scrollhjulet over en knap i indstillingerne ændrer dens værdi, som i vanilje. Fra, hjulet ruller kun listen.",
"horizon.extras.pack_browser.tooltip": "Select Resource Packs får en Tilføj knap, der søger mod Modrinth og installerer en pakke i din pakkemappe. Off, spillet kontakter aldrig Modrinth.",
"horizon.extras.splitscreen.tooltip": "I en verden kan en anden controller deltage som en ny spiller: Tryk på A, når den spørger, vælg derefter en profil og hvor du vil spille.",
"horizon.splitscreen.setup.monitor": "Overvåg %s",
@@ -440,9 +436,27 @@
"horizon.extras.cosmetics_mine.tooltip": "Skjult: alle Horizon-spillere ser dig uden din kosmetik, inklusive dig. Den samme kontakt som løfterakettens garderobe.",
"horizon.extras.cosmetics_others": "Andre spilleres kosmetik",
"horizon.extras.cosmetics_others.tooltip": "Hvad andre Horizon-spillere bærer: alt, kun deres navnemærke eller intet. Skjult spørger spillet aldrig, hvad de har på.",
"horizon.extras.cosmetics_auras": "Andres auraer og spor",
"horizon.extras.cosmetics_auras.tooltip": "Auraer og spor, som andre spillere bærer. Fra som standard.",
"horizon.extras.cosmetics_hide_fx": "Skjul andre spilleres spor og auraer",
"horizon.extras.cosmetics_hide_fx.tooltip": "Andre spilleres spor og auraer forbliver skjulte; deres andre kosmetikker vises stadig. Slået fra som standard.",
"horizon.extras.cosmetics.shown": "Vist",
"horizon.extras.cosmetics.hidden": "Skjult",
"horizon.extras.cosmetics.name_tags": "Kun navneskilte"
"horizon.extras.cosmetics.name_tags": "Kun navneskilte",
"Shader Packs...": "Shader-pakker...",
"Installed": "Installeret",
"Apply": "Anvend",
"Reset all options": "Nulstil alle indstillinger",
"A Horizon shader pack.": "En Horizon-shaderpakke.",
"An OptiFine or Iris shader pack.": "En OptiFine- eller Iris-shaderpakke.",
"In use: press to turn shaders off.": "I brug: tryk for at slå shaders fra.",
"Press to use it.": "Tryk for at bruge den.",
"Put shader pack .zip files or folders in it.": "Læg .zip-filer eller mapper med shaderpakker i den.",
"Puts every option of this pack back to its default.": "Sætter alle denne pakkes indstillinger tilbage til standard.",
"Sets many options at once, as the pack groups them.": "Sætter mange indstillinger på én gang, som pakken grupperer dem.",
"No shader packs yet: open the pack folder and put some in it.": "Ingen shaderpakker endnu: åbn pakkemappen og læg nogle i den.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Vælg en shaderpakke. Vælger du den, der er i brug, slås shaders fra.",
"Changed options apply with Apply, or when you leave.": "Ændrede indstillinger træder i kraft med Anvend, eller når du forlader skærmen.",
"Pack settings": "Pakkeindstillinger",
"Built-in settings": "Indbyggede indstillinger",
"%s settings": "Indstillinger for %s",
"Settings made by the pack's author: they change only this pack.": "Indstillinger lavet af pakkens forfatter: de ændrer kun denne pakke."
}
@@ -65,11 +65,7 @@
"horizon.mods.dev": " (Entwicklung)",
"horizon.mods.settings": "Einstellungen",
"horizon.mods.open_folder": "Modordner öffnen",
"horizon.shader_packs.empty": "Keine Shader-Pakete: Lege sie in den Ordner shaderpacks",
"horizon.shader_packs.kind_horizon": " (Horizon)",
"horizon.shader_options.open": "Shader-Optionen …",
"horizon.shader_options.profile": "Profil",
"horizon.shader_options.loading": "Optionen des Shader-Pakets werden gelesen …",
"horizon.agent.copy_details": "Verbindungsdaten kopieren",
"horizon.multiplayer.join": "Beitreten",
"horizon.multiplayer.cancel_reconnecting": "Neuverbindung abbrechen",
@@ -222,6 +218,8 @@
"horizon.extras.no_ai": "Keine KI",
"horizon.extras.agent_control": "Agentensteuerung",
"horizon.extras.discord_presence": "Discord Rich Presence",
"horizon.extras.zoom": "Zoom",
"horizon.extras.zoom_mod_install": "Zoom: über Mods installieren",
"horizon.extras.fullbright.tooltip": "Zeigt Blöcke und Objekte bei vollem Licht, selbst an dunklen Orten.",
"horizon.extras.dynamic_lights.tooltip": "Fackeln und andere Lichtquellen, die gehalten, fallen gelassen werden oder brennen, beleuchten die Blöcke um sich herum.",
"horizon.extras.own_name_tag.tooltip": "Zeigt deinen Namen in der dritten Person über deinem Kopf an, so wie andere Spieler ihn sehen. Versteckt, wenn der Server die Namen deines Teams verbirgt oder du unsichtbar bist.",
@@ -301,6 +299,35 @@
"Frame Generation": "Bildgenerierung",
"Shows a made-up frame between each two real ones: smoother, a little more lag.": "Zeigt zwischen zwei echten Bildern ein errechnetes: flüssiger, etwas mehr Verzögerung.",
"Shadow Cache": "Schatten-Cache",
"Shaders": "Shader",
"Shader packs, Horizon's and shaders/ folder ones, and their options.": "Shader-Pakete, die von Horizon und die aus shaders/-Ordnern, und ihre Optionen.",
"Shader packs": "Shader-Pakete",
"Installed": "Installiert",
"Apply": "Anwenden",
"Reset all options": "Alle Optionen zurücksetzen",
"A Horizon shader pack.": "Ein Horizon-Shader-Paket.",
"An OptiFine or Iris shader pack.": "Ein OptiFine- oder Iris-Shader-Paket.",
"In use: press to turn shaders off.": "In Verwendung: Drücken, um Shader auszuschalten.",
"Press to use it.": "Drücken, um es zu verwenden.",
"Put shader pack .zip files or folders in it.": "Lege Shader-Paket-.zip-Dateien oder -Ordner hinein.",
"Puts every option of this pack back to its default.": "Setzt jede Option dieses Pakets auf den Standardwert zurück.",
"Sets many options at once, as the pack groups them.": "Stellt viele Optionen auf einmal ein, so wie das Paket sie gruppiert.",
"No shader packs yet: open the pack folder and put some in it.": "Noch keine Shader-Pakete: Öffne den Paketordner und lege welche hinein.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Wähle ein Shader-Paket. Das verwendete erneut zu wählen schaltet Shader aus.",
"Changed options apply with Apply, or when you leave.": "Geänderte Optionen gelten mit Anwenden oder beim Verlassen.",
"Pack settings": "Paketeinstellungen",
"Built-in settings": "Integrierte Einstellungen",
"%s settings": "Einstellungen für %s",
"Settings made by the pack's author: they change only this pack.": "Vom Autor des Pakets erstellte Einstellungen: Sie ändern nur dieses Paket.",
"Vanilla's own preset: sets only vanilla's options, as Minecraft does.": "Das Preset von Vanilla: setzt nur die Optionen von Vanilla, wie Minecraft.",
"Fullscreen takes the display over, at the mode below.": "Der Vollbildmodus übernimmt den Bildschirm, im Modus darunter.",
"The display mode exclusive fullscreen uses. Applies when you leave.": "Der Anzeigemodus des exklusiven Vollbilds. Gilt, wenn du das Menü verlässt.",
"Blurs the world behind menus.": "Verwischt die Welt hinter Menüs.",
"How textures are sampled: sharper at a slant with Anisotropic.": "Wie Texturen abgetastet werden: mit Anisotrop schärfer im schrägen Blick.",
"How far Anisotropic filtering goes. Higher is sharper at a slant.": "Wie weit der anisotrope Filter geht. Höher ist schärfer im schrägen Blick.",
"Only with Anisotropic texture filtering.": "Nur mit anisotropem Texturfilter.",
"Shader Packs...": "Shader-Pakete …",
"Picks a shader pack, Horizon's or a shaders/ folder one, and sets its options.": "Wählt ein Shader-Paket, eines von Horizon oder einen shaders/-Ordner, und stellt seine Optionen ein.",
"Reuses the pack shadow map when sun, view and world match. Off by default.": "Verwendet die Schattenkarte des Pakets erneut, wenn Sonne, Blick und Welt gleich bleiben. Standardmäßig aus.",
"Synchronous": "Synchron",
"Asynchronous": "Asynchron",
@@ -345,10 +372,14 @@
"horizon.extras.header.cosmetics": "Kosmetik",
"horizon.extras.cosmetics_mine": "Meine Kosmetik",
"horizon.extras.cosmetics_mine.tooltip": "Ausgeblendet: Alle Horizon-Spieler sehen dich ohne deine Kosmetik, du selbst auch. Derselbe Schalter wie in der Garderobe des Launchers.",
"key.emote": "Emote-Rad",
"horizon.emote_wheel.title": "Emotes",
"horizon.emote_wheel.empty": "Noch keine Emotes",
"horizon.emote_wheel.help": "Loslassen oder klicken zum Abspielen · 1–8 · Esc schließt",
"horizon.extras.cosmetics_others": "Kosmetik anderer Spieler",
"horizon.extras.cosmetics_others.tooltip": "Was andere Horizon-Spieler tragen: alles, nur ihre Namensschild-Stile oder nichts. Ausgeblendet fragt das Spiel nie, was sie tragen.",
"horizon.extras.cosmetics_auras": "Auren und Spuren anderer",
"horizon.extras.cosmetics_auras.tooltip": "Auren und Spuren, die andere Spieler tragen. Standardmäßig aus.",
"horizon.extras.cosmetics_hide_fx": "Spuren und Auren anderer Spieler ausblenden",
"horizon.extras.cosmetics_hide_fx.tooltip": "Spuren und Auren anderer Spieler bleiben ausgeblendet; ihre anderen Kosmetika sind weiter sichtbar. Standardmäßig aus.",
"horizon.extras.cosmetics.shown": "Angezeigt",
"horizon.extras.cosmetics.hidden": "Ausgeblendet",
"horizon.extras.cosmetics.name_tags": "Nur Namensschilder",
@@ -67,10 +67,7 @@
"horizon.mods.settings": "Ρυθμίσεις",
"horizon.mods.in_world": " (άσε τον κόσμο να αλλάξει)",
"horizon.mods.open_folder": "Ανοίξτε το φάκελο Mod",
"horizon.shader_packs.empty": "Χωρίς πακέτα shader: τοποθετήστε τα στο φάκελο shaderpacks",
"horizon.shader_options.open": "Επιλογές Shader...",
"horizon.shader_options.profile": "Προφίλ",
"horizon.shader_options.loading": "Διαβάζοντας τις επιλογές του πακέτου shader...",
"horizon.agent.copy_details": "Αντιγραφή στοιχείων σύνδεσης",
"horizon.multiplayer.join": "Εγγραφείτε",
"horizon.multiplayer.cancel_reconnecting": "Ακύρωση επανασύνδεσης",
@@ -317,7 +314,6 @@
"horizon.osk.close": "Κλείσιμο",
"horizon.extras.chat_animation.tooltip": "Μια νέα γραμμή συνομιλίας ολισθαίνει από τα αριστερά ενώ σβήνει, αντί να εμφανίζεται ολόκληρη.",
"horizon.extras.chat_indicator.tooltip": "Η έγχρωμη γραμμή στα αριστερά μιας γραμμής συνομιλίας.",
"horizon.extras.wheel_cycles_settings.tooltip": "Ο τροχός κύλισης πάνω από ένα κουμπί στις ρυθμίσεις αλλάζει την τιμή του, όπως στη βανίλια. Ανενεργό, ο τροχός κάνει κύλιση μόνο στη λίστα.",
"horizon.extras.pack_browser.tooltip": "Το Select Resource Packs παίρνει ένα κουμπί Προσθήκη που αναζητά το Modrinth και εγκαθιστά ένα πακέτο στο φάκελο των πακέτων σας. Εκτός, το παιχνίδι δεν έρχεται ποτέ σε επαφή με τη Modrinth.",
"horizon.extras.splitscreen.tooltip": "Σε έναν κόσμο, ένας άλλος ελεγκτής μπορεί να εγγραφεί ως νέος παίκτης: πατήστε A όταν σας ζητήσει, μετά επιλέξτε ένα προφίλ και πού θα παίξετε.",
"horizon.splitscreen.setup.monitor": "Οθόνη %s",
@@ -462,9 +458,27 @@
"horizon.extras.cosmetics_mine.tooltip": "Κρυφό: κάθε παίκτης του Horizon σας βλέπει χωρίς τα καλλυντικά σας, συμπεριλαμβανομένων εσείς. Ο ίδιος διακόπτης με την ντουλάπα του εκτοξευτή.",
"horizon.extras.cosmetics_others": "Καλλυντικά άλλων παικτών",
"horizon.extras.cosmetics_others.tooltip": "Τι φοράνε οι άλλοι παίκτες του Horizon: τα πάντα, μόνο τα στυλ των ετικετών τους ή τίποτα. Κρυφά, το παιχνίδι δεν ρωτά ποτέ τι φοράνε.",
"horizon.extras.cosmetics_auras": "Οι αύρες και τα μονοπάτια των άλλων",
"horizon.extras.cosmetics_auras.tooltip": "Αύρες και μονοπάτια φορούν άλλοι παίκτες. Απενεργοποίηση από προεπιλογή.",
"horizon.extras.cosmetics_hide_fx": "Απόκρυψη ιχνών και αυρών άλλων παικτών",
"horizon.extras.cosmetics_hide_fx.tooltip": "Τα ίχνη και οι αύρες των άλλων παικτών μένουν κρυφά· τα άλλα διακοσμητικά τους εξακολουθούν να φαίνονται. Ανενεργό από προεπιλογή.",
"horizon.extras.cosmetics.shown": "Εμφανίζεται",
"horizon.extras.cosmetics.hidden": "Κρυφό",
"horizon.extras.cosmetics.name_tags": "Μόνο ετικέτες ονομάτων"
"horizon.extras.cosmetics.name_tags": "Μόνο ετικέτες ονομάτων",
"Shader Packs...": "Πακέτα Shader...",
"Installed": "Εγκατεστημένα",
"Apply": "Εφαρμογή",
"Reset all options": "Επαναφορά όλων των επιλογών",
"A Horizon shader pack.": "Ένα πακέτο shader του Horizon.",
"An OptiFine or Iris shader pack.": "Ένα πακέτο shader του OptiFine ή του Iris.",
"In use: press to turn shaders off.": "Σε χρήση: πατήστε για απενεργοποίηση των shader.",
"Press to use it.": "Πατήστε για χρήση.",
"Put shader pack .zip files or folders in it.": "Βάλτε μέσα αρχεία .zip ή φακέλους πακέτων shader.",
"Puts every option of this pack back to its default.": "Επαναφέρει κάθε επιλογή αυτού του πακέτου στην προεπιλογή της.",
"Sets many options at once, as the pack groups them.": "Ορίζει πολλές επιλογές ταυτόχρονα, όπως τις ομαδοποιεί το πακέτο.",
"No shader packs yet: open the pack folder and put some in it.": "Δεν υπάρχουν ακόμη πακέτα shader: ανοίξτε το φάκελο πακέτων και βάλτε μερικά.",
"Pick a shader pack. Picking the one in use turns shaders off.": "Επιλέξτε ένα πακέτο shader. Η επιλογή αυτού που χρησιμοποιείται απενεργοποιεί τα shader.",
"Changed options apply with Apply, or when you leave.": "Οι αλλαγμένες επιλογές εφαρμόζονται με το Εφαρμογή ή όταν φύγετε.",
"Pack settings": "Ρυθμίσεις πακέτου",
"Built-in settings": "Ενσωματωμένες ρυθμίσεις",
"%s settings": "Ρυθμίσεις %s",
"Settings made by the pack's author: they change only this pack.": "Ρυθμίσεις από τον δημιουργό του πακέτου: αλλάζουν μόνο αυτό το πακέτο."
}
Loaded 100 of 961 files, more files were not shown because too many files have changed in this diff. Show more