Merge current main and preserve PR 59 review fixes

This commit is contained in:
Cosmic
2026-10-14 14:56:18 -04:00
88 changed files with 6179 additions and 448 deletions
+2 -2
View File
@@ -22,9 +22,9 @@ jobs:
python tools/check_public_tree.py --history
- name: Test offline research tooling
run: python -m unittest discover -s tests -v
- name: Install Rust toolchain and the ALSA headers the client's audio links against
- name: Install Rust toolchain and the ALSA and udev headers the client links against
run: |
sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev
sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
rustup toolchain install stable --profile minimal --component rustfmt --component clippy
- name: Check formatting and lint
run: |
+6 -7
View File
@@ -20,7 +20,7 @@ jobs:
# The C runtime linked in, so the game runs without the Visual C++ redistributable.
env:
RUSTFLAGS: -C target-feature=+crt-static
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
- name: Only system DLLs
# Vulkan and the rest are loaded at run time; a linked non-system DLL is a
# "DLL not found" dialog on some players' machines.
@@ -29,8 +29,7 @@ jobs:
python tools/check_imports.py target/release/horizon-ctl.exe
python tools/check_imports.py target/release/horizon-prepare.exe
- name: Package
shell: bash
run: packaging/package.sh target/release/horizon-client.exe dist/horizon-windows-x64
run: cargo +stable run --locked -p xtask -- package target/release/horizon-client.exe dist/horizon-windows-x64
- uses: actions/upload-artifact@v4
with:
name: horizon-windows-x64
@@ -41,17 +40,17 @@ jobs:
- uses: actions/checkout@v4
- name: Install Rust toolchain
run: rustup toolchain install stable --profile minimal
- name: ALSA headers
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev
- name: ALSA and udev headers
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
- name: Build the client
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
- name: Standard loader and libraries only
run: |
python3 tools/check_imports.py target/release/horizon-client
python3 tools/check_imports.py target/release/horizon-ctl
python3 tools/check_imports.py target/release/horizon-prepare
- name: Package
run: packaging/package.sh target/release/horizon-client dist/horizon-linux-x86_64
run: cargo +stable run --locked -p xtask -- package target/release/horizon-client dist/horizon-linux-x86_64
- uses: actions/upload-artifact@v4
with:
name: horizon-linux-x86_64
+9
View File
@@ -18,3 +18,12 @@
/saves/
/tools/logs/
.DS_Store
# What the client writes to its working directory when run from the repo root.
/options.txt
/horizon.txt
/horizon-graphics.txt
/horizon-controller.txt
/servers.dat
/screenshots/
/crash-reports/
/debug/
Generated
+115
View File
@@ -648,6 +648,12 @@ dependencies = [
"zlib-rs",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foldhash"
version = "0.1.5"
@@ -754,6 +760,40 @@ dependencies = [
"r-efi 6.0.0",
]
[[package]]
name = "gilrs"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "902fb00d3f6398e635be22e5c837b303c501835cca7ac11a47bba138f7aafdd8"
dependencies = [
"fnv",
"gilrs-core",
"log",
"uuid",
"vec_map",
]
[[package]]
name = "gilrs-core"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc7f0ce6237abcc0523f2a5502b1e3fe5802daaae47ac14e166fe49551301ea9"
dependencies = [
"inotify",
"js-sys",
"libc",
"libudev-sys",
"log",
"nix",
"objc2-core-foundation",
"objc2-io-kit",
"uuid",
"vec_map",
"wasm-bindgen",
"web-sys",
"windows 0.62.2",
]
[[package]]
name = "glam"
version = "0.30.10"
@@ -840,6 +880,7 @@ dependencies = [
"chrono",
"cpal",
"flate2",
"gilrs",
"glam",
"horizon-assets",
"horizon-core",
@@ -848,6 +889,7 @@ dependencies = [
"horizon-world",
"log",
"miniz_oxide 0.8.9",
"naga",
"png",
"pollster",
"serde_json",
@@ -932,6 +974,26 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "inotify"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
dependencies = [
"bitflags 2.13.2",
"inotify-sys",
"libc",
]
[[package]]
name = "inotify-sys"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
dependencies = [
"libc",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -1073,6 +1135,16 @@ dependencies = [
"redox_syscall 0.9.4",
]
[[package]]
name = "libudev-sys"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"
dependencies = [
"libc",
"pkg-config",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@@ -1230,6 +1302,18 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "nix"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nom"
version = "8.0.0"
@@ -1486,6 +1570,17 @@ dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-io-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"
dependencies = [
"bitflags 2.13.2",
"libc",
"objc2-core-foundation",
]
[[package]]
name = "objc2-io-surface"
version = "0.3.2"
@@ -2425,6 +2520,22 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "uuid"
version = "1.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -3235,6 +3346,10 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]]
name = "xtask"
version = "0.1.0"
[[package]]
name = "xxhash-rust"
version = "0.8.19"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher"]
members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare"]
members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "xtask"]
resolver = "2"
[workspace.package]
+2 -2
View File
@@ -130,7 +130,7 @@ Commands block until the action is done and reply with what happened; errors are
## Build from source
For developers. Requirements: Rust 1.90 or newer, Python 3.10 or newer, JDK 25, and on Linux the ALSA development headers (`libasound2-dev` on Debian and Ubuntu). Development and the vanilla harnesses run on Linux.
For developers. Requirements: Rust 1.90 or newer, Python 3.10 or newer, JDK 25, and on Linux the ALSA and udev development headers (`libasound2-dev libudev-dev` on Debian and Ubuntu). Development and the vanilla harnesses run on Linux.
Horizon contains no game files and never downloads them. It builds its resources from **your own copy** of Minecraft: Java Edition 26.3, verified against the checksums in `research-lock.json`:
@@ -141,7 +141,7 @@ Horizon contains no game files and never downloads them. It builds its resources
git clone https://github.com/ludovic111/horizon.git
cd horizon
cargo run --release -p horizon-prepare -- --prepare --server-jar ~/Downloads/server.jar # needs JDK 25
python3 tools/fetch_sounds.py # optional: sounds from your launcher install
cargo run --release -p horizon-prepare -- sounds # optional: sounds from your launcher install
cargo run --release -p horizon-client
```
+6
View File
@@ -28,6 +28,8 @@ chrono = { version = "0.4.42", default-features = false, features = ["clock", "s
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
horizon-theme = { path = "../horizon-theme" }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input).
gilrs = "0.11"
[features]
# Records the call sites of mob random draws (`mob_ai_probe` traces).
@@ -35,3 +37,7 @@ rng-trace = ["horizon-core/rng-trace"]
[lints]
workspace = true
[dev-dependencies]
# Parses and validates the composed entity shader (already built for wgpu).
naga = { version = "30.0.1", features = ["wgsl-in"] }
@@ -9,6 +9,10 @@
//! 1.0), foxes and axolotls from the third, sulfur cubes have size 2, salmon
//! are small, slimes and magma cubes keep size 1, tropical fish school.
//!
//! Spawner cases (`mode=spawner`, tools/test_spawner_parity.py) tick a
//! `mobs::spawner::Spawner` loaded from the case's SNBT on the same world and
//! print its events tick by tick.
//!
//! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
assets::Assets,
@@ -25,6 +29,7 @@ use horizon_client::{
SpawnPlayer, SpawnRequest, SpawnState, Spawned, StructureAt, StructureSpawns,
spawn_box,
},
spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn},
species::{self, Baby},
},
};
@@ -73,6 +78,8 @@ struct Shared<'a> {
structures: &'a StructureSpawns,
collision: &'a BlockCollisionRegistry<'a>,
air: BlockStateId,
/// Every entity type id (`entity-types.json`).
entity_types: &'a HashSet<String>,
}
struct World<'a> {
s: &'a Shared<'a>,
@@ -95,8 +102,10 @@ struct World<'a> {
respawn: Option<[i32; 3]>,
unloaded: HashSet<(i32, i32)>,
spawn_mobs: bool,
/// Boxes of living entities (case entities, then spawned mobs).
entities: RefCell<Vec<Aabb>>,
/// The `spawner_blocks_work` game rule.
spawners_work: bool,
/// Types and boxes of living entities (case entities, then spawned mobs).
entities: RefCell<Vec<(String, Aabb)>>,
}
impl World<'_> {
fn biome_at(&self, x: i32, y: i32, z: i32) -> &str {
@@ -280,10 +289,21 @@ impl NaturalLevel for World<'_> {
block: &lookup,
binding: self.s.collision,
};
// getEntityCollisions(null, box): living shulkers are solid.
let grown = bounds.inflate(horizon_core::geometry::Vec3::new(1e-7, 1e-7, 1e-7));
no_collision_empty(&mut world, bounds)
&& !self
.entities
.borrow()
.iter()
.any(|(id, b)| id == "minecraft:shulker" && b.intersects(grown))
}
fn unobstructed(&self, bounds: Aabb) -> bool {
!self.entities.borrow().iter().any(|b| b.intersects(bounds))
!self
.entities
.borrow()
.iter()
.any(|(_, b)| b.intersects(bounds))
}
fn spawn_mobs(&self) -> bool {
self.spawn_mobs
@@ -299,6 +319,28 @@ impl NaturalLevel for World<'_> {
}
}
impl SpawnerLevel for World<'_> {
fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool {
self.players.iter().any(|(p, mode)| {
let d = (p[0] - x).powi(2) + (p[1] - y).powi(2) + (p[2] - z).powi(2);
mode != "spectator" && (range < 0.0 || d < range * range)
})
}
fn spawner_blocks_work(&self) -> bool {
self.spawners_work
}
fn entity_exists(&self, id: &str) -> bool {
self.s.types.types.contains_key(id) || self.s.entity_types.contains(id)
}
fn count_entities(&self, id: &str, bounds: Aabb) -> usize {
self.entities
.borrow()
.iter()
.filter(|(k, b)| k == id && b.intersects(bounds))
.count()
}
}
/// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random.
fn neutral_box(l: &World, r: &SpawnRequest) -> Aabb {
let t = &l.s.types.types[r.entity];
@@ -369,6 +411,17 @@ fn main() -> horizon_client::Result<()> {
let biomes = Biomes::load(root)?;
let structures = StructureSpawns::load(root);
let collision = collisions::load(root, registry)?;
let entity_types: HashSet<String> = fs::read(root.join("entity-types.json"))
.ok()
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
.and_then(|v| {
v.as_object().map(|o| {
o.keys()
.map(|k| horizon_client::command::args::normalize(k))
.collect()
})
})
.unwrap_or_default();
let shared = Shared {
facts: &facts,
data: &data,
@@ -378,6 +431,7 @@ fn main() -> horizon_client::Result<()> {
structures: &structures,
collision: &collision,
air: facts.air,
entity_types: &entity_types,
};
let mut adaptation: HashMap<String, bool> = HashMap::new();
let mut out = String::new();
@@ -538,12 +592,18 @@ fn main() -> horizon_client::Result<()> {
respawn,
unloaded,
spawn_mobs: get("rules", "1") != "0",
spawners_work: get("spawners", "1") != "0",
entities: RefCell::new(
case_entities
.iter()
.filter_map(|(t, p, _)| {
let t = types.types.get(t)?;
Some(spawn_box(p[0], p[1], p[2], t.width as f32, t.height as f32))
.filter_map(|(id, p, _)| {
let t = types.types.get(id)?;
// Entity.setPos (a shulker sits at its block's centre).
let p = horizon_client::mobs::spawner::entity_position(t.species, *p);
Some((
id.clone(),
spawn_box(p[0], p[1], p[2], t.width as f32, t.height as f32),
))
})
.collect(),
),
@@ -560,14 +620,16 @@ fn main() -> horizon_client::Result<()> {
let mut log: Vec<String> = Vec::new();
let mut spawn = |l: &World, r: &SpawnRequest| -> Option<Spawned> {
let bounds = neutral_box(l, r);
l.entities.borrow_mut().push(bounds);
l.entities.borrow_mut().push((r.entity.to_owned(), bounds));
Some(Spawned {
bounds,
school: true,
})
};
let mode = get("mode", "chunk");
if mode == "gen" {
if mode == "spawner" {
spawner_case(&world, &get, &mut random, &mut log)?;
} else if mode == "gen" {
let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?);
// The level random of the spawn predicates: no creature's predicate
// draws from it (the oracle's answers fixed values).
@@ -686,3 +748,86 @@ fn main() -> horizon_client::Result<()> {
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
/// `SpawnerBlockEntity.serverTick` `ticks` times at `spos` for the spawner in
/// `snbt` (base64 SNBT), as the oracle logs it.
fn spawner_case(
world: &World,
get: &dyn Fn(&str, &'static str) -> String,
random: &mut LegacyRandom,
log: &mut Vec<String>,
) -> horizon_client::Result<()> {
let v: Vec<i32> = get("spos", "0,0,0")
.split(',')
.map(|n| n.parse().unwrap_or(0))
.collect();
let pos = [v[0], v[1], v[2]];
let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?;
let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0;
let mut spawner = Spawner::load(&tag);
let ticks: i32 = get("ticks", "1").parse()?;
for tick in 0..ticks {
let mut events = Vec::new();
let mut spawned = std::collections::VecDeque::new();
let mut spawn = |l: &World, r: &SpawnerSpawn| -> Option<SpawnerAdded> {
let t = l.s.types.types.get(r.id)?;
let [x, y, z] = r.position;
let bounds = spawn_box(x, y, z, t.width as f32, t.height as f32);
l.entities.borrow_mut().push((r.id.to_owned(), bounds));
spawned.push_back(format!(
"{tick} spawn {} {} {} {} {}",
r.id,
bits(x),
bits(y),
bits(z),
// Shulker.finalizeSpawn faces it south.
yaw_text(
r.id,
if r.finalize && r.id == "minecraft:shulker" {
0.0
} else {
r.yaw
}
)
));
Some(SpawnerAdded {
id: spawned.len() as u32,
bounds,
mob: true,
})
};
spawner.server_tick(world, random, pos, &mut spawn, &mut events);
for e in events {
match e {
SpawnerEvent::BlockUpdated => log.push(format!("{tick} update")),
SpawnerEvent::BlockEvent(id) => log.push(format!("{tick} bevent {id} 0")),
// Each spawn's level event follows its tryAddFreshEntityWithPassengers.
SpawnerEvent::LevelEvent(id) => {
log.extend(spawned.pop_front());
log.push(format!("{tick} levent {id} 0"));
}
SpawnerEvent::EntityPlace(_, p) => log.push(format!(
"{tick} gevent minecraft:entity_place {} {} {}",
p[0], p[1], p[2]
)),
SpawnerEvent::SpawnAnim(_) => log.push(format!("{tick} eevent 20")),
}
}
}
let next = spawner
.next_data()
.and_then(|d| d.id())
.unwrap_or_else(|| "-".into());
let pots: Vec<String> = spawner
.potentials
.iter()
.map(|(d, w)| format!("{}*{w}", d.id().unwrap_or_else(|| "-".into())))
.collect();
log.push(format!(
"end delay={} next={next} pots={}",
spawner.spawn_delay as i16,
pots.join(",")
));
log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0)));
Ok(())
}
@@ -278,6 +278,7 @@ fn main() -> Result<()> {
jump: mask & 16 != 0,
shift: mask & 32 != 0,
sprint: mask & 64 != 0,
analog: None,
})?;
}
"movement_statistics" => world.check_movement_statistics(vector(&op["value"]))?,
@@ -457,7 +458,7 @@ fn main() -> Result<()> {
"weaving" => world.player.status.weaving = op["value"].as_bool().unwrap(),
"flying" => {
let flying = op["value"].as_bool().unwrap();
world.player.may_fly = flying;
world.player.may_fly = op["may_fly"].as_bool().unwrap_or(flying);
world.player.flying = flying;
}
"trigger" => world.player.jump_trigger_time = op["value"].as_i64().unwrap() as i32,
@@ -7,7 +7,7 @@ use horizon_client::{
biome::{BiomeInfo, Biomes, GrassModifier},
blocks::BlockFacts,
chunk::{Chunk, Light, MIN_Y, index},
mesher::{MeshTables, Mesher, OPAQUE_LAYER, Vertex},
mesher::{MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
models,
};
use horizon_core::biome::BiomeZoom;
@@ -33,7 +33,8 @@ fn argb(color: u32) -> i32 {
}
/// Horizon keeps sky*16 in the low byte and block*16 above it; vanilla's light
/// coords keep block in the low half-word and sky in the high one.
fn light_coords(light: u32) -> i32 {
fn light_coords(light: u16) -> i32 {
let light = u32::from(light);
((light & 0xFF) << 16 | (light >> 8 & 0xFF)) as i32
}
/// Scenes cover the 3x3 chunk region around chunk (0, 0).
@@ -146,9 +147,12 @@ fn scene(
}
for quad in vertices {
let sprite = names
.get(&(quad[0].layer & !OPAQUE_LAYER))
.get(&u32::from(quad[0].layer & !OPAQUE_LAYER))
.ok_or("unknown sprite layer")?;
if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) {
if quad
.iter()
.any(|v: &TerrainVertex| v.layer != quad[0].layer)
{
return Err("quad mixes sprite layers".into());
}
let vertices: Vec<Value> = quad
@@ -17,6 +17,7 @@ fn keys(mask: u64) -> Keys {
jump: mask & 16 != 0,
shift: mask & 32 != 0,
sprint: mask & 64 != 0,
analog: None,
}
}
fn main() -> Result<()> {
@@ -252,6 +252,10 @@ pub const COMMANDS: &[Cmd] = &[
["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap"]), "what to do")], mcp: true, local: false),
cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "",
["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false),
cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them",
"Buttons by position: south east west north lb rb lt rt select start ls rs up down left right (south is Xbox A / PlayStation cross). Sticks run -1..1 with up positive and stay tilted until centred; triggers 0..1. Merged with any real controller; status lists the connected ones and what is held.",
["horizon-ctl pad south tap", "horizon-ctl pad stick left 0 1", "horizon-ctl pad trigger right 1", "horizon-ctl pad status"],
&[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: false, local: false),
cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false),
cmd!("stop", Act, "stop", "cancel the running action (goto, break...) and release every key", "", ["horizon-ctl stop"], &[], mcp: true, local: false),
// Screens
+9 -3
View File
@@ -66,6 +66,8 @@ pub enum BlockEntity {
Banner(Banner),
/// `CrafterBlockEntity`.
Crafter(Crafter),
/// `SpawnerBlockEntity` (`crate::mobs::spawner`).
Spawner(Box<crate::mobs::spawner::Spawner>),
}
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
/// and the ticks left in the crafting animation.
@@ -180,6 +182,9 @@ impl BlockEntity {
if name == "minecraft:creaking_heart" {
return Some(Self::CreakingHeart(Box::default()));
}
if name == "minecraft:spawner" {
return Some(Self::Spawner(Box::default()));
}
if name == "minecraft:lectern" {
return Some(Self::Lectern(Lectern::default()));
}
@@ -255,6 +260,7 @@ impl BlockEntity {
Self::Banner(_) => "minecraft:banner",
Self::Crafter(_) => "minecraft:crafter",
Self::CreakingHeart(_) => "minecraft:creaking_heart",
Self::Spawner(_) => "minecraft:mob_spawner",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -264,7 +270,7 @@ impl BlockEntity {
Self::Brewing(b) => b.items.iter().flatten().cloned().collect(),
Self::Sign(_) => Vec::new(),
Self::Jukebox(j) => j.record.iter().cloned().collect(),
Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(),
Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
@@ -283,7 +289,7 @@ impl BlockEntity {
| Self::Sculk(_)
| Self::Banner(_) => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_) => &[],
Self::CreakingHeart(_) | Self::Spawner(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -298,7 +304,7 @@ impl BlockEntity {
| Self::Sculk(_)
| Self::Banner(_) => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_) => &mut [],
Self::CreakingHeart(_) | Self::Spawner(_) => &mut [],
}
}
}
+72
View File
@@ -67,6 +67,32 @@ impl Names {
impl Creative {
pub const WIDTH: f32 = 195.0;
pub const HEIGHT: f32 = 136.0;
pub const TRASH_POSITION: (f32, f32) = (173.0, 112.0);
/// Visible player slots in the creative inventory tab (game slot ids).
pub fn inventory_slots() -> impl Iterator<Item = usize> {
(0..36).chain(500..505)
}
/// CreativeModeInventoryScreen.selectTab positions its InventoryMenu wrappers.
pub fn inventory_slot_position(slot: usize) -> Option<(f32, f32)> {
match slot {
0..9 => Some((9.0 + slot as f32 * 18.0, 112.0)),
9..36 => Some((
9.0 + ((slot - 9) % 9) as f32 * 18.0,
54.0 + ((slot - 9) / 9) as f32 * 18.0,
)),
500..504 => {
let position = slot - 500;
Some((
54.0 + (position / 2) as f32 * 54.0,
6.0 + (position % 2) as f32 * 27.0,
))
}
504 => Some((35.0, 20.0)),
_ => None,
}
}
/// The scrollbar track (insideScrollbar), relative to the screen origin.
pub const SCROLL_X: f32 = 175.0;
pub const SCROLL_Y: f32 = 18.0;
@@ -391,6 +417,52 @@ mod tests {
Creative::from_json(&raw).unwrap()
}
#[test]
fn inventory_tab_slot_layout_matches_vanilla() {
assert_eq!(Creative::inventory_slots().count(), 41);
for (slot, expected) in [
(0, (9.0, 112.0)),
(8, (153.0, 112.0)),
(9, (9.0, 54.0)),
(35, (153.0, 90.0)),
(500, (54.0, 6.0)),
(501, (54.0, 33.0)),
(502, (108.0, 6.0)),
(503, (108.0, 33.0)),
(504, (35.0, 20.0)),
] {
assert_eq!(Creative::inventory_slot_position(slot), Some(expected));
}
assert_eq!(Creative::inventory_slot_position(100), None);
assert_eq!(Creative::TRASH_POSITION, (173.0, 112.0));
let mut c = creative(90);
c.select(2);
assert!(c.tab().inventory);
assert!(!c.can_scroll(&Names {
map: HashMap::new()
}));
}
#[test]
fn inventory_tab_can_return_to_category_and_search() {
let mut c = creative(90);
for (selected, inventory, search) in [
(2, true, false),
(0, false, false),
(1, false, true),
(2, true, false),
] {
c.search = "anvil".into();
c.scroll = 0.5;
c.select(selected);
assert_eq!(c.selected, selected);
assert_eq!(c.tab().inventory, inventory);
assert_eq!(c.tab().search, search);
assert!(c.search.is_empty());
assert_eq!(c.scroll, 0.0);
}
}
#[test]
fn hidden_tabs_are_skipped() {
let c = creative(0);
+7 -5
View File
@@ -48,12 +48,14 @@ fn entity_light(normal: vec3<f32>, nether: bool) -> f32 {
let l1 = normalize(vec3(-0.2, select(1.0, -1.0, nether), 0.7));
return min(1.0, (max(0.0, dot(l0, normal)) + max(0.0, dot(l1, normal))) * 0.6 + 0.4);
}
// The OverlayTexture texel entity.vsh fetches: rows 0-7 hold the hurt red
// 0xB2FF0000; row 10 is white with alpha (1 - u / 15 * 0.75) * 255, u = 15
// for the primed TNT flash (OverlayTexture.u(1.0)), so 63. Alpha 1 changes nothing.
// The OverlayTexture texel entity.vsh fetches (constants from overlay.rs):
// the hurt red for overlays 1 and 8, the white row at column 15 for the
// primed TNT flash (5) and at column overlay - 16 for 16..=31 (a creeper's
// swelling). Alpha 1 changes nothing.
fn overlay_texel(overlay: u32) -> vec4<f32> {
if overlay == 1u || overlay == 8u { return vec4(1.0, 0.0, 0.0, 178.0 / 255.0); }
if overlay == 5u { return vec4(1.0, 1.0, 1.0, 63.0 / 255.0); }
if overlay == 1u || overlay == 8u { return HURT_OVERLAY; }
if overlay == 5u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[15]); }
if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); }
return vec4(1.0);
}
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
+358 -133
View File
@@ -73,6 +73,8 @@ mod net_harness;
mod nether_portal;
mod options;
mod packs;
mod pad;
mod pad_menu;
mod paintings;
mod passengers;
mod persist;
@@ -93,6 +95,7 @@ mod sculk_fixture;
mod shield;
mod sign_edit;
mod sniffers;
mod spawner;
mod spill;
mod station_control;
mod stations;
@@ -589,6 +592,22 @@ pub struct Resources {
/// Enchantments, workstation recipes and brewing (game/stations.rs).
stations: horizon_client::stations::StationData,
}
/// Ctrl+Q reads the physical keyboard, independently of sprint key mappings.
fn drop_whole_stack(physical_keys: &HashSet<KeyCode>) -> bool {
physical_keys.contains(&KeyCode::ControlLeft) || physical_keys.contains(&KeyCode::ControlRight)
}
fn select_creative_tab(
creative: &mut Creative,
clicks: &mut horizon_client::container_screen::Clicks,
tab: usize,
) {
creative.select(tab);
*clicks = Default::default();
// Tabs are outside the panel; their release must not drop a carried stack.
clicks.skip_release();
}
struct Game<'a> {
res: &'a mut Resources,
collision: &'a BlockCollisionRegistry<'a>,
@@ -661,6 +680,8 @@ struct Game<'a> {
previous: Instant,
/// FramerateLimitTracker.latestInputTime.
last_input: Instant,
/// Controllers (Horizon's own).
pad: pad::Pads,
frames: u64,
fps: f32,
fps_frames: u64,
@@ -829,6 +850,8 @@ struct Game<'a> {
tridents: Vec<trident::ThrownTrident>,
rockets: Vec<fireworks::Rocket>,
creaking: creaking::CreakingState,
/// Monster spawners' display mobs (`game/spawner.rs`).
spawners: spawner::SpawnerState,
trident_model: Option<horizon_client::mobs::Part>,
arrow_model: Option<horizon_client::mobs::Part>,
tnts: Vec<tnt::PrimedTnt>,
@@ -876,6 +899,10 @@ struct Game<'a> {
forced_hit: Option<Hit>,
/// Level events of this tick for the guests, and the guest acting now.
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
/// Block events (position, b0, b1, state) and entity events (id, event,
/// position) for the guests.
lan_block_events: Vec<([i32; 3], i32, i32, u16)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
lan_acting: Option<u32>,
/// Command feedback to forward to a guest.
chat_capture: Option<Vec<horizon_client::text::Text>>,
@@ -1624,6 +1651,9 @@ impl Game<'_> {
data,
} => self.sculk_charge_event(pos, data),
LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos),
LevelEvent::LevelEvent { id: 2004, pos, .. } => {
self.spawner_burst([pos.x, pos.y, pos.z])
}
LevelEvent::LevelEvent {
id: id @ 3002..=3005,
pos,
@@ -2002,6 +2032,7 @@ impl Game<'_> {
self.with_player_actor(|game| game.break_block_as_player(pos))
}
fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> {
self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken);
// ServerPlayerGameMode.destroyBlock.
let state = self.world.block(pos[0], pos[1], pos[2]);
let facts = self.res.facts.get(state).clone();
@@ -2067,7 +2098,8 @@ impl Game<'_> {
self.pop_resource(pos, d);
}
}
let xp = if silk {
// SpawnerBlock.spawnAfterBreak pops its experience whatever the tool.
let xp = if silk && &*facts.name != "minecraft:spawner" {
0
} else {
self.block_experience(&facts.name)
@@ -2673,6 +2705,7 @@ impl Game<'_> {
}
self.previous_position = feet;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
self.eye = 1.62;
@@ -2708,6 +2741,7 @@ impl Game<'_> {
self.update_totem_ready();
self.tick_command_extras();
let camera_eye = self.camera_eye_height();
let stick = self.pad_move();
if self.riding.is_some() && self.player.is_some() {
let playing = self.screen == Screen::Playing;
let held = |k| playing && self.keys.contains(&k);
@@ -2719,7 +2753,9 @@ impl Game<'_> {
jump: held(KeyCode::Space),
shift: held(KeyCode::ShiftLeft),
sprint: false,
};
analog: None,
}
.with_stick(stick.filter(|_| playing));
self.tick_riding(keys)?;
}
let riding = self.riding.is_some();
@@ -2748,7 +2784,9 @@ impl Game<'_> {
jump: held(KeyCode::Space),
shift: held(KeyCode::ShiftLeft),
sprint: held(KeyCode::ControlLeft),
};
analog: None,
}
.with_stick(stick.filter(|_| playing));
if !riding {
self.previous_position = player.position;
}
@@ -3023,6 +3061,40 @@ impl Game<'_> {
self.keys.remove(&key);
}
}
/// A key event after rebinding, as the default key of its mapping (the
/// keyboard and controllers both end here).
fn mapped_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) -> Result<()> {
// Sneak and sprint are ToggleKeyMappings: a press (or a key
// repeat) flips them when toggling; only releases reach them
// behind a screen (KeyboardHandler.keyPress).
let toggle = match key {
KeyCode::ShiftLeft => Some((0, self.settings.toggle_crouch)),
KeyCode::ControlLeft => Some((1, self.settings.toggle_sprint)),
_ => None,
};
if let Some((slot, option)) = toggle {
let action = match (pressed, repeat) {
(false, _) => KeyAction::Release,
(_, false) => KeyAction::Press,
(_, true) => KeyAction::Repeat,
};
let screen_open = self.screen != Screen::Playing || self.title.is_some();
self.toggles.key(slot, action, screen_open, option);
self.sync_toggle(slot);
if !pressed {
return Ok(());
}
} else if !pressed {
self.keys.remove(&key);
return Ok(());
} else {
self.keys.insert(key);
}
if repeat {
return Ok(());
}
self.key_pressed(key)
}
/// `KeyMapping.releaseAll` when a screen opens and
/// `restoreToggleStatesOnScreenClosed` when it closes.
fn track_toggle_screens(&mut self) {
@@ -3087,7 +3159,11 @@ impl Game<'_> {
&& self.title.is_none()
&& (matches!(
self.screen,
Screen::Paused | Screen::Options | Screen::Stats | Screen::Advancements
Screen::Paused
| Screen::Options
| Screen::Stats
| Screen::Advancements
| Screen::WorldOptions
) || self.book.is_some())
}
fn capture(&mut self, capture: bool) {
@@ -3143,6 +3219,7 @@ impl Game<'_> {
let mut batch = self.hud_layers(size);
self.frame_graph
.draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas);
self.draw_pad_cursor(&mut batch);
batch
}
fn hud_layers(&mut self, size: [u32; 2]) -> HudBatch {
@@ -3443,7 +3520,13 @@ impl Game<'_> {
self.draw_book(&mut batch);
batch
}
fn creative_inventory_open(&self) -> bool {
self.screen == Screen::Creative && self.creative_screen.tab().inventory
}
fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) {
if self.creative_inventory_open() {
return Self::creative_origin(batch);
}
let (x, y) = batch.centered_origin(176.0, self.screen_height());
(x + self.recipe_book_shift(batch.width), y)
}
@@ -3454,6 +3537,9 @@ impl Game<'_> {
}
/// 300.. are the open container's slots.
fn slots(&self) -> Vec<usize> {
if self.creative_inventory_open() {
return Creative::inventory_slots().collect();
}
if let Some(v) = self.station_slots().or_else(|| self.mount_slots()) {
return v;
}
@@ -3470,7 +3556,8 @@ impl Game<'_> {
| BlockEntity::Lectern(_)
| BlockEntity::Sculk(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_),
| BlockEntity::CreakingHeart(_)
| BlockEntity::Spawner(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -3484,6 +3571,11 @@ impl Game<'_> {
}
/// InventoryMenu / CraftingMenu slot layouts.
fn slot_position(&self, i: usize) -> (f32, f32) {
if self.creative_inventory_open()
&& let Some(position) = Creative::inventory_slot_position(i)
{
return position;
}
if let Some(p) = self
.station_slot_position(i)
.or_else(|| self.machine_slot_position(i))
@@ -3593,6 +3685,32 @@ impl Game<'_> {
.find_with(&grid, n, &scale)
.map(|(name, result)| (name.to_owned(), result))
}
fn draw_inventory_slots(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) {
for i in self.slots() {
let (sx, sy) = self.slot_position(i);
if i == 504 && self.offhand.is_none() {
batch.sprite(
&self.res.atlas,
"gui/sprites/container/slot/shield",
ox + sx,
oy + sy,
);
}
if (500..504).contains(&i) && self.armor[i - 500].is_none() {
let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500];
batch.sprite(
&self.res.atlas,
&format!("gui/sprites/container/slot/{icon}"),
ox + sx,
oy + sy,
);
}
let stack = self.slot_view(i);
if let Some(stack) = stack {
self.draw_item(batch, &stack, ox + sx, oy + sy);
}
}
}
fn draw_inventory(&mut self, batch: &mut HudBatch) {
if self.draw_station(batch) {
return;
@@ -3687,7 +3805,8 @@ impl Game<'_> {
| BlockEntity::Lectern(_)
| BlockEntity::Sculk(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_),
| BlockEntity::CreakingHeart(_)
| BlockEntity::Spawner(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -3719,30 +3838,7 @@ impl Game<'_> {
if self.container.is_none() && self.craft_size != 3 && !self.mount_active() {
self.draw_inventory_player(batch, ox, oy);
}
for i in self.slots() {
let (sx, sy) = self.slot_position(i);
if i == 504 && self.offhand.is_none() {
batch.sprite(
&self.res.atlas,
"gui/sprites/container/slot/shield",
ox + sx,
oy + sy,
);
}
if (500..504).contains(&i) && self.armor[i - 500].is_none() {
let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500];
batch.sprite(
&self.res.atlas,
&format!("gui/sprites/container/slot/{icon}"),
ox + sx,
oy + sy,
);
}
let stack = self.slot_view(i);
if let Some(stack) = stack {
self.draw_item(batch, &stack, ox + sx, oy + sy);
}
}
self.draw_inventory_slots(batch, ox, oy);
self.draw_recipe_book(batch);
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
let (sx, sy) = self.slot_position(slot);
@@ -4204,7 +4300,7 @@ impl Game<'_> {
(Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap),
(None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap),
(None, KeyCode::KeyQ) => {
let all = self.keys.contains(&KeyCode::ControlLeft);
let all = drop_whole_stack(&self.physical_keys);
self.menu_click(Some(slot), i32::from(all), Input::Throw)
}
_ => false,
@@ -4307,16 +4403,21 @@ impl Game<'_> {
fn clicked_outside(&self, batch: &HudBatch) -> bool {
use horizon_client::container_screen::{Book, Image, clicked_outside};
let (ox, oy) = self.inventory_origin(batch);
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
let (shift, width, height) = if self.creative_inventory_open() {
(0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
} else {
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
(shift, width, self.screen_height() as i32)
};
let image = Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height: self.screen_height() as i32,
height,
};
let book = self
.recipe_book_area(batch)
@@ -5290,6 +5391,7 @@ impl Game<'_> {
self.tick_jukeboxes();
self.tick_beacons();
self.tick_creaking_hearts()?;
self.tick_spawners()?;
let mut lit_changes = Vec::new();
for (pos, entity) in self.world.block_entities.iter_mut() {
if let BlockEntity::Furnace(f) = entity
@@ -6672,7 +6774,12 @@ impl Game<'_> {
"sculk_catalyst" | "sculk_sensor" | "calibrated_sculk_sensor" | "sculk_shrieker" => {
(5, 5)
}
"spawner" => (15, 43),
// SpawnerBlock.spawnAfterBreak: 15 + nextInt(15) + nextInt(15).
"spawner" => {
let r = &mut self.world.random;
let a = r.next_int_bound(15).unwrap_or(0);
return (15 + a + r.next_int_bound(15).unwrap_or(0)) as u32;
}
_ => (0, 0),
};
if max == 0 {
@@ -7341,63 +7448,100 @@ impl Game<'_> {
);
}
let atlas = &self.res.atlas;
batch.text(
atlas,
&tab.title,
ox + 8.0,
oy + 6.0,
rgba(64, 64, 64, 255),
false,
);
if !tab.inventory {
batch.text(
atlas,
&tab.title,
ox + 8.0,
oy + 6.0,
rgba(64, 64, 64, 255),
false,
);
}
if tab.search {
let shown = format!("{}_", self.creative_screen.search);
batch.text(atlas, &shown, ox + 82.0, oy + 6.0, u32::MAX, true);
}
let items = self.creative_screen.items(&self.res.names);
let first = self.creative_screen.first_row(&self.res.names);
let mut hovered: Option<String> = None;
for r in 0..5 {
for c in 0..9 {
let Some(stack) = items.get((first + r) * 9 + c) else {
continue;
};
let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0);
self.draw_item(batch, stack, x, y);
if self.cursor.0 >= x
&& self.cursor.0 < x + 16.0
&& self.cursor.1 >= y
&& self.cursor.1 < y + 16.0
{
batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128));
hovered = Some(stack.item.to_string());
}
if tab.inventory {
self.draw_player_preview(
batch,
ox + 73.0,
oy + 6.0,
ox + 105.0,
oy + 49.0,
20.0,
0.0625,
);
self.draw_inventory_slots(batch, ox, oy);
if Self::creative_trash_hovered(batch, self.cursor) {
let (x, y) = Creative::TRASH_POSITION;
batch.fill(
&self.res.atlas,
ox + x,
oy + y,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
}
for c in 0..9 {
let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 112.0);
if let Some(stack) = self.inventory[c].clone() {
self.draw_item(batch, &stack, x, y);
if self.cursor.0 >= x
&& self.cursor.0 < x + 16.0
&& self.cursor.1 >= y
&& self.cursor.1 < y + 16.0
{
hovered = Some(stack.item.to_string());
}
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
let (x, y) = self.slot_position(slot);
batch.fill(
&self.res.atlas,
ox + x,
oy + y,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
}
let scrollable = self.creative_screen.rows(&self.res.names) > 5;
let scroller = if scrollable {
"gui/sprites/container/creative_inventory/scroller"
} else {
"gui/sprites/container/creative_inventory/scroller_disabled"
};
batch.sprite(
&self.res.atlas,
scroller,
ox + Creative::SCROLL_X,
oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(),
);
let items = self.creative_screen.items(&self.res.names);
let first = self.creative_screen.first_row(&self.res.names);
for r in 0..5 {
for c in 0..9 {
let Some(stack) = items.get((first + r) * 9 + c) else {
continue;
};
let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0);
self.draw_item(batch, stack, x, y);
if self.cursor.0 >= x
&& self.cursor.0 < x + 16.0
&& self.cursor.1 >= y
&& self.cursor.1 < y + 16.0
{
batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128));
hovered = Some(stack.item.to_string());
}
}
}
for c in 0..9 {
let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 112.0);
if let Some(stack) = self.inventory[c].clone() {
self.draw_item(batch, &stack, x, y);
if self.cursor.0 >= x
&& self.cursor.0 < x + 16.0
&& self.cursor.1 >= y
&& self.cursor.1 < y + 16.0
{
hovered = Some(stack.item.to_string());
}
}
}
let scrollable = self.creative_screen.rows(&self.res.names) > 5;
let scroller = if scrollable {
"gui/sprites/container/creative_inventory/scroller"
} else {
"gui/sprites/container/creative_inventory/scroller_disabled"
};
batch.sprite(
&self.res.atlas,
scroller,
ox + Creative::SCROLL_X,
oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(),
);
}
for t in &tabs {
let (tx, ty) = Creative::tab_position(t);
if self.cursor.0 >= ox + tx
@@ -7410,11 +7554,28 @@ impl Game<'_> {
}
if let Some(stack) = self.carried.clone() {
self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0);
} else if let Some(item) = hovered {
}
if tab.inventory {
if Self::creative_trash_hovered(batch, self.cursor) {
self.tooltip(batch, "Destroy Item", self.cursor.0, self.cursor.1);
} else {
self.draw_slot_tooltip(batch);
}
} else if self.carried.is_none()
&& let Some(item) = hovered
{
let name = self.res.names.item(&item);
self.tooltip(batch, &name, self.cursor.0, self.cursor.1);
}
}
fn creative_trash_hovered(batch: &HudBatch, cursor: (f32, f32)) -> bool {
let (ox, oy) = Self::creative_origin(batch);
let (x, y) = Creative::TRASH_POSITION;
cursor.0 >= ox + x
&& cursor.0 < ox + x + 16.0
&& cursor.1 >= oy + y
&& cursor.1 < oy + y + 16.0
}
fn click_creative(&mut self, right: bool) {
let Some(size) = self
.renderer
@@ -7430,14 +7591,30 @@ impl Game<'_> {
for (i, t) in tabs.iter().enumerate() {
let (tx, ty) = Creative::tab_position(t);
if cx >= ox + tx && cx < ox + tx + 26.0 && cy >= oy + ty && cy < oy + ty + 32.0 {
if t.inventory {
self.screen = Screen::Inventory;
return;
}
self.creative_screen.select(i);
select_creative_tab(&mut self.creative_screen, &mut self.inv_clicks, i);
self.inv_drag = None;
self.last_inv_click = None;
return;
}
}
if self.creative_inventory_open() {
if Self::creative_trash_hovered(&batch, self.cursor) {
if self.has_shift_down() {
self.inventory.fill(None);
self.armor.fill(None);
self.offhand = None;
self.craft_grid[..4].fill(None);
self.apply_equipment();
} else {
self.carried = None;
}
self.inv_drag = None;
self.inv_clicks = Default::default();
} else if self.slot_at(&batch, cx, cy).is_some() || self.clicked_outside(&batch) {
self.inventory_press(right);
}
return;
}
// Holding the scrollbar scrolls as the mouse moves (mouseDragged).
if !right
&& self
@@ -7765,7 +7942,7 @@ impl Game<'_> {
} else {
Vec::new()
};
let hand = if title || self.screen == Screen::Inventory || self.scoping() {
let hand = if title || self.scoping() {
Vec::new()
} else {
self.hand_geometry(alpha)
@@ -7956,7 +8133,8 @@ impl Game<'_> {
| KeyCode::Digit9
| KeyCode::KeyF
| KeyCode::KeyQ
if self.screen == Screen::Inventory && self.inventory_hotkey(key) => {}
if (self.screen == Screen::Inventory || self.creative_inventory_open())
&& self.inventory_hotkey(key) => {}
KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(),
KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""),
// key.advancements.
@@ -8002,7 +8180,7 @@ impl Game<'_> {
self.using = None;
}
KeyCode::KeyQ if self.screen == Screen::Playing => {
let all = self.keys.contains(&KeyCode::ControlLeft);
let all = drop_whole_stack(&self.physical_keys);
self.drop_held(all);
}
KeyCode::Digit1
@@ -8294,6 +8472,8 @@ impl ApplicationHandler for Game<'_> {
}
if self.screen == Screen::Inventory {
self.loom_drag();
}
if self.screen == Screen::Inventory || self.creative_inventory_open() {
self.inventory_drag_move();
}
if self.dragging && self.screen == Screen::Options {
@@ -8449,6 +8629,9 @@ impl ApplicationHandler for Game<'_> {
Screen::Creative if pressed => {
self.click_creative(button == MouseButton::Right);
}
Screen::Creative if self.creative_screen.tab().inventory => {
self.inventory_mouse_release(button == MouseButton::Right);
}
Screen::Creative if button == MouseButton::Left => {
self.creative_screen.release();
}
@@ -8529,18 +8712,23 @@ impl ApplicationHandler for Game<'_> {
WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => {
self.remote_chat_key(&event)
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::WorldOptions => {
WindowEvent::KeyboardInput { event, .. }
if self.screen == Screen::WorldOptions
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
{
self.world_options_key(&event)
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Options => {
// Options consumes presses; releases still reach the bound
// gameplay mapping below, including sneak/sprint toggles.
WindowEvent::KeyboardInput { event, .. }
if self.screen == Screen::Options && event.state == ElementState::Pressed =>
{
if let Some(shortcut) = self.edit_shortcut(&event)
&& self.options_shortcut(shortcut)
{
return Ok(());
}
if event.state == ElementState::Pressed
&& let PhysicalKey::Code(key) = event.physical_key
{
if let PhysicalKey::Code(key) = event.physical_key {
self.options_key(key, event.text.as_deref())?;
}
}
@@ -8592,36 +8780,7 @@ impl ApplicationHandler for Game<'_> {
}
None => return Ok(()),
};
// Sneak and sprint are ToggleKeyMappings: a press (or a key
// repeat) flips them when toggling; only releases reach them
// behind a screen (KeyboardHandler.keyPress).
let toggle = match key {
KeyCode::ShiftLeft => Some((0, self.settings.toggle_crouch)),
KeyCode::ControlLeft => Some((1, self.settings.toggle_sprint)),
_ => None,
};
if let Some((slot, option)) = toggle {
let action = match (event.state, event.repeat) {
(ElementState::Released, _) => KeyAction::Release,
(_, false) => KeyAction::Press,
(_, true) => KeyAction::Repeat,
};
let screen_open = self.screen != Screen::Playing || self.title.is_some();
self.toggles.key(slot, action, screen_open, option);
self.sync_toggle(slot);
if event.state != ElementState::Pressed {
return Ok(());
}
} else if event.state != ElementState::Pressed {
self.keys.remove(&key);
return Ok(());
} else {
self.keys.insert(key);
}
if event.repeat {
return Ok(());
}
self.key_pressed(key)?;
self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?;
}
WindowEvent::RedrawRequested => {
self.observe_fullscreen();
@@ -8666,6 +8825,7 @@ impl ApplicationHandler for Game<'_> {
}
}
self.apply_mouse_look();
self.pad_look(elapsed.as_secs_f32());
self.advance_flight();
let ticked = Instant::now();
let rendered = self.render()?;
@@ -8771,6 +8931,7 @@ impl ApplicationHandler for Game<'_> {
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
self.poll_control(event_loop);
self.poll_pads(event_loop);
if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout {
self.error = Some("frame-limited run timed out".into());
event_loop.exit();
@@ -9029,6 +9190,7 @@ pub fn run() -> Result<()> {
started: now,
previous: now,
last_input: now,
pad: Default::default(),
frames: 0,
fps: 0.0,
fps_frames: 0,
@@ -9152,6 +9314,7 @@ pub fn run() -> Result<()> {
tridents: Vec::new(),
rockets: Vec::new(),
creaking: Default::default(),
spawners: Default::default(),
trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"),
arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"),
tnts: Vec::new(),
@@ -9181,6 +9344,8 @@ pub fn run() -> Result<()> {
saved_for_exit: false,
forced_hit: None,
lan_events: Vec::new(),
lan_block_events: Vec::new(),
lan_entity_events: Vec::new(),
lan_acting: None,
chat_capture: None,
cmds: Default::default(),
@@ -9208,9 +9373,7 @@ pub fn run() -> Result<()> {
player_model: None,
};
game.ui.vanilla_root = vanilla_root;
game.res.atlas.font.uniform = game.settings.force_unicode;
game.res.atlas.font.japanese = game.settings.japanese_glyphs;
game.ui.chat.options = game.settings.chat_options();
game.apply_settings();
if let Some(path) = &game.options.control {
let server = horizon_client::control::Server::start(path)
.map_err(|e| format!("control socket {}: {e}", path.display()))?;
@@ -9301,3 +9464,65 @@ mod runtime_reset_tests {
assert!(stats.values.is_empty());
}
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_client::container_screen::{Button, Clicks, Release, Target};
use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys};
#[test]
fn selecting_creative_tabs_does_not_drop_the_carried_stack_on_release() {
let mut creative = Creative::from_json(&serde_json::json!({
"schema": 2,
"tabs": [{"type": "CATEGORY"}, {"type": "INVENTORY"}]
}))
.unwrap();
for button in [Button::Left, Button::Right] {
let mut clicks = Clicks::default();
for tab in [1, 1, 0, 1] {
select_creative_tab(&mut creative, &mut clicks, tab);
assert_eq!(creative.selected, tab);
assert_eq!(creative.tab().inventory, tab == 1);
assert_eq!(
clicks.release(
&Target::<usize>::Outside,
button,
false,
false,
false,
false
),
Release::Nothing
);
}
}
}
#[test]
fn stack_drop_requires_physical_ctrl_even_with_sprint_latched() {
for sprint in [false, true] {
let mut toggles = ToggleKeys::default();
if sprint {
toggles.key(SPRINT, KeyAction::Press, false, true);
toggles.key(SPRINT, KeyAction::Release, false, true);
}
assert_eq!(toggles.is_down(SPRINT), sprint);
for held in 0..4 {
let mut physical_keys = HashSet::from([KeyCode::ShiftLeft, KeyCode::KeyQ]);
if held & 1 != 0 {
physical_keys.insert(KeyCode::ControlLeft);
}
if held & 2 != 0 {
physical_keys.insert(KeyCode::ControlRight);
}
assert_eq!(drop_whole_stack(&physical_keys), held != 0);
physical_keys.remove(&KeyCode::ControlLeft);
physical_keys.remove(&KeyCode::ControlRight);
assert!(!drop_whole_stack(&physical_keys));
assert_eq!(toggles.is_down(SPRINT), sprint);
}
}
}
}
+1 -8
View File
@@ -1232,14 +1232,7 @@ impl Game<'_> {
self.playing()?;
let all = a.pos.first() == Some(&"all");
let before = self.held().map(|s| self.stack_value(s));
if all {
self.keys.insert(KeyCode::ControlLeft);
}
let result = self.key_pressed(KeyCode::KeyQ);
if all {
self.keys.remove(&KeyCode::ControlLeft);
}
result?;
self.drop_held(all);
ok(
json!({ "ok": true, "dropped_from": before, "held": self.held().map(|s| self.stack_value(s)) }),
)
+1 -1
View File
@@ -88,7 +88,7 @@ impl Game<'_> {
self.right = false;
self.capture(false);
}
fn close_book(&mut self) {
pub(super) fn close_book(&mut self) {
self.book = None;
self.capture(true);
}
+14 -2
View File
@@ -134,10 +134,12 @@ impl Game<'_> {
.chain(super::render_control::HELP)
.chain(super::sculk::HELP)
.chain(super::agent::HELP)
.chain(super::pad::HELP)
.collect::<Vec<_>>() }))),
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
"sculk" => Ok(Some(self.sculk_command(&words)?)),
"status" => Ok(Some(self.control_status())),
"pad" => Ok(Some(self.pad_command(&words)?)),
"key" => {
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
self.require_world()?;
@@ -161,8 +163,9 @@ impl Game<'_> {
self.debug_key(key, KeyAction::Release);
}
}
// Physical key presses follow the key binds like the keyboard does.
let key = if matches!(self.screen, Screen::Chat | Screen::Options) {
// Text screens consume raw presses; releases follow key binds.
let typing = matches!(self.screen, Screen::Chat | Screen::Options);
let key = if typing && arg(2)? != "up" {
key
} else {
match self.settings.keys.translate(key) {
@@ -391,6 +394,8 @@ impl Game<'_> {
"sound" => Page::Sound,
"controls" => Page::Controls,
"keybinds" => Page::KeyBinds,
"controller" => Page::Controller,
"controller-binds" => Page::PadBinds,
"mouse" => Page::Mouse,
"chat" => Page::Chat,
"accessibility" => Page::Accessibility,
@@ -570,6 +575,9 @@ impl Game<'_> {
json!({ "pos": hit.pos, "block": &*self.res.facts.get(state).name })
});
let renderer = self.renderer.as_ref().map(|r| {
let [arena_bytes, section_vertex_bytes] = r.section_vertex_bytes();
// Device memory by the backend's allocator (Vulkan; absent elsewhere).
let memory = r.device.generate_allocator_report();
json!({
"gpu": r.info.name,
"backend": format!("{:?}", r.info.backend),
@@ -578,6 +586,10 @@ impl Game<'_> {
"drawn_sections": r.drawn_sections,
"uploaded_bytes": r.uploaded_bytes,
"resident_sections": r.resident_sections(),
"arena_bytes": arena_bytes,
"section_vertex_bytes": section_vertex_bytes,
"gpu_allocated_bytes": memory.as_ref().map(|m| m.total_allocated_bytes),
"gpu_reserved_bytes": memory.as_ref().map(|m| m.total_reserved_bytes),
})
});
json!({
+102 -39
View File
@@ -24,6 +24,17 @@ use horizon_core::{
};
use std::sync::Arc;
/// The world impact sound after successful arrow damage, including self-shots.
fn arrow_impact_sound(
random: &mut impl RandomSource,
hurt: bool,
) -> Option<(&'static str, f32, f32)> {
hurt.then(|| {
let pitch = 1.2 / (random.next_float() * 0.2 + 0.9);
("minecraft:entity.arrow.hit", 1.0, pitch)
})
}
/// Mob-system state owned by the game.
#[derive(Default)]
pub(super) struct Creatures {
@@ -695,10 +706,10 @@ impl Game<'_> {
// (`entity_motion_events`).
MobEvent::GameEvent { .. } => {}
MobEvent::AttackPlayer(amount, from) => {
self.mob_hits_player(amount, from, "minecraft:mob_attack")
self.mob_hits_player(amount, from, "minecraft:mob_attack");
}
MobEvent::DamagePlayer { amount, from, kind } => {
self.mob_hits_player(amount, from, kind)
self.mob_hits_player(amount, from, kind);
}
MobEvent::ElderCurse { at } => self.elder_curse(at),
MobEvent::Push { target, velocity } => {
@@ -1266,9 +1277,9 @@ impl Game<'_> {
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
self.mob_hits_player(amount, from, kind);
}
fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) {
fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) -> bool {
if self.creative {
return;
return false;
}
let projectile = self
.res
@@ -1327,6 +1338,7 @@ impl Game<'_> {
if raised {
self.after_block(outcome, amount, attacker, projectile);
}
outcome.hurt
}
/// A status effect from a mob, arrow or splash potion (`addEffect`).
pub(super) fn give_player_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) {
@@ -1510,42 +1522,42 @@ impl Game<'_> {
seconds: 5,
}])?;
}
match who {
let hurt = match who {
Who::Player => {
if !self.creative {
self.mob_hits_player(
amount,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:arrow",
);
if let Some((e, t)) = effect {
self.give_player_effect(e, *t, 0);
}
self.audio.play(
"minecraft:entity.arrow.hit_player",
Some(atp),
1.0,
1.0,
);
let hurt = self.mob_hits_player(
amount,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:arrow",
);
if hurt && let Some((e, t)) = effect {
self.give_player_effect(e, *t, 0);
}
hurt
}
Who::Mob(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.damage(amount, source);
}
let hurt = self
.mobs
.iter_mut()
.find(|m| m.id == id)
.is_some_and(|m| m.damage(amount, source));
if p.owner == Some(Who::Player) {
self.last_hurt_by_player.insert(id);
}
let pitch = 1.2 / (self.world.random.next_float() * 0.2 + 0.9);
self.audio
.play("minecraft:entity.arrow.hit", Some(atp), 1.0, pitch);
hurt
}
};
if let Some((sound, volume, pitch)) =
arrow_impact_sound(&mut self.world.random, hurt)
{
self.audio.play(sound, Some(atp), volume, pitch);
}
}
(ProjectileKind::Arrow { .. }, Hit::Block { .. }) => {
let pitch = 1.2 / (self.world.random.next_float() * 0.2 + 0.9);
self.audio
.play("minecraft:entity.arrow.hit", Some(atp), 1.0, pitch);
if let Some((sound, volume, pitch)) =
arrow_impact_sound(&mut self.world.random, true)
{
self.audio.play(sound, Some(atp), volume, pitch);
}
}
(ProjectileKind::Snowball, hit) => {
if let Hit::Entity {
@@ -1652,11 +1664,13 @@ impl Game<'_> {
(ProjectileKind::LargeFireball { power }, hit) => {
if let Hit::Entity { who, .. } = hit {
match who {
Who::Player => self.mob_hits_player(
6.0,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:fireball",
),
Who::Player => {
self.mob_hits_player(
6.0,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:fireball",
);
}
Who::Mob(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.damage(6.0, source);
@@ -1734,11 +1748,13 @@ impl Game<'_> {
);
}
(ProjectileKind::LlamaSpit, Hit::Entity { who, .. }) => match who {
Who::Player => self.mob_hits_player(
1.0,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:spit",
),
Who::Player => {
self.mob_hits_player(
1.0,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:spit",
);
}
Who::Mob(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.damage(1.0, source);
@@ -2328,6 +2344,23 @@ impl Game<'_> {
return Ok(false);
};
let kind = stack.item.trim_end_matches("_spawn_egg").to_owned();
// EntityType.canSpawn: no monsters in peaceful (FAIL ends the click).
let id = format!("minecraft:{}", kind.trim_start_matches("minecraft:"));
if self.ui.difficulty == 0
&& let Some(t) = self.res.mob_types.get(&id)
&& !horizon_client::mobs::spawn_rules::allowed_in_peaceful(t.species)
{
return Ok(true);
}
// SpawnEggItem.useOn on a spawner sets its mob.
if let Some(done) = self.use_spawn_egg_on_spawner(hit.pos, &id) {
if done {
self.swing_arm();
self.stats.add("used", &stack.item, 1);
self.consume_held();
}
return Ok(true);
}
let p = [
hit.pos[0] + hit.face[0],
hit.pos[1] + hit.face[1],
@@ -2444,6 +2477,7 @@ impl Game<'_> {
}
}
self.elder_apparition_geometry(alpha, out);
self.spawner_geometry(camera, alpha, out);
// Projectiles: the baked vanilla arrow model, the rest as item billboards.
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
let forward = glam::Vec3::new(
@@ -2658,3 +2692,32 @@ impl Game<'_> {
let _ = self.spawn_mob("minecraft:zombified_piglin", at, false);
}
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_core::random::LegacyRandom;
#[test]
fn arrow_impact_uses_world_sound_volume_and_seeded_pitch() {
let mut random = LegacyRandom::new(0);
assert_eq!(
arrow_impact_sound(&mut random, true),
Some((
"minecraft:entity.arrow.hit",
1.0,
f32::from_bits(0x3f92d167)
))
);
let mut expected = LegacyRandom::new(0);
expected.next_float();
assert_eq!(random.next_float(), expected.next_float());
}
#[test]
fn rejected_arrow_damage_is_silent_without_drawing_pitch() {
let mut random = LegacyRandom::new(0);
assert_eq!(arrow_impact_sound(&mut random, false), None);
assert_eq!(random.next_float(), LegacyRandom::new(0).next_float());
}
}
@@ -340,6 +340,34 @@ impl Game<'_> {
disabled.join(",")
));
}
// A spawner's next spawn data (its id and number of keys), potentials and delay.
let mut spawners: Vec<_> = self
.world
.block_entities
.iter()
.filter_map(|(p, e)| match e {
BlockEntity::Spawner(s) => Some((*p, s)),
_ => None,
})
.collect();
spawners.sort_unstable_by_key(|s| s.0);
for (p, s) in spawners {
let next = s.next_data().map_or("-".to_owned(), |d| {
format!(
"{}/{}",
d.id().unwrap_or_else(|| "?".into()),
d.entity.len()
)
});
out.push(format!(
"spawner {},{},{} next={next} potentials={} delay={}",
p.0,
p.1,
p.2,
s.potentials.len(),
s.spawn_delay as i16
));
}
self.fixture_entities(&old_mobs, &old_stands, &mut out);
for (i, t) in targets.iter().enumerate() {
out.push(self.fixture_describe(i, t));
@@ -449,11 +477,19 @@ impl Game<'_> {
f64::from(pos.z) + 0.5,
],
});
self.chat_capture = Some(Vec::new());
let used = self.use_item_as_player();
self.forced_hit = None;
let messages = self.chat_capture.take().unwrap_or_default();
used?;
self.process_level_events()?;
let mut out = Vec::new();
for m in messages {
let key = m.component()["translate"]
.as_str()
.map_or_else(|| m.plain(), str::to_owned);
out.push(format!("msg {key}"));
}
if let Some(s) = &stack {
let used = self.stats.get("used", &s.item) - used_before;
if used != 0 {
+1
View File
@@ -485,6 +485,7 @@ impl Game<'_> {
player.fall_distance = 0.0;
self.previous_position = player.position;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
let pitch = self.world.random.next_float() * 0.4 + 0.8;
@@ -335,6 +335,15 @@ impl Game<'_> {
interaction: BlockInteraction,
fire: bool,
) -> Result<()> {
if let Some(p) = &self.player {
let d = [
p.position.x - center[0],
p.position.y - center[1],
p.position.z - center[2],
];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius });
}
let mut targets = self.exploded_positions(center, radius);
// Explosion.explode: the blast is heard.
let ctx = horizon_client::sculk::Context::default();
+19
View File
@@ -707,6 +707,19 @@ impl Game<'_> {
}
}
/// `Level.blockEvent` for the guests (`ClientboundBlockEventPacket`).
pub(super) fn lan_block_event(&mut self, pos: [i32; 3], b0: i32, b1: i32) {
if self.audio.capture.is_some() {
let state = self.world.block(pos[0], pos[1], pos[2]).0 as u16;
self.lan_block_events.push((pos, b0, b1, state));
}
}
/// `Level.broadcastEntityEvent` for the guests.
pub(super) fn lan_entity_event(&mut self, id: i32, event: i8, at: [f64; 3]) {
if self.audio.capture.is_some() {
self.lan_entity_events.push((id, event, at));
}
}
/// Send the tick's level events, sounds and mob animations.
fn lan_flush_effects(&mut self, host: &mut LanHost) {
for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) {
@@ -716,6 +729,12 @@ impl Game<'_> {
}
host.hub.level_event(kind, pos, data, acting);
}
for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) {
host.hub.block_event(pos, b0, b1, state);
}
for (id, event, at) in std::mem::take(&mut self.lan_entity_events) {
host.hub.entity_event(id, event, at);
}
self.lan_broadcast_effects(host);
if host.hub.guests.is_empty() {
host.mob_state.clear();
@@ -304,8 +304,6 @@ impl Game<'_> {
self.world_options = Some(o);
self.apply_world_options(&before, &wanted);
self.close_world_options();
self.screen = Screen::Playing;
self.capture(true);
return;
}
None => {}
@@ -28,7 +28,9 @@ pub(super) struct GameLevel<'g, 'a> {
pub(super) game: &'g Game<'a>,
w: MobWorld<'g>,
/// Boxes of the mobs this pass created, not yet in the game's list.
pending: std::cell::RefCell<Vec<Aabb>>,
pub(super) pending: std::cell::RefCell<Vec<Aabb>>,
/// The types and boxes of what a spawner created this tick.
pub(super) pending_ids: std::cell::RefCell<Vec<(String, Aabb)>>,
}
impl GameLevel<'_, '_> {
fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> {
@@ -165,7 +167,20 @@ impl NaturalLevel for GameLevel<'_, '_> {
binding: self.w.collision,
subject: None,
};
// getEntityCollisions(null, box): living shulkers are solid.
let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7));
no_collision_empty(&mut scene, bounds)
&& !self.game.mobs.iter().any(|m| {
m.species() == Species::Shulker
&& m.alive()
&& !m.removed
&& m.bounds().intersects(grown)
})
&& !self
.pending_ids
.borrow()
.iter()
.any(|(id, b)| id == "minecraft:shulker" && b.intersects(grown))
}
fn unobstructed(&self, bounds: Aabb) -> bool {
let player = self
@@ -194,12 +209,49 @@ impl NaturalLevel for GameLevel<'_, '_> {
self.w.data.state(self.state(x, y, z)).flags & data::LAND != 0
}
}
impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> {
fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool {
let Some(p) = self.game.player_view() else {
return false;
};
if !p.alive || p.spectator {
return false;
}
let at = self.game.player.as_ref().map(|p| p.position);
at.is_some_and(|a| {
let d = (a.x - x).powi(2) + (a.y - y).powi(2) + (a.z - z).powi(2);
range < 0.0 || d < range * range
})
}
fn spawner_blocks_work(&self) -> bool {
self.game.ui.rules.bool("spawner_blocks_work")
}
fn entity_exists(&self, id: &str) -> bool {
self.game.res.mob_types.contains_key(id) || self.game.entity_type_exists(id)
}
fn count_entities(&self, id: &str, bounds: Aabb) -> usize {
let mobs = self
.game
.mobs
.iter()
.filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds))
.count();
let pending = self
.pending_ids
.borrow()
.iter()
.filter(|(k, b)| k == id && b.intersects(bounds))
.count();
mobs + pending
}
}
impl<'a> Game<'a> {
pub(super) fn natural_level(&self) -> GameLevel<'_, 'a> {
GameLevel {
game: self,
w: self.mob_world_base(&[]),
pending: Default::default(),
pending_ids: Default::default(),
}
}
/// Creates a mob the spawner accepted, finalized the game's way; the
@@ -361,6 +361,7 @@ impl Game<'_> {
player.velocity = rotate_y(player.velocity, -rotation);
self.previous_position = player.position;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
let pitch = self.world.random.next_float() * 0.4 + 0.8;
+8 -2
View File
@@ -26,6 +26,9 @@ impl Game<'_> {
}
/// Open the options screens (OptionsScreen) from the title or pause menu.
pub(super) fn open_options(&mut self, from_title: bool) {
// Gameplay keys must not stay held behind the options screen, where
// bindings can also change before the physical key is released.
self.keys.clear();
self.screen = Screen::Options;
self.options_from_title = from_title;
let ui = &mut self.ui.options;
@@ -91,7 +94,10 @@ impl Game<'_> {
.shortcut(&self.res.atlas, shortcut, &mut self.clipboard)
}
pub(super) fn options_scroll(&mut self, amount: f32) {
self.ui.options.scroll_at(self.cursor, amount);
let size = self.gui_size();
self.ui
.options
.scroll_at(&self.settings, size, self.cursor, amount);
}
/// Mouse buttons pressed while a key is being bound.
pub(super) fn options_waiting_for_key(&self) -> bool {
@@ -106,7 +112,7 @@ impl Game<'_> {
}
Ok(())
}
fn handle_option_events(&mut self, events: Vec<Event>) -> Result<()> {
pub(super) fn handle_option_events(&mut self, events: Vec<Event>) -> Result<()> {
for e in events {
match e {
Event::Changed => {
+532
View File
@@ -0,0 +1,532 @@
//! Controllers through gilrs (Horizon's own; docs/controllers.md): the
//! active pad's state each loop iteration, its button edges dispatched as
//! the vanilla key mappings they are bound to, the left stick as an analog
//! move vector and the right stick turning the view. `horizon-ctl pad`
//! injects a virtual pad on top of the real one.
use super::{Game, Screen};
use horizon_client::{
Result,
gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble},
keybinds::{KeyBinds, key_code, mouse_button},
mouse::Rotation,
};
use serde_json::{Value, json};
use std::time::{Duration, Instant};
use winit::{event_loop::ActiveEventLoop, keyboard::KeyCode};
pub(super) const HELP: &[&str] = &[
"pad BUTTON down|up|tap a virtual controller button (south east west north lb rb lt rt select start ls rs up down left right)",
"pad stick left|right X Y tilt a virtual stick (-1..1, up positive); 0 0 centres it",
"pad trigger left|right VALUE pull a virtual trigger (0..1)",
"pad release centre and release the virtual controller",
"pad status connected controllers, the active one and its state",
];
/// The controllers and the state the game last acted on.
#[derive(Default)]
pub(super) struct Pads {
gilrs: Option<gilrs::Gilrs>,
started: bool,
/// The pad last touched; only its input counts.
active: Option<gilrs::GamepadId>,
/// The virtual pad of `horizon-ctl pad`.
injected: PadState,
/// The virtual pad was in use at the last poll.
virtual_input: bool,
/// Buttons a `pad ... tap` releases at the next poll.
taps: Vec<Button>,
edges: Edges,
/// The game tick each button went down in, and releases held back until
/// a tick has passed: vanilla samples keys once per tick, so a click
/// shorter than that (a quick stick click for sprint) would be lost.
pressed_at: [Option<u64>; 16],
late_releases: Vec<Button>,
/// The merged state of the last poll.
pub(super) state: PadState,
/// The pad drove the game last (the mouse and keyboard hand control back).
pub(super) in_use: bool,
pub(super) style: GlyphStyle,
/// The cursor the pad drives in menus.
pub(super) menu: super::pad_menu::MenuCursor,
/// Vibrations playing (an effect stops when dropped) and when they end.
rumbles: Vec<(gilrs::ff::Effect, Instant)>,
/// The last vibration asked for, for `pad status`.
last_rumble: Option<(&'static str, gamepad::Pulse)>,
/// The player's health between polls (a drop is damage taken).
health: HealthWatch,
}
fn gilrs_button(button: Button) -> gilrs::Button {
use gilrs::Button as G;
match button {
Button::South => G::South,
Button::East => G::East,
Button::West => G::West,
Button::North => G::North,
Button::LeftBumper => G::LeftTrigger,
Button::RightBumper => G::RightTrigger,
Button::LeftTrigger => G::LeftTrigger2,
Button::RightTrigger => G::RightTrigger2,
Button::Select => G::Select,
Button::Start => G::Start,
Button::LeftStick => G::LeftThumb,
Button::RightStick => G::RightThumb,
Button::DPadUp => G::DPadUp,
Button::DPadDown => G::DPadDown,
Button::DPadLeft => G::DPadLeft,
Button::DPadRight => G::DPadRight,
}
}
impl Pads {
/// A new player entity took over (spawn, respawn, a server joined, a
/// dimension change): its health is not compared with the old one's.
pub(super) fn player_replaced(&mut self) {
self.health.forget();
}
/// Open gilrs on first use. A platform without it (or a Linux without
/// udev) leaves controllers off; the game runs as before.
fn start(&mut self) {
if self.started {
return;
}
self.started = true;
self.gilrs = match gilrs::Gilrs::new() {
Ok(g) => {
for (_, pad) in g.gamepads() {
log::info!("Controller connected: {}", pad.name());
}
Some(g)
}
Err(gilrs::Error::NotImplemented(_)) => None,
Err(e) => {
log::warn!("Horizon: controllers are unavailable: {e}");
None
}
};
}
/// Drain gilrs' events and read the active pad.
fn read(&mut self) -> PadState {
let Some(gilrs) = self.gilrs.as_mut() else {
return PadState::default();
};
while let Some(gilrs::Event { id, event, .. }) = gilrs.next_event() {
use gilrs::EventType as E;
match event {
E::Connected => {
log::info!("Controller connected: {}", gilrs.gamepad(id).name());
}
E::Disconnected => {
log::info!("Controller disconnected: {}", gilrs.gamepad(id).name());
if self.active == Some(id) {
self.active = None;
}
}
E::ButtonPressed(..) => self.active = Some(id),
E::AxisChanged(_, value, _) | E::ButtonChanged(_, value, _)
if value.abs() > 0.5 =>
{
self.active = Some(id)
}
_ => {}
}
}
let Some(pad) = self.active.and_then(|id| gilrs.connected_gamepad(id)) else {
return PadState::default();
};
self.style = GlyphStyle::of_vendor(pad.vendor_id());
let mut state = PadState::default();
for button in Button::ALL {
if !matches!(button, Button::LeftTrigger | Button::RightTrigger) {
state.set(button, pad.is_pressed(gilrs_button(button)));
}
}
let axis = |a| pad.value(a);
use gilrs::Axis as A;
state.left = [axis(A::LeftStickX), axis(A::LeftStickY)];
state.right = [axis(A::RightStickX), axis(A::RightStickY)];
// Triggers arrive as analog buttons on most mappings, as plain
// buttons on some.
let trigger = |b: gilrs::Button| {
let value = pad.button_data(b).map_or(0.0, |d| d.value());
if pad.is_pressed(b) {
value.max(1.0)
} else {
value
}
};
state.triggers = [
trigger(gilrs::Button::LeftTrigger2),
trigger(gilrs::Button::RightTrigger2),
];
state
}
}
impl Game<'_> {
/// Once per loop iteration: read the pads and act on button changes.
pub(super) fn poll_pads(&mut self, event_loop: &ActiveEventLoop) {
let settings = &self.settings.controller;
if !settings.enabled {
if self.pad.state != PadState::default() {
self.pad.state = PadState::default();
for (button, down) in self.pad.edges.release_all() {
self.pad_edge(event_loop, button, down);
}
}
return;
}
self.pad.start();
let hardware = self.pad.read();
self.ui.options.pad_style = self.settings.controller.glyphs.resolve(self.pad.style);
let state = hardware.merge(&self.pad.injected);
self.pad.virtual_input = self.pad.injected != PadState::default();
for button in std::mem::take(&mut self.pad.taps) {
self.pad.injected.set(button, false);
}
let threshold = self.settings.controller.trigger_threshold;
let edges = self.pad.edges.update(&state, threshold);
if state.active(&self.settings.controller) {
self.last_input = Instant::now();
self.pad.in_use = true;
}
self.pad.state = state;
// Damage from any source, here or on a server; nothing counts on
// the title screen.
let health = self
.player
.as_ref()
.filter(|_| self.title.is_none())
.map(|p| p.health.health());
if let Some(damage) = self.pad.health.observe(health) {
self.pad_rumble(Rumble::Hurt(damage));
}
let now = Instant::now();
self.pad.rumbles.retain(|(_, end)| *end > now);
let ticking = self.title.is_none() && self.screen == Screen::Playing && !self.pause;
for button in std::mem::take(&mut self.pad.late_releases) {
if !ticking || self.pad.pressed_at[button as usize] != Some(self.ticks) {
self.pad_button_logged(event_loop, button, false);
} else {
self.pad.late_releases.push(button);
}
}
for (button, down) in edges {
self.pad_edge(event_loop, button, down);
}
self.pad_menu_frame(event_loop);
}
fn pad_edge(&mut self, event_loop: &ActiveEventLoop, button: Button, down: bool) {
let ticking = self.title.is_none() && self.screen == Screen::Playing && !self.pause;
if down {
// Pressed again before its held-back release went out.
if let Some(i) = self.pad.late_releases.iter().position(|b| *b == button) {
self.pad.late_releases.remove(i);
self.pad_button_logged(event_loop, button, false);
}
self.pad.pressed_at[button as usize] = Some(self.ticks);
} else if ticking && self.pad.pressed_at[button as usize] == Some(self.ticks) {
self.pad.late_releases.push(button);
return;
}
self.pad_button_logged(event_loop, button, down);
}
fn pad_button_logged(&mut self, event_loop: &ActiveEventLoop, button: Button, down: bool) {
if let Err(e) = self.pad_button(event_loop, button, down) {
log::warn!("Horizon: controller {}: {e}", button.name());
}
}
/// Input from the pad counts while the window has focus, or always for
/// the virtual pad (a script can't focus the window).
fn pad_focused(&self) -> bool {
self.focused || self.pad.virtual_input
}
fn pad_button(
&mut self,
event_loop: &ActiveEventLoop,
button: Button,
down: bool,
) -> Result<()> {
if down && !self.pad_focused() {
return Ok(());
}
let playing = self.title.is_none() && self.screen == Screen::Playing;
if down && playing && !self.captured && self.focused {
// Like a click into the window: take the pointer.
self.capture(true);
}
if !playing {
self.pad_menu_button(event_loop, button, down)?;
if down {
return Ok(());
}
} else if button == Button::Start {
return if down { self.pad_back() } else { Ok(()) };
}
// Releases always reach the mappings, so nothing stays held when a
// screen opened in between.
for action in self.settings.controller.actions_of(button) {
self.pad_action(action, down)?;
}
Ok(())
}
/// A bound action: a vanilla mapping acts as its default key or mouse
/// button, like a rebound keyboard key.
fn pad_action(&mut self, action: &str, down: bool) -> Result<()> {
match action {
gamepad::HOTBAR_PREVIOUS | gamepad::HOTBAR_NEXT => {
if down && self.screen == Screen::Playing {
self.selected =
gamepad::hotbar_step(self.selected, action == gamepad::HOTBAR_NEXT);
}
Ok(())
}
"key.sneak"
if self.settings.controller.toggle_sneak && !self.settings.toggle_crouch =>
{
// A stick click flips sneaking instead of holding it.
if down {
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
self.mapped_key(KeyCode::ShiftLeft, !sneaking, false)?;
}
Ok(())
}
_ => {
let default = KeyBinds::default_of(action);
if let Some(button) = mouse_button(default) {
if self.title.is_none() && self.screen == Screen::Playing {
self.play_mouse(button, down)?;
}
Ok(())
} else if let Some(key) = key_code(default) {
self.mapped_key(key, down, false)
} else {
Ok(())
}
}
}
}
/// B and Start: what Escape does where the pad is.
pub(super) fn pad_back(&mut self) -> Result<()> {
if let Some(title) = self.title.as_mut() {
title.escape();
return Ok(());
}
if self.sign_edit.is_some() {
self.close_sign_editor();
return Ok(());
}
if self.book.is_some() {
self.close_book();
return Ok(());
}
if let Some(remote) = self.remote.as_mut()
&& remote.chat_input.is_some()
{
remote.chat_input = None;
self.capture(true);
return Ok(());
}
self.key_pressed(KeyCode::Escape)
}
/// The left stick as the move vector, while playing.
pub(super) fn pad_move(&self) -> Option<[f32; 2]> {
let settings = &self.settings.controller;
if !settings.enabled
|| self.title.is_some()
|| self.screen != Screen::Playing
|| !self.pad_focused()
{
return None;
}
gamepad::move_vector(self.pad.state.left, settings.move_deadzone)
}
/// The right stick turns the view, once per frame (`Entity.turn`).
pub(super) fn pad_look(&mut self, seconds: f32) {
let settings = &self.settings.controller;
if !settings.enabled
|| self.title.is_some()
|| self.screen != Screen::Playing
|| self.player.is_none()
|| !self.pad_focused()
{
return;
}
// A long frame (a hitch) must not spin the view.
let (yaw, pitch) = gamepad::look_delta(
self.pad.state.right,
settings,
seconds.min(0.1),
self.scoping(),
);
if yaw == 0.0 && pitch == 0.0 {
return;
}
let mut rotation = Rotation {
x_rot: self.pitch,
y_rot: self.yaw,
x_rot_o: self.pitch,
y_rot_o: self.yaw,
};
rotation.turn(f64::from(yaw / 0.15), f64::from(pitch / 0.15));
self.yaw = rotation.y_rot;
self.pitch = rotation.x_rot;
}
/// Vibrate the active pad, when vibration is on and the pad is the one
/// playing (a pad lying idle while the mouse plays stays still).
/// Platforms without force feedback (gilrs on macOS) skip it.
pub(super) fn pad_rumble(&mut self, rumble: Rumble) {
let settings = &self.settings.controller;
if !settings.enabled || !settings.vibration || !self.pad.in_use {
return;
}
let Some(pulse) = rumble.pulse() else {
return;
};
self.pad.last_rumble = Some((rumble.name(), pulse));
let (Some(gilrs), Some(id)) = (self.pad.gilrs.as_mut(), self.pad.active) else {
return;
};
if !gilrs
.connected_gamepad(id)
.is_some_and(|g| g.is_ff_supported())
{
return;
}
use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks};
let length = Ticks::from_ms(pulse.millis);
let motor = |kind| BaseEffect {
kind,
scheduling: Replay {
play_for: length,
..Default::default()
},
envelope: Default::default(),
};
let magnitude = |v: f32| (v.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16;
let effect = EffectBuilder::new()
.add_effect(motor(BaseEffectType::Strong {
magnitude: magnitude(pulse.strong),
}))
.add_effect(motor(BaseEffectType::Weak {
magnitude: magnitude(pulse.weak),
}))
.repeat(Repeat::For(length))
.gamepads(&[id])
.finish(gilrs);
match effect.and_then(|e| e.play().map(|()| e)) {
Ok(effect) => {
let end = Instant::now() + Duration::from_millis(u64::from(pulse.millis) + 50);
self.pad.rumbles.push((effect, end));
}
Err(e) => log::debug!("Horizon: controller vibration: {e}"),
}
}
/// `horizon-ctl pad ...`.
pub(super) fn pad_command(&mut self, words: &[&str]) -> Result<Value> {
let arg = |i: usize| -> Result<&str> {
words
.get(i)
.copied()
.ok_or_else(|| format!("usage: {}", HELP[0]).into())
};
let number = |i: usize| -> Result<f32> {
let v: f32 = arg(i)?.parse()?;
if v.is_finite() {
Ok(v)
} else {
Err("not a number".into())
}
};
match arg(1)? {
"status" => {
let pads: Vec<Value> = self.pad.gilrs.as_ref().map_or(Vec::new(), |g| {
g.gamepads()
.map(|(id, p)| {
json!({
"name": p.name(),
"vendor": p.vendor_id(),
"product": p.product_id(),
"active": self.pad.active == Some(id),
})
})
.collect()
});
let s = &self.pad.state;
let held: Vec<&str> = Button::ALL
.into_iter()
.filter(|b| self.pad.edges.is_held(*b))
.map(Button::name)
.collect();
Ok(json!({
"enabled": self.settings.controller.enabled,
"backend": self.pad.gilrs.is_some(),
"controllers": pads,
"glyphs": self.pad.style.name(),
"last_rumble": self.pad.last_rumble.map(|(why, p)| json!({
"reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis,
})),
"in_use": self.pad.in_use,
"held": held,
"left": s.left,
"right": s.right,
"triggers": s.triggers,
}))
}
"release" => {
self.pad.injected = PadState::default();
self.pad.taps.clear();
Ok(json!({ "ok": true }))
}
"stick" => {
let v = [number(3)?.clamp(-1.0, 1.0), number(4)?.clamp(-1.0, 1.0)];
match arg(2)? {
"left" => self.pad.injected.left = v,
"right" => self.pad.injected.right = v,
other => return Err(format!("stick must be left or right, not {other}").into()),
}
Ok(json!({ "ok": true }))
}
"trigger" => {
let v = number(3)?.clamp(0.0, 1.0);
match arg(2)? {
"left" => self.pad.injected.triggers[0] = v,
"right" => self.pad.injected.triggers[1] = v,
other => {
return Err(format!("trigger must be left or right, not {other}").into());
}
}
Ok(json!({ "ok": true }))
}
name => {
let button = Button::parse(name)
.ok_or_else(|| format!("unknown pad button {name}; {}", HELP[0]))?;
match arg(2)? {
"down" => self.pad.injected.set(button, true),
"up" => self.pad.injected.set(button, false),
"tap" => {
self.pad.injected.set(button, true);
self.pad.taps.push(button);
}
other => {
return Err(
format!("pad action must be down, up or tap, not {other}").into()
);
}
}
Ok(json!({ "ok": true }))
}
}
}
}
+447
View File
@@ -0,0 +1,447 @@
//! A controller in menus, screens and inventories (Horizon's own;
//! docs/controllers.md): a virtual cursor the left stick moves and the
//! D-pad steps between slots and buttons, with A, X and the stick feeding
//! the screens the same pointer events a mouse sends. Every screen keeps
//! its mouse behaviour (drags, sliders, scrollbars) with no pad code of its
//! own.
use super::{Game, Screen};
use horizon_client::{
Result,
creative::Creative,
gamepad::{self, Button},
hud::{HudBatch, rgba},
options_ui::{Event, Page},
widgets,
};
use std::time::Instant;
use winit::{
application::ApplicationHandler,
dpi::PhysicalPosition,
event::{DeviceId, ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent},
event_loop::ActiveEventLoop,
keyboard::KeyCode,
};
/// D-pad auto-repeat: the first step at once, the next after a pause.
const REPEAT_DELAY: f32 = 0.35;
const REPEAT_EVERY: f32 = 0.09;
/// Lines per second the right stick scrolls at full tilt.
const SCROLL_SPEED: f32 = 12.0;
#[derive(Default)]
pub(super) struct MenuCursor {
/// Where the pad put the pointer (GUI pixels); `None` while the mouse
/// has it.
pos: Option<(f32, f32)>,
last_poll: Option<Instant>,
/// The stick moved the cursor last poll (it settles when let go).
moving: bool,
wheel: [f32; 2],
/// The held D-pad direction and when it last stepped.
repeat: Option<(Button, Instant, bool)>,
/// Pointer buttons the pad holds down.
held: [bool; 2],
/// The OS pointer is hidden while the pad's cursor is drawn.
os_hidden: bool,
/// Polls since a menu opened (its widgets are drawn after one frame).
open_polls: u32,
}
impl Game<'_> {
/// A menu, a screen or the title is open: the pad drives a cursor.
pub(super) fn pad_in_menu(&self) -> bool {
self.title.is_some() || self.screen != Screen::Playing
}
fn gui_scale(&self) -> Option<HudBatch> {
self.renderer
.as_ref()
.map(|r| HudBatch::new([r.config.width, r.config.height]))
}
/// Where focus can land: buttons drawn last frame, and the slots and
/// tabs of inventories (centres, GUI pixels).
fn pad_targets(&self) -> Vec<(f32, f32)> {
let mut targets: Vec<(f32, f32)> = widgets::last()
.iter()
.filter(|w| w.enabled)
.map(|w| (w.x + w.w / 2.0, w.y + w.h / 2.0))
.chain(
widgets::last_targets()
.into_iter()
.map(|[x, y, w, h]| (x + w / 2.0, y + h / 2.0)),
)
.collect();
if self.title.is_some() {
return targets;
}
let Some(batch) = self.gui_scale() else {
return targets;
};
match self.screen {
Screen::Inventory => {
let (ox, oy) = self.inventory_origin(&batch);
targets.extend(self.slots().into_iter().map(|i| {
let (x, y) = self.slot_position(i);
(ox + x + 8.0, oy + y + 8.0)
}));
}
Screen::Creative => {
let (ox, oy) = Self::creative_origin(&batch);
for r in 0..5 {
for c in 0..9 {
targets.push((ox + 17.0 + c as f32 * 18.0, oy + 26.0 + r as f32 * 18.0));
}
}
for c in 0..9 {
targets.push((ox + 17.0 + c as f32 * 18.0, oy + 120.0));
}
for t in &self.creative_screen.tabs {
let (x, y) = Creative::tab_position(t);
targets.push((ox + x + 13.0, oy + y + 16.0));
}
}
_ => {}
}
targets
}
/// Where focus starts when a menu opens: the held hotbar slot in an
/// inventory, else the first button.
fn pad_first_target(&self) -> Option<(f32, f32)> {
let batch = self.gui_scale()?;
match self.screen {
Screen::Inventory if self.title.is_none() => {
let (ox, oy) = self.inventory_origin(&batch);
let (x, y) = self.slot_position(self.selected);
return Some((ox + x + 8.0, oy + y + 8.0));
}
Screen::Creative if self.title.is_none() => {
let (ox, oy) = Self::creative_origin(&batch);
return Some((ox + 17.0 + self.selected as f32 * 18.0, oy + 120.0));
}
_ => {}
}
widgets::last()
.iter()
.find(|w| w.enabled)
.map(|w| (w.x + w.w / 2.0, w.y + w.h / 2.0))
}
/// Send the window a pointer move to `at` (GUI pixels), as the mouse would.
fn pad_pointer_to(&mut self, event_loop: &ActiveEventLoop, at: (f32, f32)) {
let (Some(window), Some(batch)) = (self.window.as_ref(), self.gui_scale()) else {
return;
};
let id = window.id();
let at = (
at.0.clamp(0.0, batch.width - 1.0),
at.1.clamp(0.0, batch.height - 1.0),
);
let position =
PhysicalPosition::new(f64::from(at.0 * batch.scale), f64::from(at.1 * batch.scale));
self.window_event(
event_loop,
id,
WindowEvent::CursorMoved {
device_id: DeviceId::dummy(),
position,
},
);
// Read back what the window made of it, so a real mouse move shows.
self.pad.menu.pos = Some(self.cursor);
}
fn pad_pointer_button(&mut self, event_loop: &ActiveEventLoop, right: bool, pressed: bool) {
let Some(id) = self.window.as_ref().map(|w| w.id()) else {
return;
};
self.pad.menu.held[usize::from(right)] = pressed;
let button = if right {
MouseButton::Right
} else {
MouseButton::Left
};
let state = if pressed {
ElementState::Pressed
} else {
ElementState::Released
};
self.window_event(
event_loop,
id,
WindowEvent::MouseInput {
device_id: DeviceId::dummy(),
state,
button,
},
);
}
fn pad_wheel(&mut self, event_loop: &ActiveEventLoop, x: f32, y: f32) {
let Some(id) = self.window.as_ref().map(|w| w.id()) else {
return;
};
self.window_event(
event_loop,
id,
WindowEvent::MouseWheel {
device_id: DeviceId::dummy(),
delta: MouseScrollDelta::LineDelta(x, y),
phase: TouchPhase::Moved,
},
);
}
/// Put the cursor where the pad last left it, or on the first target.
fn pad_take_pointer(&mut self, event_loop: &ActiveEventLoop) {
if self.pad.menu.pos.is_some() {
return;
}
let at = self.pad_first_target().unwrap_or(self.cursor);
self.pad_pointer_to(event_loop, at);
}
/// A button in a menu.
pub(super) fn pad_menu_button(
&mut self,
event_loop: &ActiveEventLoop,
button: Button,
down: bool,
) -> Result<()> {
if !down {
match button {
Button::South if self.pad.menu.held[0] => {
self.pad_pointer_button(event_loop, false, false)
}
Button::West if self.pad.menu.held[1] => {
self.pad_pointer_button(event_loop, true, false)
}
b if self.pad.menu.repeat.is_some_and(|r| r.0 == b) => self.pad.menu.repeat = None,
_ => {}
}
return Ok(());
}
// Controller Binds waiting for a button: this one (Start cancels).
if self.screen == Screen::Options
&& self.ui.options.page() == Page::PadBinds
&& let Some(action) = self.ui.options.selected_pad_action.take()
{
if button != Button::Start {
self.settings.controller.bind(action, Some(button));
}
return self.handle_option_events(vec![Event::Changed]);
}
match button {
Button::East | Button::Start => return self.pad_back(),
Button::South | Button::West => {
self.pad_take_pointer(event_loop);
self.pad_pointer_button(event_loop, button == Button::West, true);
}
// Y in an inventory: a shift-click (quick move).
Button::North if matches!(self.screen, Screen::Inventory | Screen::Creative) => {
self.pad_take_pointer(event_loop);
let held = (
self.keys.contains(&KeyCode::ShiftLeft),
self.physical_keys.contains(&KeyCode::ShiftLeft),
);
self.keys.insert(KeyCode::ShiftLeft);
self.physical_keys.insert(KeyCode::ShiftLeft);
self.pad_pointer_button(event_loop, false, true);
self.pad_pointer_button(event_loop, false, false);
if !held.0 {
self.keys.remove(&KeyCode::ShiftLeft);
}
if !held.1 {
self.physical_keys.remove(&KeyCode::ShiftLeft);
}
}
Button::DPadUp | Button::DPadDown | Button::DPadLeft | Button::DPadRight => {
self.pad_focus_step(event_loop, button);
self.pad.menu.repeat = Some((button, Instant::now(), false));
}
// Bumpers switch creative tabs.
Button::LeftBumper | Button::RightBumper if self.screen == Screen::Creative => {
self.pad_creative_tab(event_loop, button == Button::RightBumper);
}
_ => {}
}
Ok(())
}
fn pad_focus_step(&mut self, event_loop: &ActiveEventLoop, button: Button) {
if self.pad.menu.pos.is_none() {
self.pad_take_pointer(event_loop);
return;
}
// With A held (a slider grabbed, a drag), the D-pad nudges instead.
if self.pad.menu.held[0] {
let (dx, dy) = match button {
Button::DPadLeft => (-2.0, 0.0),
Button::DPadRight => (2.0, 0.0),
Button::DPadUp => (0.0, -2.0),
_ => (0.0, 2.0),
};
let at = self.cursor;
self.pad_pointer_to(event_loop, (at.0 + dx, at.1 + dy));
return;
}
let from = self.cursor;
let targets = self.pad_targets();
if let Some(i) = gamepad::focus_step(from, button, &targets) {
self.pad_pointer_to(event_loop, targets[i]);
}
}
/// Click the next or previous creative tab (wrapping), as a mouse would.
fn pad_creative_tab(&mut self, event_loop: &ActiveEventLoop, next: bool) {
let Some(batch) = self.gui_scale() else {
return;
};
let count = self.creative_screen.tabs.len();
if count == 0 {
return;
}
let selected = self.creative_screen.selected;
let tab = if next {
(selected + 1) % count
} else {
(selected + count - 1) % count
};
let (ox, oy) = Self::creative_origin(&batch);
let (x, y) = Creative::tab_position(&self.creative_screen.tabs[tab]);
let back = self.pad.menu.pos;
self.pad_pointer_to(event_loop, (ox + x + 13.0, oy + y + 16.0));
self.pad_pointer_button(event_loop, false, true);
self.pad_pointer_button(event_loop, false, false);
if let Some(at) = back {
self.pad_pointer_to(event_loop, at);
}
}
/// Once per poll in a menu: the stick moves the cursor, the right stick
/// scrolls, a held D-pad repeats, and the OS pointer hides while the
/// pad's cursor shows.
pub(super) fn pad_menu_frame(&mut self, event_loop: &ActiveEventLoop) {
let now = Instant::now();
let seconds = self
.pad
.menu
.last_poll
.map_or(0.0, |t| now.duration_since(t).as_secs_f32().min(0.05));
self.pad.menu.last_poll = Some(now);
let in_menu = self.pad_in_menu() && self.settings.controller.enabled;
if !in_menu {
self.pad.menu.open_polls = 0;
self.pad.menu.pos = None;
self.pad.menu.repeat = None;
self.pad.menu.held = [false; 2];
self.pad_show_os_pointer(true);
return;
}
self.pad.menu.open_polls = self.pad.menu.open_polls.saturating_add(1);
// A real mouse move hands the pointer back.
if let Some(at) = self.pad.menu.pos
&& ((at.0 - self.cursor.0).abs() > 0.5 || (at.1 - self.cursor.1).abs() > 0.5)
{
self.pad.menu.pos = None;
self.pad.in_use = false;
}
// Focus lands on the menu as it opens when the pad was in use.
if self.pad.in_use && self.pad.menu.pos.is_none() && self.pad.menu.open_polls == 3 {
self.pad_take_pointer(event_loop);
}
let (move_deadzone, look_deadzone) = (
self.settings.controller.move_deadzone,
self.settings.controller.look_deadzone,
);
let state = self.pad.state;
let (dx, dy) = gamepad::cursor_delta(state.left, move_deadzone, seconds);
if dx != 0.0 || dy != 0.0 {
self.pad_take_pointer(event_loop);
let at = self.cursor;
self.pad_pointer_to(event_loop, (at.0 + dx, at.1 + dy));
self.pad.menu.moving = true;
} else if self.pad.menu.moving {
// Let go: settle onto a slot or button close by.
self.pad.menu.moving = false;
let targets = self.pad_targets();
if let Some(i) = gamepad::nearest(self.cursor, &targets, 10.0) {
self.pad_pointer_to(event_loop, targets[i]);
}
}
let scroll = gamepad::radial(state.right, look_deadzone);
let wheel = &mut self.pad.menu.wheel;
wheel[0] += scroll[0] * SCROLL_SPEED * seconds;
wheel[1] += scroll[1] * SCROLL_SPEED * seconds;
if scroll == [0.0, 0.0] {
*wheel = [0.0, 0.0];
}
let lines = [wheel[0].trunc(), wheel[1].trunc()];
if lines != [0.0, 0.0] {
wheel[0] -= lines[0];
wheel[1] -= lines[1];
// Stick right scrolls right: the wheel's x runs the other way.
self.pad_wheel(event_loop, -lines[0], lines[1]);
}
if let Some((button, since, repeating)) = self.pad.menu.repeat {
let wait = if repeating {
REPEAT_EVERY
} else {
REPEAT_DELAY
};
if now.duration_since(since).as_secs_f32() >= wait {
self.pad.menu.repeat = Some((button, now, true));
self.pad_focus_step(event_loop, button);
}
}
self.pad_show_os_pointer(self.pad.menu.pos.is_none());
}
fn pad_show_os_pointer(&mut self, show: bool) {
if self.pad.menu.os_hidden != show {
return;
}
self.pad.menu.os_hidden = !show;
if let Some(window) = &self.window {
window.set_cursor_visible(show && !self.captured);
}
}
/// The pad's cursor, over everything else.
pub(super) fn draw_pad_cursor(&self, batch: &mut HudBatch) {
let Some((x, y)) = self.pad.menu.pos else {
return;
};
if !self.pad_in_menu() {
return;
}
// An arrow, outlined, pointing up-left at (x, y).
let atlas = &self.res.atlas;
let (x, y) = (x.floor(), y.floor());
const ROWS: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 4, 2, 1];
for (i, &w) in ROWS.iter().enumerate() {
let row = y + i as f32;
batch.fill(
atlas,
x - 1.0,
row,
f32::from(w) + 2.0,
1.0,
rgba(0, 0, 0, 255),
);
}
batch.fill(atlas, x - 1.0, y + 10.0, 2.0, 1.0, rgba(0, 0, 0, 255));
for (i, &w) in ROWS.iter().enumerate().skip(1).take(8) {
let row = y + i as f32;
batch.fill(
atlas,
x,
row,
f32::from(w) - 1.0,
1.0,
rgba(255, 255, 255, 255),
);
}
}
}
+1 -1
View File
@@ -304,7 +304,7 @@ impl Game<'_> {
}
}
/// A saved mob and, under `Passengers`, the mobs riding it.
fn load_mob(&mut self, tag: Tag, mount: Option<u32>) -> Option<u32> {
pub(super) fn load_mob(&mut self, tag: Tag, mount: Option<u32>) -> Option<u32> {
self.next_entity += 1;
let uuid = entity_nbt::uuid(&tag);
// Structure entities placed with finalizeEntities.
+5 -1
View File
@@ -1573,6 +1573,7 @@ impl Game<'_> {
let mut player = PlayerMotion::new(self.motion, position)?;
player.velocity = delta;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.eye = 1.62;
self.previous_eye = 1.62;
@@ -1637,6 +1638,7 @@ impl Game<'_> {
r.loaded_sent = true;
}
}
let stick = self.pad_move();
let Some(player) = self.player.as_mut() else {
return Ok(());
};
@@ -1651,7 +1653,9 @@ impl Game<'_> {
jump: held(KeyCode::Space),
shift: held(KeyCode::ShiftLeft),
sprint: held(KeyCode::ControlLeft),
};
analog: None,
}
.with_stick(stick.filter(|_| playing));
let input = u8::from(keys.forward)
| u8::from(keys.backward) << 1
| u8::from(keys.left) << 2
+1 -1
View File
@@ -33,7 +33,7 @@ impl Game<'_> {
self.right = false;
self.capture(false);
}
fn close_sign_editor(&mut self) {
pub(super) fn close_sign_editor(&mut self) {
if let Some(edit) = self.sign_edit.take() {
self.world
.modified
+414
View File
@@ -0,0 +1,414 @@
//! Monster spawners in the game: `SpawnerBlockEntity.serverTick` and
//! `clientTick` for every spawner (`mobs::spawner`), the mobs they add, a
//! spawn egg used on one (`SpawnEggItem.useOn`), their events and the mob
//! spinning inside (`SpawnerRenderer`).
use super::Game;
use horizon_client::{
Result,
containers::BlockEntity,
mobs::{
Mob, Who,
spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerSpawn},
spawning,
},
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_world::nbt::Tag;
use std::collections::{HashMap, HashSet};
type Pos = (i32, i32, i32);
/// What a spawner tick decided to add, created once the level is free.
enum Planned {
/// `finalizeSpawn` ran on a fresh mob.
Finalized(Mob),
/// A mob loaded from the spawn data (with its passengers).
Loaded(Tag),
}
/// What the spawner code keeps between ticks.
#[derive(Default)]
pub(super) struct SpawnerState {
/// Every entity type id (`EntityType.byString`), read once.
entity_types: Option<HashSet<String>>,
/// The mob shown in each spawner and the id it was made for
/// (`getOrCreateDisplayEntity`).
displays: HashMap<Pos, (String, Mob)>,
}
impl Game<'_> {
/// `EntityType.byString`: the type is in the registry.
pub(super) fn entity_type_exists(&self, id: &str) -> bool {
self.spawners
.entity_types
.as_ref()
.is_some_and(|t| t.contains(id))
}
fn load_entity_types(&mut self) {
if self.spawners.entity_types.is_some() {
return;
}
let path = self.options.resources.join("entity-types.json");
let types = std::fs::read(path)
.ok()
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
.and_then(|v| {
v.as_object().map(|o| {
o.keys()
.map(|k| horizon_client::command::args::normalize(k))
.collect()
})
})
.unwrap_or_default();
self.spawners.entity_types = Some(types);
}
/// Every spawner's server tick, then its client tick.
pub(super) fn tick_spawners(&mut self) -> Result<()> {
self.load_entity_types();
let keys: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Spawner(_)))
.map(|(k, _)| *k)
.collect();
for key in &keys {
let state = self.world.block(key.0, key.1, key.2);
if &*self.res.facts.get(state).name != "minecraft:spawner" {
continue;
}
let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.remove(key)
else {
continue;
};
let result = self.server_tick_spawner(*key, &mut spawner);
self.world
.block_entities
.insert(*key, BlockEntity::Spawner(spawner));
result?;
}
for key in keys {
self.client_tick_spawner(key);
}
let entities = &self.world.block_entities;
self.spawners
.displays
.retain(|k, _| matches!(entities.get(k), Some(BlockEntity::Spawner(_))));
Ok(())
}
fn server_tick_spawner(&mut self, key: Pos, spawner: &mut Spawner) -> Result<()> {
let pos = [key.0, key.1, key.2];
let mut random = std::mem::replace(
&mut self.world.random,
horizon_core::random::LegacyRandom::new(0),
);
let mut events = Vec::new();
let mut planned: Vec<Planned> = Vec::new();
{
let level = self.natural_level();
let mut spawn = |l: &super::natural_spawning::GameLevel, r: &SpawnerSpawn| {
l.game.plan_spawner_mob(l, r, &mut planned)
};
spawner.server_tick(&level, &mut random, pos, &mut spawn, &mut events);
}
self.world.random = random;
// Provisional ids (counting down from u32::MAX) become the mobs' ids.
let mut ids = HashMap::new();
for (i, plan) in planned.into_iter().enumerate() {
let provisional = u32::MAX - i as u32;
let id = match plan {
Planned::Finalized(mut mob) => {
self.next_entity += 1;
mob.id = self.next_entity;
let id = mob.id;
self.mobs.push(mob);
self.enchant_spawn_equipment(id);
self.spawn_jockeys(id, true);
Some(id)
}
Planned::Loaded(tag) => self.load_mob(tag, None),
};
if let Some(id) = id {
ids.insert(provisional, id);
}
}
self.apply_spawner_events(key, events, &ids)
}
/// The spawner's `loadEntityRecursive` and `tryAddFreshEntityWithPassengers`:
/// the mob it will add (created after the tick) and its box.
fn plan_spawner_mob(
&self,
l: &super::natural_spawning::GameLevel,
r: &SpawnerSpawn,
planned: &mut Vec<Planned>,
) -> Option<SpawnerAdded> {
let kind = self.res.mob_types.get(r.id)?.clone();
let [x, y, z] = r.position;
let at = Vec3::new(x, y, z);
let bounds = if r.finalize {
let mut mob = Mob::new(0, kind, at, r.yaw);
let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32);
let difficulty = self.local_difficulty(r.position);
spawning::finalize(&mut mob, &facts, &difficulty);
horizon_client::mobs::raider::finalize(
&mut mob,
horizon_client::mobs::raider::Reason::Other,
);
// Shulker.finalizeSpawn faces it south.
if mob.species() == horizon_client::mobs::Species::Shulker {
mob.yaw = 0.0;
mob.previous_yaw = 0.0;
mob.body_yaw = 0.0;
mob.previous_body_yaw = 0.0;
mob.head_yaw = 0.0;
mob.previous_head_yaw = 0.0;
}
let bounds = mob.bounds();
planned.push(Planned::Finalized(mob));
bounds
} else {
// A UUID already in the level is refused.
let mut tag = r.entity.clone();
if let Some(uuid) = horizon_client::entity_nbt::uuid(&Tag::Compound(tag.clone()))
&& self.persist.uuids.values().any(|u| *u == uuid)
{
return None;
}
let double = |v: f64| Tag::Double(v.to_bits());
tag.insert(
"Pos".into(),
Tag::List(vec![double(x), double(y), double(z)]),
);
tag.insert(
"Rotation".into(),
Tag::List(vec![
Tag::Float(r.yaw.to_bits()),
Tag::Float(0f32.to_bits()),
]),
);
let tag = Tag::Compound(tag);
let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, 0)?;
let bounds = mob.bounds();
planned.push(Planned::Loaded(tag));
bounds
};
l.pending.borrow_mut().push(bounds);
l.pending_ids.borrow_mut().push((r.id.to_owned(), bounds));
Some(SpawnerAdded {
id: u32::MAX - (planned.len() as u32 - 1),
bounds,
mob: true,
})
}
/// What a spawner's tick or a spawn egg did, shown and sent.
fn apply_spawner_events(
&mut self,
key: Pos,
events: Vec<SpawnerEvent>,
ids: &HashMap<u32, u32>,
) -> Result<()> {
let pos = [key.0, key.1, key.2];
for event in events {
match event {
SpawnerEvent::BlockUpdated => self.spawner_block_updated(key),
SpawnerEvent::BlockEvent(id) => {
self.lan_block_event(pos, id, 0);
// The client copy's onEventTriggered.
if let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get_mut(&key) {
s.client_event(id);
}
}
SpawnerEvent::LevelEvent(id) => self.level_event_at(id, pos, 0),
SpawnerEvent::EntityPlace(mob, at) => {
let who = ids.get(&mob).map(|id| Who::Mob(*id));
self.post_block_game_event("minecraft:entity_place", at, who, None);
}
SpawnerEvent::SpawnAnim(mob) => {
if let Some(id) = ids.get(&mob) {
self.mob_poof(*id);
}
}
}
}
Ok(())
}
/// `sendBlockUpdated`: the clients load the new update tag (the client
/// copy's delay follows it, its display mob is made again).
fn spawner_block_updated(&mut self, key: Pos) {
if let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get_mut(&key) {
s.client_loaded();
}
self.spawners.displays.remove(&key);
if let Some(log) = self.world.block_log.as_mut() {
log.push(key);
}
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
}
/// `LivingEntity.makePoofParticles` (entity event 20) for a mob.
fn mob_poof(&mut self, id: u32) {
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
return;
};
let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height()));
self.lan_entity_event(id as i32, 20, [at.x, at.y, at.z]);
let options = ParticleOptions::simple(ParticleType::Poof);
for _ in 0..20 {
let r = self.particles.level_random();
let xa = r.next_gaussian() * 0.02;
let ya = r.next_gaussian() * 0.02;
let za = r.next_gaussian() * 0.02;
let x = at.x + w * (2.0 * r.next_double() - 1.0) - xa * 10.0;
let y = at.y + h * r.next_double() - ya * 10.0;
let z = at.z + w * (2.0 * r.next_double() - 1.0) - za * 10.0;
self.particles.add(&options, [x, y, z], [xa, ya, za]);
}
}
/// `LevelEventHandler` 2004: twenty smoke and flame pairs around the spawner.
pub(super) fn spawner_burst(&mut self, pos: [i32; 3]) {
let (smoke, flame) = (
ParticleOptions::simple(ParticleType::Smoke),
ParticleOptions::simple(ParticleType::Flame),
);
for _ in 0..20 {
let r = self.particles.level_random();
let x = f64::from(pos[0]) + 0.5 + (r.next_double() - 0.5) * 2.0;
let y = f64::from(pos[1]) + 0.5 + (r.next_double() - 0.5) * 2.0;
let z = f64::from(pos[2]) + 0.5 + (r.next_double() - 0.5) * 2.0;
self.particles.add(&smoke, [x, y, z], [0.0; 3]);
self.particles.add(&flame, [x, y, z], [0.0; 3]);
}
}
/// The client copy's tick: particles and the spin while a player is near.
fn client_tick_spawner(&mut self, key: Pos) {
let near = {
let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get(&key) else {
return;
};
let range = f64::from(s.required_player_range);
let center = [
f64::from(key.0) + 0.5,
f64::from(key.1) + 0.5,
f64::from(key.2) + 0.5,
];
self.player.as_ref().is_some_and(|p| {
let d = (p.position.x - center[0]).powi(2)
+ (p.position.y - center[1]).powi(2)
+ (p.position.z - center[2]).powi(2);
!p.health.dead_or_dying() && !self.spectator() && (range < 0.0 || d < range * range)
})
};
let display = self.update_spawner_display(key);
let pos = [key.0, key.1, key.2];
let random = self.particles.level_random();
let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get_mut(&key) else {
return;
};
if let Some(p) = s.client_tick(near, display, random, pos) {
self.particles
.add(&ParticleOptions::simple(ParticleType::Smoke), p, [0.0; 3]);
self.particles
.add(&ParticleOptions::simple(ParticleType::Flame), p, [0.0; 3]);
}
}
/// `getOrCreateDisplayEntity`: the mob shown in the spawner, made again
/// when its type changes. False when there is none.
fn update_spawner_display(&mut self, key: Pos) -> bool {
let Some(kind) = self.spawner_display_kind(key) else {
self.spawners.displays.remove(&key);
return false;
};
if self
.spawners
.displays
.get(&key)
.is_none_or(|(k, _)| *k != kind)
{
let Some(t) = self.res.mob_types.get(&kind).cloned() else {
return false;
};
let mob = Mob::new(u32::MAX, t, Vec3::ZERO, 0.0);
self.spawners.displays.insert(key, (kind, mob));
}
true
}
/// The type of the mob a spawner shows: its next data's id, when the game
/// knows the mob.
fn spawner_display_kind(&self, key: Pos) -> Option<String> {
let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get(&key) else {
return None;
};
let id = s.next_data()?.id()?;
self.res.mob_types.contains_key(&id).then_some(id)
}
/// `SpawnEggItem.useOn` on a spawner: the egg sets its mob. None when the
/// clicked block has no spawner.
pub(super) fn use_spawn_egg_on_spawner(&mut self, pos: [i32; 3], kind: &str) -> Option<bool> {
let key = (pos[0], pos[1], pos[2]);
if !matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Spawner(_))
) {
return None;
}
if !self.ui.rules.bool("spawner_blocks_work") {
self.system_message(horizon_client::text::Text::translate(
"advMode.notEnabled.spawner",
&[],
));
return Some(false);
}
let mut events = Vec::new();
let mut random = std::mem::replace(
&mut self.world.random,
horizon_core::random::LegacyRandom::new(0),
);
if let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get_mut(&key) {
s.set_entity_id(kind, &mut random, &mut events);
}
self.world.random = random;
let _ = self.apply_spawner_events(key, events, &HashMap::new());
// sendBlockUpdated(3) and the player's block_change game event.
self.spawner_block_updated(key);
self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None);
Some(true)
}
/// `SpawnerRenderer`: the next mob of every spawner near the camera,
/// small and turning.
pub(super) fn spawner_geometry(
&self,
camera: glam::DVec3,
alpha: f64,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
let atlas = &self.res.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
for (key, (_, mob)) in &self.spawners.displays {
let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
if at.distance_squared(camera) >= 64.0 * 64.0 {
continue;
}
let Some(BlockEntity::Spawner(s)) = self.world.block_entities.get(key) else {
continue;
};
let (spin, scale) = s.display_pose(alpha as f32, mob.width(), mob.height());
let origin = glam::Mat4::from_translation(
(at - camera).as_vec3() + glam::Vec3::new(0.5, 0.4, 0.5),
) * glam::Mat4::from_rotation_y(spin.to_radians())
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.2, 0.0))
* glam::Mat4::from_rotation_x((-30.0_f32).to_radians())
* glam::Mat4::from_scale(glam::Vec3::splat(scale));
let light = self.world.light(key.0, key.1, key.2);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
horizon_client::mobs::render::render_posed(
mob,
alpha as f32,
origin,
&lookup,
packed,
&self.res.mob_data,
out,
);
}
}
}
+1
View File
@@ -71,5 +71,6 @@ impl Game<'_> {
height,
30,
);
self.pad_rumble(horizon_client::gamepad::Rumble::Totem);
}
}
+902
View File
@@ -0,0 +1,902 @@
//! Controllers: Horizon's own feature (vanilla 26.3 has no gamepad input).
//! The default layout is Bedrock Edition's; 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};
pub const FILE: &str = "horizon-controller.txt";
/// A button by its position on the pad (gilrs' and SDL's layout): `South`
/// is Xbox A, PlayStation ✕, Nintendo B.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Button {
South,
East,
West,
North,
LeftBumper,
RightBumper,
LeftTrigger,
RightTrigger,
Select,
Start,
LeftStick,
RightStick,
DPadUp,
DPadDown,
DPadLeft,
DPadRight,
}
impl Button {
pub const ALL: [Button; 16] = [
Button::South,
Button::East,
Button::West,
Button::North,
Button::LeftBumper,
Button::RightBumper,
Button::LeftTrigger,
Button::RightTrigger,
Button::Select,
Button::Start,
Button::LeftStick,
Button::RightStick,
Button::DPadUp,
Button::DPadDown,
Button::DPadLeft,
Button::DPadRight,
];
/// The name in `horizon-controller.txt` and `horizon-ctl pad`.
pub fn name(self) -> &'static str {
match self {
Button::South => "south",
Button::East => "east",
Button::West => "west",
Button::North => "north",
Button::LeftBumper => "lb",
Button::RightBumper => "rb",
Button::LeftTrigger => "lt",
Button::RightTrigger => "rt",
Button::Select => "select",
Button::Start => "start",
Button::LeftStick => "ls",
Button::RightStick => "rs",
Button::DPadUp => "up",
Button::DPadDown => "down",
Button::DPadLeft => "left",
Button::DPadRight => "right",
}
}
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|b| b.name() == name)
}
fn bit(self) -> u32 {
1 << self as u32
}
/// What is printed on the button for a pad family (`Auto` reads as Xbox).
pub fn label(self, style: GlyphStyle) -> &'static str {
let i = self as usize;
match style {
GlyphStyle::PlayStation => [
"×", "○", "□", "△", "L1", "R1", "L2", "R2", "Create", "Options", "L3", "R3", "↑",
"↓", "←", "→",
][i],
GlyphStyle::Nintendo => [
"B", "A", "Y", "X", "L", "R", "ZL", "ZR", "−", "+", "LS", "RS", "↑", "↓", "←", "→",
][i],
GlyphStyle::Xbox | GlyphStyle::Auto => [
"A", "B", "X", "Y", "LB", "RB", "LT", "RT", "View", "Menu", "LS", "RS", "↑", "↓",
"←", "→",
][i],
}
}
/// The glyph's colour (RGB): face buttons in their family's colours,
/// the rest white.
pub fn color(self, style: GlyphStyle) -> [u8; 3] {
let face = match self {
Button::South => 0,
Button::East => 1,
Button::West => 2,
Button::North => 3,
_ => return [255, 255, 255],
};
match style {
GlyphStyle::PlayStation => [
[124, 178, 232],
[235, 110, 110],
[222, 145, 205],
[92, 205, 170],
][face],
GlyphStyle::Nintendo => [255, 255, 255],
GlyphStyle::Xbox | GlyphStyle::Auto => [
[110, 200, 90],
[235, 90, 80],
[80, 150, 240],
[240, 200, 60],
][face],
}
}
}
/// A pad's inputs at one moment. Sticks are `[x, y]` with right and up
/// positive; triggers run 0..1.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PadState {
/// Digital buttons as a bit set (triggers are in `triggers`).
pub buttons: u32,
pub left: [f32; 2],
pub right: [f32; 2],
pub triggers: [f32; 2],
}
impl PadState {
pub fn set(&mut self, button: Button, down: bool) {
if down {
self.buttons |= button.bit();
} else {
self.buttons &= !button.bit();
}
}
pub fn held(&self, button: Button) -> bool {
self.buttons & button.bit() != 0
}
/// Two sources at once (a real pad and `horizon-ctl pad`): buttons held on
/// either, sticks and triggers added.
pub fn merge(&self, other: &PadState) -> PadState {
let add = |a: [f32; 2], b: [f32; 2]| {
[
(a[0] + b[0]).clamp(-1.0, 1.0),
(a[1] + b[1]).clamp(-1.0, 1.0),
]
};
PadState {
buttons: self.buttons | other.buttons,
left: add(self.left, other.left),
right: add(self.right, other.right),
triggers: [
(self.triggers[0] + other.triggers[0]).clamp(0.0, 1.0),
(self.triggers[1] + other.triggers[1]).clamp(0.0, 1.0),
],
}
}
/// Anything pushed past the deadzones (the pad is in use).
pub fn active(&self, settings: &PadSettings) -> bool {
self.buttons != 0
|| length(self.left) > settings.move_deadzone
|| length(self.right) > settings.look_deadzone
|| self
.triggers
.iter()
.any(|t| *t >= settings.trigger_threshold)
}
}
/// Button presses and releases between successive states. Triggers count as
/// buttons past `threshold`, with a little hysteresis so a trigger resting
/// near the threshold doesn't chatter.
#[derive(Clone, Debug, Default)]
pub struct Edges {
held: u32,
}
impl Edges {
pub fn update(&mut self, state: &PadState, threshold: f32) -> Vec<(Button, bool)> {
let mut now = state.buttons;
for (trigger, button) in [(0, Button::LeftTrigger), (1, Button::RightTrigger)] {
let was = self.held & button.bit() != 0;
let value = state.triggers[trigger];
let on = if was {
value >= (threshold - 0.1).max(0.05)
} else {
value >= threshold
};
if on {
now |= button.bit();
} else {
now &= !button.bit();
}
}
let changed = now ^ self.held;
self.held = now;
Button::ALL
.into_iter()
.filter(|b| changed & b.bit() != 0)
.map(|b| (b, now & b.bit() != 0))
.collect()
}
/// Release everything (the pad was unplugged or turned off).
pub fn release_all(&mut self) -> Vec<(Button, bool)> {
let held = std::mem::take(&mut self.held);
Button::ALL
.into_iter()
.filter(|b| held & b.bit() != 0)
.map(|b| (b, false))
.collect()
}
pub fn is_held(&self, button: Button) -> bool {
self.held & button.bit() != 0
}
}
/// Horizon's pad-only actions (no vanilla key mapping).
pub const HOTBAR_PREVIOUS: &str = "pad.hotbarPrevious";
pub const HOTBAR_NEXT: &str = "pad.hotbarNext";
/// Bindable actions and their default buttons: vanilla key mappings (the
/// game acts as their default key) and Horizon's pad-only actions. Start is
/// always pause / back and isn't listed.
pub const ACTIONS: &[(&str, Option<Button>)] = &[
("key.jump", Some(Button::South)),
("key.drop", Some(Button::East)),
("key.swapOffhand", Some(Button::West)),
("key.inventory", Some(Button::North)),
(HOTBAR_PREVIOUS, Some(Button::LeftBumper)),
(HOTBAR_NEXT, Some(Button::RightBumper)),
("key.use", Some(Button::LeftTrigger)),
("key.attack", Some(Button::RightTrigger)),
("key.sprint", Some(Button::LeftStick)),
("key.sneak", Some(Button::RightStick)),
("key.togglePerspective", Some(Button::DPadUp)),
("key.pickItem", Some(Button::DPadLeft)),
("key.chat", Some(Button::DPadRight)),
("key.advancements", Some(Button::DPadDown)),
("key.playerlist", Some(Button::Select)),
("key.command", None),
("key.screenshot", None),
("key.toggleGui", None),
("key.smoothCamera", None),
];
/// An action's name in the binds list: vanilla's translation key, or
/// Horizon's own English for the pad-only actions.
pub fn action_caption(action: &str) -> &str {
match action {
HOTBAR_PREVIOUS => "Hotbar: Previous Slot",
HOTBAR_NEXT => "Hotbar: Next Slot",
other => other,
}
}
/// Which button pictures prompts use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum GlyphStyle {
/// From the pad's maker.
#[default]
Auto,
Xbox,
PlayStation,
Nintendo,
}
impl GlyphStyle {
pub fn name(self) -> &'static str {
match self {
GlyphStyle::Auto => "auto",
GlyphStyle::Xbox => "xbox",
GlyphStyle::PlayStation => "playstation",
GlyphStyle::Nintendo => "nintendo",
}
}
pub fn parse(name: &str) -> Self {
match name {
"xbox" => GlyphStyle::Xbox,
"playstation" => GlyphStyle::PlayStation,
"nintendo" => GlyphStyle::Nintendo,
_ => GlyphStyle::Auto,
}
}
/// The style the player chose, else the connected pad's.
pub fn resolve(self, detected: GlyphStyle) -> GlyphStyle {
match self {
GlyphStyle::Auto => match detected {
GlyphStyle::Auto => GlyphStyle::Xbox,
d => d,
},
chosen => chosen,
}
}
pub const ALL: [GlyphStyle; 4] = [
GlyphStyle::Auto,
GlyphStyle::Xbox,
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,
_ => GlyphStyle::Xbox,
}
}
}
/// The controller settings (`horizon-controller.txt`).
#[derive(Clone, Debug, PartialEq)]
pub struct PadSettings {
pub enabled: bool,
pub vibration: bool,
/// 0..1; 0.5 is the default speed, 1 twice that.
pub look_sensitivity: f32,
pub invert_x: bool,
pub invert_y: bool,
pub move_deadzone: f32,
pub look_deadzone: f32,
pub trigger_threshold: f32,
/// The sneak button flips sneaking (Bedrock's default) instead of
/// holding it, unless vanilla's toggle crouch is on already.
pub toggle_sneak: bool,
pub glyphs: GlyphStyle,
/// Action name -> button, `None` for unbound; missing means the default.
bindings: BTreeMap<&'static str, Option<Button>>,
}
impl Default for PadSettings {
fn default() -> Self {
Self {
enabled: true,
vibration: true,
look_sensitivity: 0.5,
invert_x: false,
invert_y: false,
move_deadzone: 0.15,
look_deadzone: 0.12,
trigger_threshold: 0.4,
toggle_sneak: true,
glyphs: GlyphStyle::Auto,
bindings: BTreeMap::new(),
}
}
}
fn bool_text(v: bool) -> &'static str {
if v { "true" } else { "false" }
}
impl PadSettings {
pub fn load(dir: &Path) -> Self {
fs::read_to_string(dir.join(FILE))
.map(|t| Self::parse(&t))
.unwrap_or_default()
}
/// Written once something differs from the defaults, so players who
/// never touch a controller get no new file.
pub fn save(&self, dir: &Path) {
let path = dir.join(FILE);
if *self != Self::default() || path.exists() {
let _ = fs::write(path, self.serialize());
}
}
pub fn parse(text: &str) -> Self {
let mut s = Self::default();
for line in text.lines() {
let Some((key, value)) = line.split_once(':') else {
continue;
};
let value = value.trim();
let flag = |d: bool| match value {
"true" => true,
"false" => false,
_ => d,
};
let unit = |d: f32| {
value
.parse::<f32>()
.ok()
.filter(|v| v.is_finite())
.map_or(d, |v| v.clamp(0.0, 1.0))
};
match key.trim() {
"enabled" => s.enabled = flag(s.enabled),
"vibration" => s.vibration = flag(s.vibration),
"lookSensitivity" => s.look_sensitivity = unit(s.look_sensitivity),
"invertX" => s.invert_x = flag(s.invert_x),
"invertY" => s.invert_y = flag(s.invert_y),
"moveDeadzone" => s.move_deadzone = unit(s.move_deadzone).min(0.9),
"lookDeadzone" => s.look_deadzone = unit(s.look_deadzone).min(0.9),
"triggerThreshold" => {
s.trigger_threshold = unit(s.trigger_threshold).clamp(0.1, 0.9)
}
"toggleSneak" => s.toggle_sneak = flag(s.toggle_sneak),
"glyphs" => s.glyphs = GlyphStyle::parse(value),
other => {
if let Some(action) = other.strip_prefix("bind_") {
let button = if value == "none" {
Some(None)
} else {
Button::parse(value).map(Some)
};
if let Some(button) = button {
s.bind(action, button);
}
}
}
}
}
s
}
pub fn serialize(&self) -> String {
let mut text = format!(
"enabled:{}\nvibration:{}\nlookSensitivity:{}\ninvertX:{}\ninvertY:{}\nmoveDeadzone:{}\nlookDeadzone:{}\ntriggerThreshold:{}\ntoggleSneak:{}\nglyphs:{}\n",
bool_text(self.enabled),
bool_text(self.vibration),
self.look_sensitivity,
bool_text(self.invert_x),
bool_text(self.invert_y),
self.move_deadzone,
self.look_deadzone,
self.trigger_threshold,
bool_text(self.toggle_sneak),
self.glyphs.name(),
);
for (action, button) in &self.bindings {
text.push_str(&format!(
"bind_{action}:{}\n",
button.map_or("none", Button::name)
));
}
text
}
pub fn default_of(action: &str) -> Option<Button> {
ACTIONS.iter().find(|a| a.0 == action).and_then(|a| a.1)
}
/// The button an action is bound to.
pub fn binding(&self, action: &str) -> Option<Button> {
match self.bindings.get(action) {
Some(button) => *button,
None => Self::default_of(action),
}
}
/// Bind an action (`None` unbinds); unknown actions are ignored.
pub fn bind(&mut self, action: &str, button: Option<Button>) {
let Some((name, default)) = ACTIONS.iter().find(|a| a.0 == action) else {
return;
};
if button == *default {
self.bindings.remove(name);
} else {
self.bindings.insert(name, button);
}
}
pub fn reset_bindings(&mut self) {
self.bindings.clear();
}
/// Other actions on the same button (marked in the binds list).
pub fn conflicts(&self, action: &str) -> bool {
self.binding(action)
.is_some_and(|b| self.actions_of(b).iter().any(|a| *a != action))
}
pub fn is_default(&self, action: &str) -> bool {
!self.bindings.contains_key(action)
}
/// The actions a button triggers, in `ACTIONS` order.
pub fn actions_of(&self, button: Button) -> Vec<&'static str> {
ACTIONS
.iter()
.map(|a| a.0)
.filter(|a| self.binding(a) == Some(button))
.collect()
}
}
fn length(v: [f32; 2]) -> f32 {
(v[0] * v[0] + v[1] * v[1]).sqrt()
}
/// 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.
pub fn radial(v: [f32; 2], deadzone: f32) -> [f32; 2] {
let len = length(v);
if !len.is_finite() || len <= deadzone || len == 0.0 {
return [0.0, 0.0];
}
let scaled = ((len - deadzone) / (1.0 - deadzone)).min(1.0);
[v[0] / len * scaled, v[1] / len * scaled]
}
/// The left stick as the player's move vector, in `KeyboardInput`'s layout
/// (`[left, forward]`, length at most 1); `None` inside the deadzone.
pub fn move_vector(stick: [f32; 2], deadzone: f32) -> Option<[f32; 2]> {
let v = radial(stick, deadzone);
(v != [0.0, 0.0]).then_some([-v[0], v[1]])
}
/// Degrees per second at full tilt and the default sensitivity.
pub const YAW_SPEED: f32 = 200.0;
pub const PITCH_SPEED: f32 = 140.0;
/// The view turn from the right stick over `seconds`: `(yaw, pitch)` in
/// degrees, pitch positive looking down as in `Entity.turn`. A squared
/// curve keeps small tilts precise; a spyglass slows it down.
pub fn look_delta(
stick: [f32; 2],
settings: &PadSettings,
seconds: f32,
scoping: bool,
) -> (f32, f32) {
let v = radial(stick, settings.look_deadzone);
let len = length(v);
if len == 0.0 {
return (0.0, 0.0);
}
// The vector already has length `len`: scaling by it squares the tilt.
let curve = len;
let speed = settings.look_sensitivity * 2.0 * if scoping { 0.25 } else { 1.0 };
let x = v[0] * curve * if settings.invert_x { -1.0 } else { 1.0 };
let y = v[1] * curve * if settings.invert_y { -1.0 } else { 1.0 };
(
x * YAW_SPEED * speed * seconds,
-y * PITCH_SPEED * speed * seconds,
)
}
/// 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;
/// How far the menu cursor moves for a stick over `seconds`, in GUI pixels
/// (`y` down): a squared curve, so a light touch lands on a slot.
pub fn cursor_delta(stick: [f32; 2], deadzone: f32, seconds: f32) -> (f32, f32) {
let v = radial(stick, deadzone);
let len = length(v);
if len == 0.0 {
return (0.0, 0.0);
}
let speed = (CURSOR_SPEED * len + 30.0) * seconds;
(v[0] * speed, -v[1] * speed)
}
/// The target a D-pad press moves focus to: the nearest one inside a cone
/// around the direction, weighing sideways distance double.
pub fn focus_step(from: (f32, f32), button: Button, targets: &[(f32, f32)]) -> Option<usize> {
let (dx, dy) = match button {
Button::DPadUp => (0.0, -1.0),
Button::DPadDown => (0.0, 1.0),
Button::DPadLeft => (-1.0, 0.0),
Button::DPadRight => (1.0, 0.0),
_ => return None,
};
targets
.iter()
.enumerate()
.filter_map(|(i, t)| {
let (x, y) = (t.0 - from.0, t.1 - from.1);
let along = x * dx + y * dy;
let across = (x * dy - y * dx).abs();
(along > 2.0 && across <= along * 2.0).then_some((i, along + 2.0 * across))
})
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i)
}
/// The target within `radius` of `at`, nearest first (the cursor settles
/// onto a slot or button when the stick lets go).
pub fn nearest(at: (f32, f32), targets: &[(f32, f32)], radius: f32) -> Option<usize> {
targets
.iter()
.enumerate()
.map(|(i, t)| (i, (t.0 - at.0).hypot(t.1 - at.1)))
.filter(|(_, d)| *d <= radius)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i)
}
/// Damage taken, from the player's health between polls. The baseline is
/// forgotten whenever there is no player or a new player entity replaces
/// the old one (a world loaded, a respawn, a server joined, a dimension
/// change), so arriving with less health than before isn't damage.
#[derive(Clone, Copy, Debug, Default)]
pub struct HealthWatch {
last: Option<f32>,
}
impl HealthWatch {
/// The health now (`None` without a player); returns the damage taken
/// since the last call.
pub fn observe(&mut self, health: Option<f32>) -> Option<f32> {
let before = std::mem::replace(&mut self.last, health);
match (before, health) {
(Some(before), Some(now)) if now < before => Some(before - now),
_ => None,
}
}
pub fn forget(&mut self) {
self.last = None;
}
}
/// What makes the pad vibrate (Bedrock-like: short, light pulses).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Rumble {
/// The player lost this much health.
Hurt(f32),
BlockBroken,
/// An explosion this far away (blocks) with this power.
Explosion {
distance: f64,
radius: f32,
},
Totem,
}
/// A vibration: the heavy (low-frequency) and light motors, 0..1, and how
/// long it lasts.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pulse {
pub strong: f32,
pub weak: f32,
pub millis: u32,
}
impl Rumble {
pub fn name(self) -> &'static str {
match self {
Rumble::Hurt(_) => "hurt",
Rumble::BlockBroken => "block",
Rumble::Explosion { .. } => "explosion",
Rumble::Totem => "totem",
}
}
/// The pulse, or `None` when it is too faint to feel.
pub fn pulse(self) -> Option<Pulse> {
match self {
Rumble::Hurt(amount) if amount > 0.0 => Some(Pulse {
strong: (0.2 + 0.06 * amount).min(0.8),
weak: 0.3,
millis: (150.0 + 20.0 * amount).min(400.0) as u32,
}),
Rumble::Hurt(_) => None,
Rumble::BlockBroken => Some(Pulse {
strong: 0.0,
weak: 0.25,
millis: 60,
}),
Rumble::Explosion { distance, radius } => {
// Felt up to four times the blast radius, fading with distance.
let reach = f64::from(radius.max(1.0)) * 4.0;
let near = (1.0 - distance / reach) as f32;
(near > 0.05).then_some(Pulse {
strong: 0.9 * near,
weak: 0.6 * near,
millis: 350,
})
}
Rumble::Totem => Some(Pulse {
strong: 0.7,
weak: 0.7,
millis: 500,
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_follow_bedrock() {
let s = PadSettings::default();
assert_eq!(s.actions_of(Button::South), ["key.jump"]);
assert_eq!(s.actions_of(Button::RightTrigger), ["key.attack"]);
assert_eq!(s.actions_of(Button::LeftTrigger), ["key.use"]);
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.
for (action, _) in ACTIONS {
assert!(
action.starts_with("pad.")
|| crate::keybinds::MAPPINGS.iter().any(|m| m.0 == *action),
"{action}"
);
}
}
#[test]
fn settings_round_trip_and_store_only_changes() {
let mut s = PadSettings::default();
assert!(!s.serialize().contains("bind_"));
s.bind("key.jump", Some(Button::East));
s.bind("key.drop", None);
s.bind("key.sneak", Some(Button::RightStick));
s.invert_y = true;
s.look_sensitivity = 0.75;
s.glyphs = GlyphStyle::PlayStation;
let text = s.serialize();
assert!(text.contains("bind_key.jump:east\n"));
assert!(text.contains("bind_key.drop:none\n"));
assert!(!text.contains("key.sneak"));
let back = PadSettings::parse(&text);
assert_eq!(back, s);
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");
assert_eq!(odd, PadSettings::default());
}
#[test]
fn radial_deadzone_rescales() {
assert_eq!(radial([0.1, 0.05], 0.15), [0.0, 0.0]);
let full = radial([1.0, 0.0], 0.15);
assert!((full[0] - 1.0).abs() < 1e-6);
let half = radial([0.0, 0.575], 0.15);
assert!((half[1] - 0.5).abs() < 1e-6);
// A worn stick reporting more than 1 still caps at 1.
let over = radial([1.0, 1.0], 0.15);
assert!((length(over) - 1.0).abs() < 1e-6);
assert_eq!(move_vector([0.0, 0.0], 0.15), None);
let m = move_vector([1.0, 0.0], 0.15).unwrap();
assert!(m[0] < -0.99 && m[1] == 0.0, "right is negative left");
}
#[test]
fn look_turns_right_and_up() {
let s = PadSettings::default();
let (yaw, pitch) = look_delta([1.0, 0.0], &s, 1.0, false);
assert!((yaw - YAW_SPEED).abs() < 1e-3 && pitch == 0.0);
let (_, pitch) = look_delta([0.0, 1.0], &s, 0.5, false);
assert!((pitch + PITCH_SPEED * 0.5).abs() < 1e-3, "up looks up");
let inverted = PadSettings {
invert_y: true,
..PadSettings::default()
};
assert!(look_delta([0.0, 1.0], &inverted, 1.0, false).1 > 0.0);
let (small, _) = look_delta([0.5, 0.0], &s, 1.0, false);
assert!(
small < YAW_SPEED * 0.5,
"the curve is gentler near the centre"
);
assert_eq!(look_delta([0.05, 0.05], &s, 1.0, false), (0.0, 0.0));
assert!(look_delta([1.0, 0.0], &s, 1.0, true).0 < YAW_SPEED * 0.5);
}
#[test]
fn edges_with_trigger_hysteresis() {
let mut edges = Edges::default();
let mut state = PadState::default();
state.set(Button::South, true);
assert_eq!(edges.update(&state, 0.4), [(Button::South, true)]);
assert!(edges.update(&state, 0.4).is_empty());
state.triggers[1] = 0.45;
assert_eq!(edges.update(&state, 0.4), [(Button::RightTrigger, true)]);
state.triggers[1] = 0.35;
assert!(
edges.update(&state, 0.4).is_empty(),
"inside the hysteresis"
);
state.triggers[1] = 0.2;
state.set(Button::South, false);
assert_eq!(
edges.update(&state, 0.4),
[(Button::South, false), (Button::RightTrigger, false)]
);
state.set(Button::DPadUp, true);
edges.update(&state, 0.4);
assert_eq!(edges.release_all(), [(Button::DPadUp, false)]);
}
#[test]
fn merge_and_activity() {
let s = PadSettings::default();
let mut a = PadState::default();
assert!(!a.active(&s));
a.left = [0.1, 0.0];
assert!(!a.active(&s), "drift inside the deadzone");
let mut b = PadState::default();
b.set(Button::North, true);
b.left = [0.95, 0.0];
let m = a.merge(&b);
assert!(m.held(Button::North) && m.left[0] == 1.0 && m.active(&s));
}
#[test]
fn focus_moves_between_slots() {
// A 3x2 grid of slots 18 apart and a button below it.
let mut targets: Vec<(f32, f32)> = (0..6)
.map(|i| (8.0 + (i % 3) as f32 * 18.0, 8.0 + (i / 3) as f32 * 18.0))
.collect();
targets.push((26.0, 80.0));
let from = targets[0];
assert_eq!(focus_step(from, Button::DPadRight, &targets), Some(1));
assert_eq!(focus_step(from, Button::DPadDown, &targets), Some(3));
assert_eq!(focus_step(from, Button::DPadUp, &targets), None);
assert_eq!(focus_step(from, Button::DPadLeft, &targets), None);
assert_eq!(focus_step(targets[4], Button::DPadDown, &targets), Some(6));
// The far end of a row skips nothing in between.
assert_eq!(focus_step(targets[2], Button::DPadLeft, &targets), Some(1));
assert_eq!(nearest((12.0, 10.0), &targets, 9.0), Some(0));
assert_eq!(nearest((100.0, 100.0), &targets, 9.0), None);
let (x, y) = cursor_delta([0.0, 1.0], 0.15, 0.1);
assert!(x == 0.0 && y < -30.0, "up moves up the screen");
assert_eq!(cursor_delta([0.1, 0.0], 0.15, 0.1), (0.0, 0.0));
}
#[test]
fn labels_and_conflicts() {
assert_eq!(Button::South.label(GlyphStyle::Xbox), "A");
assert_eq!(Button::South.label(GlyphStyle::PlayStation), "×");
assert_eq!(Button::South.label(GlyphStyle::Nintendo), "B");
assert_eq!(Button::RightTrigger.label(GlyphStyle::PlayStation), "R2");
assert_eq!(Button::DPadLeft.label(GlyphStyle::Xbox), "←");
assert_eq!(
GlyphStyle::Auto.resolve(GlyphStyle::PlayStation),
GlyphStyle::PlayStation
);
assert_eq!(
GlyphStyle::Xbox.resolve(GlyphStyle::PlayStation),
GlyphStyle::Xbox
);
assert_eq!(GlyphStyle::Auto.resolve(GlyphStyle::Auto), GlyphStyle::Xbox);
let mut s = PadSettings::default();
assert!(!s.conflicts("key.jump"));
s.bind("key.drop", Some(Button::South));
assert!(s.conflicts("key.jump") && s.conflicts("key.drop"));
assert!(!s.is_default("key.drop") && s.is_default("key.jump"));
assert_eq!(action_caption(HOTBAR_NEXT), "Hotbar: Next Slot");
assert_eq!(action_caption("key.jump"), "key.jump");
}
#[test]
fn health_watch_only_counts_damage_in_one_life() {
let mut w = HealthWatch::default();
assert_eq!(w.observe(Some(20.0)), None);
assert_eq!(w.observe(Some(15.0)), Some(5.0));
assert_eq!(w.observe(Some(18.0)), None, "healing");
// A new player entity (world, respawn, server, dimension).
w.forget();
assert_eq!(w.observe(Some(6.0)), None);
// No player in between (title, loading) forgets too.
assert_eq!(w.observe(None), None);
assert_eq!(w.observe(Some(2.0)), None);
assert_eq!(w.observe(Some(1.0)), Some(1.0));
}
#[test]
fn rumble_pulses() {
let small = Rumble::Hurt(1.0).pulse().unwrap();
let big = Rumble::Hurt(10.0).pulse().unwrap();
assert!(big.strong > small.strong && big.millis > small.millis);
assert!(Rumble::Hurt(100.0).pulse().unwrap().strong <= 0.8);
assert_eq!(Rumble::Hurt(0.0).pulse(), None);
let near = Rumble::Explosion {
distance: 2.0,
radius: 4.0,
}
.pulse()
.unwrap();
let far = Rumble::Explosion {
distance: 12.0,
radius: 4.0,
}
.pulse()
.unwrap();
assert!(near.strong > far.strong);
assert_eq!(
Rumble::Explosion {
distance: 20.0,
radius: 4.0
}
.pulse(),
None
);
assert_eq!(Rumble::BlockBroken.pulse().unwrap().strong, 0.0);
}
#[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);
}
}
+56 -8
View File
@@ -5,7 +5,7 @@ use crate::{
Result,
environment::Sky,
hud::{HudBatch, HudRenderer},
mesher::{SectionMesh, Vertex},
mesher::{SectionMesh, TerrainVertex, Vertex},
sprites::SpriteAnimation,
};
use glam::{DVec3, Mat4, Vec3, Vec4};
@@ -22,6 +22,14 @@ const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState {
},
alpha: wgpu::BlendComponent::REPLACE,
};
/// `TerrainVertex` for `vs_terrain`: position, UV, layer, light, colour.
const TERRAIN_ATTRIBUTES: [wgpu::VertexAttribute; 5] =
wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint16,4=>Uint8x2,3=>Unorm8x4];
/// entity.wgsl after the OverlayTexture constants it reads.
fn entity_shader() -> String {
crate::overlay::wgsl_constants() + include_str!("entity.wgsl")
}
// Separate special materials without changing entity order or their overlays.
fn batch_entities(
@@ -369,6 +377,17 @@ impl Renderer {
pub fn resident_sections(&self) -> usize {
self.sections.len()
}
/// Bytes of the section vertex arena's buffers, and of the vertices
/// resident sections hold in them.
pub fn section_vertex_bytes(&self) -> [u64; 2] {
let stride = std::mem::size_of::<TerrainVertex>() as u64;
let vertices: u64 = self
.sections
.values()
.map(|s| u64::from(s.solid + s.translucent) * 4)
.sum();
[self.arena.bytes(), vertices * stride]
}
}
impl Renderer {
pub async fn new(
@@ -533,14 +552,12 @@ impl Renderer {
bind_group_layouts: &[Some(&bindings)],
..Default::default()
});
let vertex_attributes =
wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4];
let instance_attributes = wgpu::vertex_attr_array![5=>Float32x4];
let terrain_buffers = [
Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as u64,
array_stride: std::mem::size_of::<TerrainVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &vertex_attributes,
attributes: &TERRAIN_ATTRIBUTES,
}),
Some(wgpu::VertexBufferLayout {
array_stride: 16,
@@ -828,7 +845,7 @@ impl Renderer {
hud.atlas_texture = Some(atlas.clone());
let entity_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon entities"),
source: wgpu::ShaderSource::Wgsl(include_str!("entity.wgsl").into()),
source: wgpu::ShaderSource::Wgsl(entity_shader().into()),
});
let entity_bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Entity bindings"),
@@ -1327,7 +1344,11 @@ impl Renderer {
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let arena = arena::Arena::new(&device, std::mem::size_of::<Vertex>() as u64, 1 << 20);
let arena = arena::Arena::new(
&device,
std::mem::size_of::<TerrainVertex>() as u64,
1 << 20,
);
let indirect = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section draws"),
size: 1024 * 20,
@@ -1561,7 +1582,7 @@ impl Renderer {
}
let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64;
let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices);
let stride = std::mem::size_of::<Vertex>() as u64;
let stride = std::mem::size_of::<TerrainVertex>() as u64;
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
if !part.is_empty() {
let bytes: &[u8] = bytemuck::cast_slice(part);
@@ -2576,6 +2597,33 @@ mod tests {
);
}
#[test]
fn entity_shader_validates_with_its_overlay_constants() {
let module = naga::front::wgsl::parse_str(&super::entity_shader()).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
}
#[test]
fn terrain_attributes_follow_the_terrain_vertex() {
use super::TerrainVertex;
use std::mem::offset_of;
let offsets = super::TERRAIN_ATTRIBUTES.map(|a| (a.shader_location, a.offset as usize));
assert_eq!(
offsets,
[
(0, offset_of!(TerrainVertex, pos)),
(1, offset_of!(TerrainVertex, uv)),
(2, offset_of!(TerrainVertex, layer)),
(4, offset_of!(TerrainVertex, light)),
(3, offset_of!(TerrainVertex, color)),
]
);
assert_eq!(std::mem::size_of::<TerrainVertex>(), 28);
}
#[test]
fn cracks_multiply_instead_of_covering_the_block() {
let blend = super::CRUMBLING_BLEND;
assert_eq!(blend.color.src_factor, wgpu::BlendFactor::Dst);
+4
View File
@@ -84,6 +84,10 @@ impl Arena {
fn span(vertices: u64) -> u64 {
vertices.max(1).next_multiple_of(GRAIN)
}
/// Bytes of every page's buffer.
pub fn bytes(&self) -> u64 {
self.pages.iter().map(|p| p.capacity).sum::<u64>() * self.stride
}
pub fn buffer(&self, page: u32) -> &wgpu::Buffer {
&self.pages[page as usize].buffer
}
+68 -8
View File
@@ -490,12 +490,27 @@ impl GraphicsUi {
fn bounds(h: f32) -> (f32, f32) {
(STYLE.band, h - STYLE.band)
}
/// Widgets and the list's content height.
fn layout(&self, level: Level, w: f32, h: f32) -> (Vec<Widget>, Vec<(f32, &'static str)>, f32) {
fn content_height(level: Level) -> f32 {
rows(level).iter().fold(4.0, |height, row| {
height
+ match row {
Row::Header(_) => STYLE.header_height,
Row::Setting(_) => STYLE.row_height,
}
})
}
/// Widgets and the list's content height, using a bounded offset.
fn layout(
&mut self,
level: Level,
w: f32,
h: f32,
) -> (Vec<Widget>, Vec<(f32, &'static str)>, f32) {
let content = Self::content_height(level);
self.clamp_scroll(h, content);
let (top, _) = Self::bounds(h);
let x = STYLE.row_x(w);
let mut y = top + 4.0 - self.scroll;
let start = y;
let mut widgets = Vec::new();
let mut headers = Vec::new();
for row in rows(level) {
@@ -516,7 +531,6 @@ impl GraphicsUi {
}
}
}
let content = y - start + 4.0;
let cx = (w / 2.0).floor();
let by = h - 27.0;
let other = match level {
@@ -553,9 +567,7 @@ impl GraphicsUi {
in_world: bool,
) {
let (w, h) = (batch.width, batch.height);
let (_, _, content) = self.layout(level, w, h);
self.clamp_scroll(h, content);
let (widgets, headers, _) = self.layout(level, w, h);
let (widgets, headers, content) = self.layout(level, w, h);
let (top, bottom) = Self::bounds(h);
STYLE.background(batch, atlas, top, bottom, in_world);
let shown = |y: f32, height: f32| y >= top && y + height <= bottom;
@@ -684,8 +696,11 @@ impl GraphicsUi {
pub fn release(&mut self) {
self.dragging = None;
}
pub fn scroll(&mut self, amount: f32) {
pub fn scroll(&mut self, level: Level, h: f32, amount: f32) {
let content = Self::content_height(level);
self.clamp_scroll(h, content);
self.scroll -= amount * 18.0;
self.clamp_scroll(h, content);
}
}
@@ -693,6 +708,51 @@ impl GraphicsUi {
mod tests {
use super::*;
#[test]
fn scrolling_stops_at_both_limits_before_layout() {
for level in [Level::Simple, Level::Advanced] {
let mut ui = GraphicsUi::default();
let h = 120.0;
let (top, bottom) = GraphicsUi::bounds(h);
let max = GraphicsUi::content_height(level) - (bottom - top);
assert!(max > 4.5);
for _ in 0..3 {
ui.scroll(level, h, 1000.0);
assert_eq!(ui.scroll, 0.0);
}
for _ in 0..3 {
ui.scroll(level, h, -1000.0);
assert_eq!(ui.scroll, max);
}
ui.scroll(level, h, 0.25);
assert_eq!(ui.scroll, max - 4.5);
ui.scroll(level, h, 1000.0);
ui.scroll(level, h, -0.25);
assert_eq!(ui.scroll, 4.5);
}
}
#[test]
fn resizing_clamps_before_positioning_graphics_rows() {
for level in [Level::Simple, Level::Advanced] {
let mut ui = GraphicsUi::default();
ui.scroll(level, 120.0, -1000.0);
assert!(ui.scroll > 0.0);
let (widgets, headers, _) = ui.layout(level, 480.0, 4000.0);
assert_eq!(ui.scroll, 0.0);
if let Some((y, _)) = headers.first() {
assert_eq!(*y, STYLE.band + 4.0);
}
let (expected, _, _) = GraphicsUi::default().layout(level, 480.0, 4000.0);
assert_eq!(
widgets.iter().map(|w| w.y).collect::<Vec<_>>(),
expected.iter().map(|w| w.y).collect::<Vec<_>>()
);
ui.scroll(level, 4000.0, -1000.0);
assert_eq!(ui.scroll, 0.0);
}
}
#[test]
fn every_advanced_setting_has_a_description() {
for level in [Level::Simple, Level::Advanced] {
+1 -34
View File
@@ -254,7 +254,6 @@ impl ChunkEncoder {
tag: block_entities
.get(&pos)
.and_then(entity_tag)
.or_else(|| saved_update_tag(chunk, pos))
.unwrap_or(Tag::End),
});
}
@@ -343,43 +342,11 @@ fn java_hash_order<T>(items: &mut Vec<T>, pos: impl Fn(&T) -> (i32, i32, i32)) {
items.extend(iteration.into_iter().filter_map(|i| slots[i].take()));
}
/// The update tag of a block entity Horizon keeps only as loaded NBT:
/// SpawnerBlockEntity.getUpdateTag is its saved fields without
/// SpawnPotentials (saveCustomOnly, so no id or position).
fn saved_update_tag(chunk: &Chunk, pos: (i32, i32, i32)) -> Option<Tag> {
let saved = chunk.saved.as_ref()?;
let tag = saved.block_entities.iter().find(|t| {
let Tag::Compound(c) = t else { return false };
let at = |k: &str| match c.get(&k.into()) {
Some(Tag::Int(v)) => Some(*v),
_ => None,
};
(at("x"), at("y"), at("z")) == (Some(pos.0), Some(pos.1), Some(pos.2))
})?;
if crate::block_entity_nbt::id(tag).as_deref() != Some("minecraft:mob_spawner") {
return None;
}
let Tag::Compound(mut c) = crate::block_entity_nbt::canonical(tag)? else {
return None;
};
for key in [
"id",
"x",
"y",
"z",
"keepPacked",
"SpawnPotentials",
"components",
] {
c.remove(&key.into());
}
Some(Tag::Compound(c))
}
/// The update tag of a block entity (getUpdateTag) for what the client shows.
pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
match entity {
BlockEntity::Sign(sign) => Some(Tag::compound(sign.encode())),
BlockEntity::Spawner(s) => Some(s.update_tag()),
BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None,
_ => None,
}
@@ -78,6 +78,28 @@ impl Hub {
);
}
/// ClientboundBlockEventPacket (`PlayerList.broadcast` within 64 blocks).
pub fn block_event(&self, pos: [i32; 3], b0: i32, b1: i32, state: u16) {
let block = self
.encoder
.block_ids
.get(usize::from(state))
.copied()
.unwrap_or(0);
let at = [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])];
self.broadcast_near(
at,
64.0,
&C::BlockEvent(play::BlockEvent {
pos,
b0: b0 as u8,
b1: b1 as u8,
block,
}),
None,
);
}
pub fn entity_event(&self, id: i32, event: i8, at: [f64; 3]) {
self.broadcast_near(
at,
+6 -2
View File
@@ -360,8 +360,12 @@ impl BlockLandingWorld for MotionWorld<'_, '_, '_> {
multiplier: f32,
source: LandingDamage,
) -> Result<bool> {
// Nonflying player: Player.causeFallDamage records centimeters before
// delegating to LivingEntity. No mayfly ability in the walking scene.
// Player.causeFallDamage exempts players with the mayfly ability,
// including creative players who are currently walking.
if self.player.may_fly {
return Ok(false);
}
// Record centimeters before delegating to LivingEntity.
if distance >= 2.0 || distance.is_nan() {
let scaled = distance * 100.0;
let floor = scaled.floor();
+2
View File
@@ -54,6 +54,7 @@ pub mod flatgen;
pub mod fog;
pub mod font;
pub mod front;
pub mod gamepad;
pub mod gamerules;
pub mod gfx;
pub mod gizmos;
@@ -97,6 +98,7 @@ pub mod options_file;
pub mod options_fixes;
pub mod options_horizon;
pub mod options_ui;
pub mod overlay;
pub mod pack_screen;
pub mod packs;
pub mod particles;
+42 -18
View File
@@ -22,10 +22,11 @@ use horizon_world::{
};
use std::sync::Arc;
/// An entity, item and effect vertex (the entity pipelines), with a face
/// normal for `entity.wgsl`'s directional light.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Vertex {
/// Section-relative position.
pub pos: [f32; 3],
pub uv: [f32; 2],
pub layer: u32,
@@ -36,9 +37,26 @@ pub struct Vertex {
/// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour.
pub normal: [i8; 4],
}
/// A section vertex, 28 bytes like vanilla's `DefaultVertexFormat.BLOCK`
/// (position, colour, UV0, UV2) with the sprite's array layer beside the
/// light. Terrain has no normal: `ModelBlockRenderer` bakes the face shade
/// into the colour and `terrain.vsh` only multiplies it by the lightmap.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct TerrainVertex {
/// Section-relative position.
pub pos: [f32; 3],
pub uv: [f32; 2],
/// Sprite array layer, with `OPAQUE_LAYER` for opaque leaves.
pub layer: u16,
/// Smooth light, 16x fixed point: sky in the low byte, block in the high one.
pub light: u16,
/// RGBA8: tint multiplied by directional shade and ambient occlusion.
pub color: u32,
}
pub struct SectionMesh {
pub solid: Vec<Vertex>,
pub translucent: Vec<Vertex>,
pub solid: Vec<TerrainVertex>,
pub translucent: Vec<TerrainVertex>,
/// VisGraph: bit `a * 6 + b` is set when faces `a` and `b` (Direction
/// order) are connected through non-opaque blocks.
pub visibility: u64,
@@ -192,11 +210,11 @@ pub struct MeshFacts {
pub struct MeshTables {
info: Vec<Info>,
pub visibility: FaceVisibility,
water_still: u32,
water_flow: u32,
water_overlay: u32,
lava_still: u32,
lava_flow: u32,
water_still: u16,
water_flow: u16,
water_overlay: u16,
lava_still: u16,
lava_flow: u16,
}
fn redstone_color(power: u8) -> u32 {
// RedstoneWireBlock.COLORS
@@ -212,11 +230,18 @@ impl MeshTables {
facts: &BlockFacts,
visibility: FaceVisibility,
) -> crate::Result<Self> {
let layer = |name: &str| -> crate::Result<u32> {
// Terrain vertices keep the sprite layer below `OPAQUE_LAYER`.
let layers = assets.sprite_layers.values().max().map_or(0, |l| l + 1);
if layers > u32::from(OPAQUE_LAYER) {
return Err(
format!("{layers} block sprites, terrain vertices index {OPAQUE_LAYER}").into(),
);
}
let layer = |name: &str| -> crate::Result<u16> {
assets
.sprite_layers
.get(name)
.copied()
.map(|&l| l as u16)
.ok_or_else(|| format!("missing fluid sprite {name}").into())
};
let mut covers = std::collections::HashMap::new();
@@ -416,8 +441,8 @@ impl Padded {
Self { blocks, light }
}
}
/// Set on a vertex's sprite layer when its texture alpha must be ignored.
pub const OPAQUE_LAYER: u32 = 1 << 31;
/// Set on a terrain vertex's sprite layer when its texture alpha must be ignored.
pub const OPAQUE_LAYER: u16 = 1 << 15;
const UNSET: u32 = u32::MAX;
const NO_BIOME: u16 = u16::MAX;
/// The `ColorResolver`s `ClientLevel` caches block tints for.
@@ -530,8 +555,8 @@ fn pack_rgb([r, g, b]: [u32; 3]) -> u32 {
}
/// Vanilla light coords (block*16 in the low half, sky*16 in the high half) to
/// the vertex layout (sky*16 in bits 0..8, block*16 in bits 8..16).
fn pack_coords(coords: u32) -> u32 {
(coords >> 16 & 0xFF) | (coords & 0xFF) << 8
fn pack_coords(coords: u32) -> u16 {
((coords >> 16 & 0xFF) | (coords & 0xFF) << 8) as u16
}
pub struct Mesher<'a> {
/// CardinalLighting.NETHER: brighter up/down faces.
@@ -723,15 +748,14 @@ impl Mesher<'_> {
None => [g; 3],
};
let p = q.positions[i];
target.push(Vertex {
normal: [0; 4],
target.push(TerrainVertex {
pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]],
uv: q.uv[i],
// Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout.
layer: if !self.cutout_leaves && state.leaves {
face.layer | OPAQUE_LAYER
face.layer as u16 | OPAQUE_LAYER
} else {
face.layer
face.layer as u16
},
color: pack_rgb(rgb),
light: pack_coords(lighting::with_emission(coords[i], q.light_emission)),
+5 -4
View File
@@ -2,7 +2,9 @@
//! occlusion against neighbour shapes, flow-rotated top UVs, the water overlay
//! beside glass and leaves, back faces, cardinal shading and max(self, above)
//! light.
use super::{Info, MeshTables, Padded, SectionMesh, Vertex, lighting, pack_coords, pack_rgb, pi};
use super::{
Info, MeshTables, Padded, SectionMesh, TerrainVertex, lighting, pack_coords, pack_rgb, pi,
};
use horizon_core::{
geometry::{Axis, Direction, VoxelShape, trig},
position::BlockPos,
@@ -303,9 +305,8 @@ pub(super) fn tesselate(
&mut out.solid
};
let mut quad =
|v: [([f32; 3], [f32; 2]); 4], layer: u32, color: u32, light: u32, back: bool| {
let vertex = |(pos, uv): ([f32; 3], [f32; 2])| Vertex {
normal: [0; 4],
|v: [([f32; 3], [f32; 2]); 4], layer: u16, color: u32, light: u16, back: bool| {
let vertex = |(pos, uv): ([f32; 3], [f32; 2])| TerrainVertex {
pos,
uv,
layer,
+1
View File
@@ -54,6 +54,7 @@ pub mod shulker;
pub mod sniffer;
pub mod spawn_rules;
pub mod spawn_selection;
pub mod spawner;
pub mod spawning;
pub mod species;
pub mod sulfur_cube;
+58 -14
View File
@@ -716,6 +716,11 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 {
m.previous.y + (m.position.y - m.previous.y) * a,
m.previous.z + (m.position.z - m.previous.z) * a,
) - camera;
base_transform_at(m, alpha, glam::Mat4::from_translation(p.as_vec3()))
}
/// `base_transform` from a pose of the entity's origin (`EntityRenderDispatcher.submit`
/// under a pose stack, as `SpawnerRenderer` draws the mob inside a spawner).
pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 {
let mut body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha;
if shaking(m) {
// LivingEntityRenderer.setupRotations: a rapid wobble.
@@ -737,7 +742,7 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 {
None => super::aquatic::rotations(m, alpha, body)
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
};
let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation;
let mut base = origin * rotation;
if m.extra.fall_flying {
let ticks = m.extra.fall_fly_ticks as f32 + alpha;
let scale = (ticks * ticks / 100.0).min(1.0);
@@ -800,6 +805,25 @@ fn species_rotations(m: &Mob, alpha: f32) -> glam::Mat4 {
_ => glam::Mat4::IDENTITY,
}
}
/// Creeper.getSwelling: the fuse's progress, past 1 in its last two ticks.
fn creeper_swelling(m: &Mob, alpha: f32) -> f32 {
(m.previous_swell as f32 + alpha * (m.swell - m.previous_swell) as f32) / 28.0
}
/// LivingEntityRenderer.getOverlayCoords for the body: the hurt red, or a
/// swelling creeper's white flash. Layers take the red only (progress 0).
fn body_overlay(m: &Mob, alpha: f32) -> u32 {
let white = if m.species() == Species::Creeper {
crate::overlay::creeper_progress(creeper_swelling(m, alpha))
} else {
0.0
};
crate::overlay::living(white, red_overlay(m))
}
/// LivingEntityRenderState.hasRedOverlay: hurt or dying (not a creaking
/// tearing down).
fn red_overlay(m: &Mob) -> bool {
m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))
}
fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 {
match m.species() {
Species::Wither => {
@@ -807,10 +831,9 @@ fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 {
}
Species::Creeper => {
// CreeperRenderer.scale: swelling with a wobble.
let s = ((m.previous_swell as f32 + (m.swell - m.previous_swell) as f32 * alpha)
/ 28.0)
.clamp(0.0, 1.0);
let wobble = 1.0 + (s * 100.0).msin() * s * 0.01;
let g = creeper_swelling(m, alpha);
let wobble = 1.0 + (g * 100.0).msin() * g * 0.01;
let s = g.clamp(0.0, 1.0);
let s4 = s * s * s * s;
let xz = (1.0 + s4 * 0.4) * wobble;
let y = (1.0 + s4 * 0.1) / wobble;
@@ -926,27 +949,49 @@ pub fn render_with(
let w = super::illusioner::wobble(i, age);
let shifted =
camera - glam::DVec3::new(off[0] + w[0], off[1] + w[1], off[2] + w[2]);
render_visible(m, alpha, shifted, atlas, light, data, extra, out);
let base = base_transform(m, alpha, shifted);
render_visible(m, alpha, base, atlas, light, data, extra, out);
}
}
return;
}
render_visible(m, alpha, camera, atlas, light, data, extra, out);
render_visible(
m,
alpha,
base_transform(m, alpha, camera),
atlas,
light,
data,
extra,
out,
);
}
/// A mob drawn under `origin` instead of at its position (the spinning mob
/// of `SpawnerRenderer.submitEntityInSpawner`).
pub fn render_posed(
m: &Mob,
alpha: f32,
origin: glam::Mat4,
atlas: Atlas,
light: u32,
data: &MobData,
out: &mut Vec<Vertex>,
) {
let base = base_transform_at(m, alpha, origin);
render_visible(m, alpha, base, atlas, light, data, &[], out);
}
#[allow(clippy::too_many_arguments)]
fn render_visible(
m: &Mob,
alpha: f32,
camera: glam::DVec3,
base: glam::Mat4,
atlas: Atlas,
light: u32,
data: &MobData,
extra: &[(&Part, [f32; 4], u32)],
out: &mut Vec<Vertex>,
) {
let base = base_transform(m, alpha, camera);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
let overlay = u32::from(red_overlay(m));
let s = anim::state(m, alpha);
let (model_key, texture) = body(m);
let model = m
@@ -964,7 +1009,7 @@ fn render_visible(
uv,
body_color(m, alpha),
light,
overlay,
body_overlay(m, alpha),
out,
);
}
@@ -1035,8 +1080,7 @@ pub fn render_single(
out: &mut Vec<Vertex>,
) {
let base = base_transform(m, alpha, camera);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
let overlay = body_overlay(m, alpha);
let s = anim::state(m, alpha);
let model = m.kind.model.clone();
let mut poses = Poses::new(&model);
@@ -445,7 +445,7 @@ fn fluid_at<L: NaturalLevel>(l: &L, x: i32, y: i32, z: i32) -> crate::blocks::Fl
l.facts().get(l.state(x, y, z)).fluid
}
/// `checkSpawnRules(level, NATURAL)` of a freshly created mob at a block.
fn mob_spawn_rules<L: NaturalLevel>(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool {
pub(crate) fn mob_spawn_rules<L: NaturalLevel>(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool {
use crate::blocks::Fluid;
let value = match walk_target(s) {
WalkTarget::NotPathfinder | WalkTarget::Zero => 0.0,
@@ -584,7 +584,7 @@ pub fn spawn_aabb(s: Species, x: f64, y: f64, z: f64, width: f32, height: f32) -
)
}
/// `checkSpawnObstruction` of a freshly created mob with the given box.
fn spawn_obstruction<L: NaturalLevel>(
pub(crate) fn spawn_obstruction<L: NaturalLevel>(
s: Species,
l: &L,
bounds: Aabb,
+740
View File
@@ -0,0 +1,740 @@
//! The monster spawner (`BaseSpawner` as `SpawnerBlockEntity` runs it): its
//! saved state and `SpawnData`, the server tick that spawns its mobs and the
//! client tick that spins the mob inside and puffs flames.
//!
//! Vanilla keeps a server and a client copy of the block entity; Horizon keeps
//! one [`Spawner`] with the client's own delay and spin beside the server's
//! state. The level's random drives the server tick in vanilla's draw order;
//! what the spawner asks of the level goes through [`SpawnerLevel`], so the
//! game and a differential test world answer the same questions.
use super::{
Species,
spawn_rules::{self, Reason},
spawn_selection::{self, Category, NaturalLevel},
};
use horizon_core::{geometry::Aabb, geometry::Vec3, random::RandomSource};
use horizon_world::nbt::{Compound, JavaString, Tag};
/// `SpawnData.CustomSpawnRules`: the block and sky light the spawn block
/// must have (inclusive ranges within 0..=15).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CustomSpawnRules {
pub block: (i32, i32),
pub sky: (i32, i32),
}
/// `SpawnData`: the entity to spawn, optional light rules and an equipment
/// table (kept as loaded).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SpawnData {
pub entity: Compound,
pub custom_spawn_rules: Option<CustomSpawnRules>,
pub equipment: Option<Tag>,
}
impl SpawnData {
/// The `SpawnData` constructor: an `id` that is a valid identifier is
/// stored normalised (`zombie` becomes `minecraft:zombie`), any other is
/// removed.
pub fn new(
mut entity: Compound,
rules: Option<CustomSpawnRules>,
equipment: Option<Tag>,
) -> Self {
let key = JavaString::from("id");
let id = match entity.get(&key) {
Some(Tag::String(s)) => normalize_id(&s.to_string_lossy()),
_ => None,
};
match id {
Some(id) => {
entity.insert(key, Tag::String(id.as_str().into()));
}
None => {
entity.remove(&key);
}
}
Self {
entity,
custom_spawn_rules: rules,
equipment,
}
}
/// The entity's `id`, if any.
pub fn id(&self) -> Option<String> {
match self.entity.get(&JavaString::from("id")) {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
}
}
/// `SpawnData.CODEC`: `entity` (required), `custom_spawn_rules` and
/// `equipment`.
pub fn decode(tag: &Tag) -> Option<Self> {
let Some(Tag::Compound(entity)) = tag.get("entity") else {
return None;
};
let rules = match tag.get("custom_spawn_rules") {
Some(Tag::Compound(_)) => {
let rules = tag.get("custom_spawn_rules")?;
Some(CustomSpawnRules {
block: light_limit(rules.get("block_light_limit"))?,
sky: light_limit(rules.get("sky_light_limit"))?,
})
}
Some(_) => return None,
None => None,
};
Some(Self::new(
entity.clone(),
rules,
tag.get("equipment").cloned(),
))
}
pub fn encode(&self) -> Tag {
let mut out = vec![("entity", Tag::Compound(self.entity.clone()))];
if let Some(r) = self.custom_spawn_rules {
let mut rules = Vec::new();
for (name, range) in [("block_light_limit", r.block), ("sky_light_limit", r.sky)] {
// lenientOptionalFieldOf: the full range is left out.
if range != (0, 15) {
rules.push((name, encode_range(range)));
}
}
out.push(("custom_spawn_rules", Tag::compound(rules)));
}
if let Some(e) = &self.equipment {
out.push(("equipment", e.clone()));
}
Tag::compound(out)
}
/// The entity compound is only its `id` (`hasNoConfiguration`): the
/// spawned mob is finalized.
fn unconfigured(&self) -> bool {
self.entity.len() == 1 && self.id().is_some()
}
/// `CustomSpawnRules.isValidPosition`.
fn valid_position<L: SpawnerLevel>(r: CustomSpawnRules, l: &L, x: i32, y: i32, z: i32) -> bool {
let block = l.block_light(x, y, z);
let sky = (l.sky_light(x, y, z) - l.sky_darken()).max(0);
(r.block.0..=r.block.1).contains(&block) && (r.sky.0..=r.sky.1).contains(&sky)
}
}
/// `Identifier.CODEC` parsing an entity id: lowercase namespace and path
/// characters, `minecraft` when the namespace is left out.
pub fn normalize_id(s: &str) -> Option<String> {
let (ns, path) = match s.split_once(':') {
Some((ns, path)) => (if ns.is_empty() { "minecraft" } else { ns }, path),
None => ("minecraft", s),
};
let ok = |c: char, slash: bool| {
c.is_ascii_lowercase()
|| c.is_ascii_digit()
|| matches!(c, '_' | '-' | '.')
|| slash && c == '/'
};
(ns.chars().all(|c| ok(c, false)) && path.chars().all(|c| ok(c, true)))
.then(|| format!("{ns}:{path}"))
}
/// A whole number from any numeric tag (`NumericTag.intValue`: floats floor).
fn number(tag: Option<&Tag>) -> Option<i64> {
Some(match tag? {
Tag::Byte(v) => i64::from(*v),
Tag::Short(v) => i64::from(*v),
Tag::Int(v) => i64::from(*v),
Tag::Long(v) => *v,
Tag::Float(b) => f32::from_bits(*b).floor() as i64,
Tag::Double(b) => f64::from_bits(*b).floor() as i64,
_ => return None,
})
}
/// `InclusiveRange.INT` within 0..=15 (`lenientOptionalFieldOf` with the
/// full range as default): a number, a two-element list or
/// `{min_inclusive, max_inclusive}`. None is a decoding error.
fn light_limit(tag: Option<&Tag>) -> Option<(i32, i32)> {
let int = |t: &Tag| match t {
Tag::Int(v) => Some(*v),
Tag::Byte(v) => Some(i32::from(*v)),
Tag::Short(v) => Some(i32::from(*v)),
_ => None,
};
let range = match tag {
None => return Some((0, 15)),
Some(Tag::IntArray(v)) if v.len() == 2 => Some((v[0], v[1])),
Some(Tag::List(v)) if v.len() == 2 => int(&v[0]).zip(int(&v[1])),
Some(t @ Tag::Compound(_)) => t
.get("min_inclusive")
.and_then(int)
.zip(t.get("max_inclusive").and_then(int)),
Some(t) => int(t).map(|v| (v, v)),
};
match range {
// A malformed value falls back to the default (lenient); an
// inverted range or one outside 0..=15 fails validation.
None => Some((0, 15)),
Some((lo, hi)) if lo <= hi && lo >= 0 && hi <= 15 => Some((lo, hi)),
Some(_) => None,
}
}
fn encode_range((lo, hi): (i32, i32)) -> Tag {
if lo == hi {
Tag::Int(lo)
} else {
Tag::IntArray(vec![lo, hi])
}
}
/// Which `SpawnData` is next: one of the potentials (the same object in
/// vanilla, so changing it changes the potential) or its own.
#[derive(Clone, Debug, PartialEq)]
enum Next {
Potential(usize),
Own(SpawnData),
}
/// `BaseSpawner`.
#[derive(Clone, Debug, PartialEq)]
pub struct Spawner {
pub spawn_delay: i32,
/// `SpawnPotentials`: data and weight.
pub potentials: Vec<(SpawnData, i32)>,
next: Option<Next>,
pub min_spawn_delay: i32,
pub max_spawn_delay: i32,
pub spawn_count: i32,
pub max_nearby_entities: i32,
pub required_player_range: i32,
pub spawn_range: i32,
/// The client copy's delay (`spawnDelay` on the client level), which
/// speeds the spin up as the next spawn nears.
pub client_delay: i32,
pub spin: f64,
pub o_spin: f64,
}
impl Default for Spawner {
fn default() -> Self {
Self {
spawn_delay: 20,
potentials: Vec::new(),
next: None,
min_spawn_delay: 200,
max_spawn_delay: 800,
spawn_count: 4,
max_nearby_entities: 6,
required_player_range: 16,
spawn_range: 4,
client_delay: 20,
spin: 0.0,
o_spin: 0.0,
}
}
}
/// What a spawner did that the level shows or sends.
#[derive(Clone, Debug, PartialEq)]
pub enum SpawnerEvent {
/// `setNextSpawnData`: `sendBlockUpdated` with the new update tag.
BlockUpdated,
/// `broadcastEvent(1)`: the block event that resets the clients' delay.
BlockEvent(i32),
/// `levelEvent(2004)`: the flame and smoke burst at the spawner.
LevelEvent(i32),
/// `gameEvent(entity, ENTITY_PLACE, block)`.
EntityPlace(u32, [i32; 3]),
/// `mob.spawnAnim()`: entity event 20 (the poof).
SpawnAnim(u32),
}
/// A mob or entity the spawner wants to add (`EntityType.loadEntityRecursive`
/// then `tryAddFreshEntityWithPassengers`).
#[derive(Clone, Debug)]
pub struct SpawnerSpawn<'a> {
pub entity: &'a Compound,
pub id: &'a str,
pub position: [f64; 3],
pub yaw: f32,
/// `finalizeSpawn(SPAWNER)` runs (the data is just an id).
pub finalize: bool,
pub equipment: Option<&'a Tag>,
}
/// An entity the level added: its id, box and whether it is a mob.
#[derive(Clone, Copy, Debug)]
pub struct SpawnerAdded {
pub id: u32,
pub bounds: Aabb,
pub mob: bool,
}
/// What a spawner reads from the level besides the spawn rules.
pub trait SpawnerLevel: NaturalLevel {
/// `hasNearbyAlivePlayer`: a living non-spectator closer than `range`
/// (any distance when negative).
fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool;
/// The `spawner_blocks_work` game rule.
fn spawner_blocks_work(&self) -> bool;
/// `EntityType.byString`: the entity type exists.
fn entity_exists(&self, id: &str) -> bool;
/// Entities of the exact class of `id` whose box meets `bounds`.
fn count_entities(&self, id: &str, bounds: Aabb) -> usize;
}
impl Spawner {
/// `BaseSpawner.load` (`SpawnerBlockEntity.loadAdditional`).
pub fn load(tag: &Tag) -> Self {
let mut s = Self {
spawn_delay: number(tag.get("Delay")).map_or(20, |v| i32::from(v as i16)),
..Self::default()
};
s.next = tag
.get("SpawnData")
.and_then(SpawnData::decode)
.map(Next::Own);
s.potentials = match tag.get("SpawnPotentials") {
Some(Tag::List(list)) => list
.iter()
.filter_map(|e| {
let weight = match e.get("weight") {
Some(Tag::Int(w)) if *w >= 0 => *w,
_ => return None,
};
Some((SpawnData::decode(e.get("data")?)?, weight))
})
.collect(),
// WeightedList.of(nextSpawnData), the same object, when the
// potentials are missing or not a list.
_ => {
let data = match s.next.take() {
Some(Next::Own(d)) => d,
_ => SpawnData::default(),
};
let had = tag.get("SpawnData").and_then(SpawnData::decode).is_some();
if had {
s.next = Some(Next::Potential(0));
}
vec![(data, 1)]
}
};
let int = |k: &str, d: i32| number(tag.get(k)).map_or(d, |v| v as i32);
s.min_spawn_delay = int("MinSpawnDelay", 200);
s.max_spawn_delay = int("MaxSpawnDelay", 800);
s.spawn_count = int("SpawnCount", 4);
s.max_nearby_entities = int("MaxNearbyEntities", 6);
s.required_player_range = int("RequiredPlayerRange", 16);
s.spawn_range = int("SpawnRange", 4);
s.client_delay = s.spawn_delay;
s
}
/// `BaseSpawner.save`: the fields as shorts, the next data when set and
/// the potentials.
pub fn save(&self) -> Vec<(&'static str, Tag)> {
let short = |v: i32| Tag::Short(v as i16);
let mut out = vec![
("Delay", short(self.spawn_delay)),
("MinSpawnDelay", short(self.min_spawn_delay)),
("MaxSpawnDelay", short(self.max_spawn_delay)),
("SpawnCount", short(self.spawn_count)),
("MaxNearbyEntities", short(self.max_nearby_entities)),
("RequiredPlayerRange", short(self.required_player_range)),
("SpawnRange", short(self.spawn_range)),
];
if let Some(next) = self.next_data() {
out.push(("SpawnData", next.encode()));
}
out.push((
"SpawnPotentials",
Tag::List(
self.potentials
.iter()
.map(|(d, w)| Tag::compound([("data", d.encode()), ("weight", Tag::Int(*w))]))
.collect(),
),
));
out
}
/// `SpawnerBlockEntity.getUpdateTag`: the saved fields without the potentials.
pub fn update_tag(&self) -> Tag {
Tag::compound(
self.save()
.into_iter()
.filter(|(k, _)| *k != "SpawnPotentials"),
)
}
pub fn next_data(&self) -> Option<&SpawnData> {
match self.next.as_ref()? {
Next::Own(d) => Some(d),
Next::Potential(i) => self.potentials.get(*i).map(|(d, _)| d),
}
}
fn next_data_mut(&mut self) -> Option<&mut SpawnData> {
match self.next.as_mut()? {
Next::Own(d) => Some(d),
Next::Potential(i) => self.potentials.get_mut(*i).map(|(d, _)| d),
}
}
/// `WeightedList.getRandom`: one draw over the total weight, none when
/// the list weighs nothing.
fn random_potential(&self, random: &mut impl RandomSource) -> Option<usize> {
let total: i64 = self.potentials.iter().map(|(_, w)| i64::from(*w)).sum();
if total == 0 {
return None;
}
let mut pick = i64::from(
random
.next_int_bound(total.min(i64::from(i32::MAX)) as i32)
.unwrap_or(0),
);
for (i, (_, w)) in self.potentials.iter().enumerate() {
pick -= i64::from(*w);
if pick < 0 {
return Some(i);
}
}
None
}
/// `getOrCreateNextSpawnData`: a potential at random, or empty data.
fn next_or_create(&mut self, random: &mut impl RandomSource, events: &mut Vec<SpawnerEvent>) {
if self.next.is_some() {
return;
}
self.next = Some(match self.random_potential(random) {
Some(i) => Next::Potential(i),
None => Next::Own(SpawnData::default()),
});
events.push(SpawnerEvent::BlockUpdated);
}
/// `setEntityId`: the next data's `id` (a spawn egg used on the spawner).
pub fn set_entity_id(
&mut self,
id: &str,
random: &mut impl RandomSource,
events: &mut Vec<SpawnerEvent>,
) {
self.next_or_create(random, events);
if let Some(d) = self.next_data_mut() {
d.entity.insert("id".into(), Tag::String(id.into()));
}
}
/// `isNearPlayer`.
fn near_player<L: SpawnerLevel>(&self, l: &L, pos: [i32; 3]) -> bool {
l.alive_player_near(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
f64::from(self.required_player_range),
)
}
/// `delay`: the next delay, a new potential (when there are any) and the
/// block event.
fn delay(&mut self, random: &mut impl RandomSource, events: &mut Vec<SpawnerEvent>) {
self.spawn_delay = if self.max_spawn_delay <= self.min_spawn_delay {
self.min_spawn_delay
} else {
self.min_spawn_delay
+ random
.next_int_bound(self.max_spawn_delay - self.min_spawn_delay)
.unwrap_or(0)
};
if let Some(i) = self.random_potential(random) {
self.next = Some(Next::Potential(i));
events.push(SpawnerEvent::BlockUpdated);
}
events.push(SpawnerEvent::BlockEvent(1));
}
/// `serverTick`. `spawn` adds an entity the spawner accepted and returns
/// it, or None when the level would not take it.
pub fn server_tick<L: SpawnerLevel, R: RandomSource>(
&mut self,
l: &L,
random: &mut R,
pos: [i32; 3],
spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option<SpawnerAdded>,
events: &mut Vec<SpawnerEvent>,
) {
if !self.near_player(l, pos) || !l.spawner_blocks_work() {
return;
}
if self.spawn_delay == -1 {
self.delay(random, events);
}
if self.spawn_delay > 0 {
self.spawn_delay -= 1;
return;
}
let mut delay = false;
self.next_or_create(random, events);
let Some(data) = self.next_data().cloned() else {
return;
};
// Boxes of what this tick added, for the obstruction test.
let mut added: Vec<Aabb> = Vec::new();
for _ in 0..self.spawn_count {
// EntityType.by: an unknown type delays.
let Some(id) = data.id().filter(|id| l.entity_exists(id)) else {
self.delay(random, events);
return;
};
let at = match read_pos(data.entity.get(&JavaString::from("Pos"))) {
Some(p) => p,
None => {
let range = f64::from(self.spawn_range);
let x = f64::from(pos[0])
+ (random.next_double() - random.next_double()) * range
+ 0.5;
let y = f64::from(pos[1] + random.next_int_bound(3).unwrap_or(0) - 1);
let z = f64::from(pos[2])
+ (random.next_double() - random.next_double()) * range
+ 0.5;
[x, y, z]
}
};
let kind = l.mob_type(&id);
let (species, width, height, category) = match kind {
Some((s, w, h, c)) => (Some(s), w, h, c),
// Entity types Horizon cannot create: a unit box, misc.
None => (None, 1.0, 1.0, Category::Misc),
};
let spawn_box = match species {
Some(s) => spawn_selection::spawn_aabb(s, at[0], at[1], at[2], width, height),
None => spawn_selection::spawn_box(at[0], at[1], at[2], width, height),
};
if !l.no_collision(spawn_box) {
continue;
}
let block = [
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
];
if let Some(rules) = data.custom_spawn_rules {
if !category.friendly() && l.peaceful() {
continue;
}
if !SpawnData::valid_position(rules, l, block[0], block[1], block[2]) {
continue;
}
} else if let Some(s) = species
&& !spawn_rules::check_spawn_rules(
s,
l,
Reason::Spawner,
random,
block[0],
block[1],
block[2],
)
{
continue;
}
// loadEntityRecursive: a type the game cannot create delays.
let Some(s) = species else {
self.delay(random, events);
return;
};
let around = Aabb::new(
Vec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])),
Vec3::new(
f64::from(pos[0] + 1),
f64::from(pos[1] + 1),
f64::from(pos[2] + 1),
),
)
.inflate(Vec3::new(
f64::from(self.spawn_range),
f64::from(self.spawn_range),
f64::from(self.spawn_range),
));
if l.count_entities(&id, around) as i64 >= i64::from(self.max_nearby_entities) {
self.delay(random, events);
return;
}
let yaw = random.next_float() * 360.0;
// The entity's own position (Entity.setPos, which a shulker snaps
// to its block) for its box and its block.
let placed = entity_position(s, at);
let own = [
placed[0].floor() as i32,
placed[1].floor() as i32,
placed[2].floor() as i32,
];
let bounds = spawn_selection::spawn_box(placed[0], placed[1], placed[2], width, height);
let rules_ok = data.custom_spawn_rules.is_some()
|| spawn_selection::mob_spawn_rules(s, l, own[0], own[1], own[2]);
if !rules_ok
|| !spawn_selection::spawn_obstruction(s, l, bounds, &added, own[0], own[1], own[2])
{
continue;
}
let request = SpawnerSpawn {
entity: &data.entity,
id: &id,
position: placed,
yaw,
finalize: data.unconfigured(),
equipment: data.equipment.as_ref(),
};
let Some(result) = spawn(l, &request) else {
self.delay(random, events);
return;
};
added.push(result.bounds);
events.push(SpawnerEvent::LevelEvent(2004));
events.push(SpawnerEvent::EntityPlace(result.id, block));
if result.mob {
events.push(SpawnerEvent::SpawnAnim(result.id));
}
delay = true;
}
if delay {
self.delay(random, events);
}
}
/// `clientTick`: with a player near and a mob to show, a smoke and flame
/// particle at a random point of the block (returned) and the spin.
pub fn client_tick(
&mut self,
near_player: bool,
has_display: bool,
random: &mut impl RandomSource,
pos: [i32; 3],
) -> Option<[f64; 3]> {
if !near_player {
self.o_spin = self.spin;
return None;
}
if !has_display {
return None;
}
let p = [
f64::from(pos[0]) + random.next_double(),
f64::from(pos[1]) + random.next_double(),
f64::from(pos[2]) + random.next_double(),
];
if self.client_delay > 0 {
self.client_delay -= 1;
}
self.o_spin = self.spin;
self.spin =
(self.spin + f64::from(1000.0_f32 / (self.client_delay as f32 + 200.0))) % 360.0;
Some(p)
}
/// `onEventTriggered` on the client: event 1 resets the delay.
pub fn client_event(&mut self, id: i32) -> bool {
if id == 1 {
self.client_delay = self.min_spawn_delay;
true
} else {
false
}
}
/// The client copy received an update tag (`load`): its delay follows.
pub fn client_loaded(&mut self) {
self.client_delay = self.spawn_delay;
}
/// `TrialSpawnerRenderer.extractSpawnerData`: the spin in degrees and
/// the scale of a display mob of the given size.
pub fn display_pose(&self, alpha: f32, width: f32, height: f32) -> (f32, f32) {
let spin = (self.o_spin + f64::from(alpha) * (self.spin - self.o_spin)) as f32 * 10.0;
let longest = width.max(height);
let scale = if longest > 1.0 {
0.53125 / longest
} else {
0.53125
};
(spin, scale)
}
}
/// `Entity.setPos` of a fresh mob: a shulker sits at the centre of its block.
pub fn entity_position(s: Species, at: [f64; 3]) -> [f64; 3] {
if s == Species::Shulker {
[
at[0].floor() + 0.5,
(at[1] + 0.5).floor(),
at[2].floor() + 0.5,
]
} else {
at
}
}
/// `Vec3.CODEC`: a list of three doubles.
fn read_pos(tag: Option<&Tag>) -> Option<[f64; 3]> {
let Tag::List(v) = tag? else {
return None;
};
if v.len() != 3 {
return None;
}
let mut out = [0.0; 3];
for (o, t) in out.iter_mut().zip(v) {
*o = match t {
Tag::Double(b) => f64::from_bits(*b),
Tag::Float(b) => f64::from(f32::from_bits(*b)),
_ => return None,
};
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_core::random::LegacyRandom;
fn tag(snbt: &str) -> Tag {
horizon_world::nbt::parse_snbt(snbt).expect("snbt").0
}
#[test]
fn load_without_potentials_shares_the_next_data() {
let mut s = Spawner::load(&tag("{SpawnData:{entity:{id:\"zombie\"}}}"));
assert_eq!(s.potentials.len(), 1);
assert_eq!(
s.next_data().and_then(SpawnData::id).as_deref(),
Some("minecraft:zombie")
);
let mut events = Vec::new();
s.set_entity_id("minecraft:skeleton", &mut LegacyRandom::new(0), &mut events);
assert!(events.is_empty());
assert_eq!(
s.potentials[0].0.id().as_deref(),
Some("minecraft:skeleton")
);
}
#[test]
fn generated_spawner_keeps_no_potentials() {
let s = Spawner::load(&tag(
"{SpawnData:{entity:{id:\"minecraft:cave_spider\"}},SpawnPotentials:[]}",
));
assert!(s.potentials.is_empty());
let saved = Tag::compound(s.save());
assert_eq!(saved.get("SpawnPotentials"), Some(&Tag::List(Vec::new())));
assert_eq!(saved.get("Delay"), Some(&Tag::Short(20)));
}
#[test]
fn invalid_ids_are_removed() {
let d = SpawnData::new(
match tag("{id:\"Zombie\"}") {
Tag::Compound(c) => c,
_ => unreachable!(),
},
None,
None,
);
assert!(d.id().is_none());
assert_eq!(normalize_id(":pig").as_deref(), Some("minecraft:pig"));
}
#[test]
fn light_limits_decode_and_encode() {
assert_eq!(light_limit(Some(&tag("7"))), Some((7, 7)));
assert_eq!(light_limit(Some(&tag("[I;0,7]"))), Some((0, 7)));
assert_eq!(
light_limit(Some(&tag("{min_inclusive:2,max_inclusive:9}"))),
Some((2, 9))
);
assert_eq!(light_limit(Some(&tag("[I;9,2]"))), None);
assert_eq!(encode_range((3, 3)), Tag::Int(3));
}
}
+25 -1
View File
@@ -72,7 +72,7 @@ pub const SECTIONS: &[Section] = &[
},
Section {
name: "Controls",
blurb: "Keys, the mouse and how movement keys behave.",
blurb: "Keys, the mouse, controllers and how movement keys behave.",
rows: |_| {
let mut r = vec![HRow::Page(
"Key binds",
@@ -91,6 +91,26 @@ pub const SECTIONS: &[Section] = &[
);
r.push(HRow::Header("Movement"));
r.extend([Opt::ToggleCrouch, Opt::ToggleSprint, Opt::AutoJump].map(HRow::Opt));
r.push(HRow::Header("Controller"));
r.push(HRow::Page(
"Controller binds",
"Every action and its button",
Page::PadBinds,
));
r.extend(
[
Opt::PadEnabled,
Opt::PadVibration,
Opt::PadLookSensitivity,
Opt::PadToggleSneak,
Opt::PadInvertX,
Opt::PadInvertY,
Opt::PadMoveDeadzone,
Opt::PadLookDeadzone,
Opt::PadGlyphs,
]
.map(HRow::Opt),
);
r
},
},
@@ -185,6 +205,10 @@ fn switch_value(opt: Opt, s: &Settings) -> Option<bool> {
Opt::ShowSubtitles => s.show_subtitles,
Opt::ForceUnicode => s.force_unicode,
Opt::JapaneseGlyphs => s.japanese_glyphs,
Opt::PadEnabled => s.controller.enabled,
Opt::PadVibration => s.controller.vibration,
Opt::PadInvertX => s.controller.invert_x,
Opt::PadInvertY => s.controller.invert_y,
_ => return None,
})
}
+343 -23
View File
@@ -3,6 +3,7 @@
//! Language and Resource Packs, laid out like vanilla's HeaderAndFooter /
//! OptionsList screens and drawn with the shared widgets.
use crate::{
gamepad::{self, GlyphStyle},
hud::{HudAtlas, HudBatch, rgba},
keybinds::{self, CATEGORIES, KeyBinds, MAPPINGS},
lang::{self, LanguageInfo},
@@ -67,6 +68,16 @@ pub enum Opt {
NotificationDisplayTime,
ForceUnicode,
JapaneseGlyphs,
/// Horizon's controller settings (`horizon-controller.txt`).
PadEnabled,
PadVibration,
PadLookSensitivity,
PadInvertX,
PadInvertY,
PadToggleSneak,
PadMoveDeadzone,
PadLookDeadzone,
PadGlyphs,
}
fn tr(key: &str) -> Text {
Text::translate(key, &[])
@@ -153,6 +164,16 @@ impl Opt {
Opt::NotificationDisplayTime => "options.notifications.display_time",
Opt::ForceUnicode => "options.forceUnicodeFont",
Opt::JapaneseGlyphs => "options.japaneseGlyphVariants",
// Horizon's own options: English captions (no vanilla keys).
Opt::PadEnabled => "Controller",
Opt::PadVibration => "Vibration",
Opt::PadLookSensitivity => "Look Sensitivity",
Opt::PadInvertX => "Invert Look X",
Opt::PadInvertY => "Invert Look Y",
Opt::PadToggleSneak => "Sneak Button",
Opt::PadMoveDeadzone => "Move Deadzone",
Opt::PadLookDeadzone => "Look Deadzone",
Opt::PadGlyphs => "Button Glyphs",
}
}
pub(crate) fn kind(self, s: &Settings) -> Kind {
@@ -187,6 +208,9 @@ impl Opt {
Opt::ChatHeightFocused => Kind::Slider(s.chat_height_focused),
Opt::ChatHeightUnfocused => Kind::Slider(s.chat_height_unfocused),
Opt::ChatLineSpacing => Kind::Slider(s.chat_line_spacing),
Opt::PadLookSensitivity => Kind::Slider(s.controller.look_sensitivity),
Opt::PadMoveDeadzone => unit(s.controller.move_deadzone, 0.0, 0.5),
Opt::PadLookDeadzone => unit(s.controller.look_deadzone, 0.0, 0.5),
_ => Kind::Cycle,
}
}
@@ -313,6 +337,21 @@ impl Opt {
&[&format!("{:.1}", s.notification_display_time)],
),
),
Opt::PadLookSensitivity => percent(c, 2.0 * s.controller.look_sensitivity),
Opt::PadMoveDeadzone | Opt::PadLookDeadzone => {
let v = if self == Opt::PadMoveDeadzone {
s.controller.move_deadzone
} else {
s.controller.look_deadzone
};
Text::translate(
"options.percent_value",
&[
tr(c),
Text::literal(((v * 100.0).round() as i32).to_string()),
],
)
}
_ => generic(c, self.value_text(s)),
}
}
@@ -378,6 +417,21 @@ impl Opt {
Opt::ShowSubtitles => on_off(s.show_subtitles),
Opt::ForceUnicode => on_off(s.force_unicode),
Opt::JapaneseGlyphs => on_off(s.japanese_glyphs),
Opt::PadEnabled => on_off(s.controller.enabled),
Opt::PadVibration => on_off(s.controller.vibration),
Opt::PadInvertX => on_off(s.controller.invert_x),
Opt::PadInvertY => on_off(s.controller.invert_y),
Opt::PadToggleSneak => tr(if s.controller.toggle_sneak {
"options.key.toggle"
} else {
"options.key.hold"
}),
Opt::PadGlyphs => Text::literal(match s.controller.glyphs {
GlyphStyle::Auto => "Auto",
GlyphStyle::Xbox => "Xbox",
GlyphStyle::PlayStation => "PlayStation",
GlyphStyle::Nintendo => "Nintendo",
}),
_ => Text::empty(),
}
}
@@ -411,6 +465,9 @@ impl Opt {
Opt::ChatHeightFocused => s.chat_height_focused = v,
Opt::ChatHeightUnfocused => s.chat_height_unfocused = v,
Opt::ChatLineSpacing => s.chat_line_spacing = v,
Opt::PadLookSensitivity => s.controller.look_sensitivity = v,
Opt::PadMoveDeadzone => s.controller.move_deadzone = step(0.0, 50.0) / 100.0,
Opt::PadLookDeadzone => s.controller.look_deadzone = step(0.0, 50.0) / 100.0,
_ => {}
}
if self.affects_preset() {
@@ -484,6 +541,18 @@ impl Opt {
Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles,
Opt::ForceUnicode => s.force_unicode = !s.force_unicode,
Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs,
Opt::PadEnabled => s.controller.enabled = !s.controller.enabled,
Opt::PadVibration => s.controller.vibration = !s.controller.vibration,
Opt::PadInvertX => s.controller.invert_x = !s.controller.invert_x,
Opt::PadInvertY => s.controller.invert_y = !s.controller.invert_y,
Opt::PadToggleSneak => s.controller.toggle_sneak = !s.controller.toggle_sneak,
Opt::PadGlyphs => {
let i = GlyphStyle::ALL
.iter()
.position(|g| *g == s.controller.glyphs)
.unwrap_or(0) as u8;
s.controller.glyphs = GlyphStyle::ALL[usize::from(next(i, 4))];
}
_ => {}
}
if self.affects_preset() {
@@ -542,6 +611,9 @@ pub enum Page {
/// Horizon's graphics settings (`graphics_ui`).
Graphics,
GraphicsAdvanced,
/// Horizon's controller settings and button binds.
Controller,
PadBinds,
}
#[derive(Clone, Debug, PartialEq)]
enum Act {
@@ -552,6 +624,10 @@ enum Act {
Key(&'static str),
ResetKey(&'static str),
ResetKeys,
/// Controller binds: wait for a button, reset one, reset all.
PadKey(&'static str),
ResetPadKey(&'static str),
ResetPadKeys,
/// Back to Horizon's own menus (Horizon only, see `list_rows`).
HorizonMenus,
}
@@ -612,6 +688,10 @@ pub struct OptionsUi {
pub(crate) hdragging: Option<crate::graphics_ui::Item>,
/// Key Binds: the mapping waiting for a key.
pub selected_key: Option<&'static str>,
/// Controller Binds: the action waiting for a pad button.
pub selected_pad_action: Option<&'static str>,
/// The glyphs the binds list shows (the setting, else the pad's family).
pub pad_style: GlyphStyle,
pub languages: Vec<LanguageInfo>,
language_choice: Option<String>,
language_search: ui::EditBox,
@@ -640,6 +720,8 @@ impl Default for OptionsUi {
hscroll: 0.0,
hdragging: None,
selected_key: None,
selected_pad_action: None,
pad_style: GlyphStyle::Xbox,
languages: Vec::new(),
language_choice: None,
language_search: search,
@@ -759,6 +841,8 @@ impl OptionsUi {
Page::Font => "options.font.title",
Page::Packs => "resourcePack.title",
Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle",
Page::Controller => "Controller Settings",
Page::PadBinds => "Controller Binds",
}
}
fn list_rows(&self, s: &Settings) -> Vec<Row> {
@@ -863,6 +947,41 @@ impl OptionsUi {
Opt::ToggleSprint,
Opt::AutoJump,
]));
// Horizon's controller page, after vanilla's rows.
rows.push(Row::Buttons(
button(
0.0,
0.0,
310.0,
Text::literal("Controller Settings..."),
Act::Push(Page::Controller),
),
None,
));
rows
}
Page::Controller => {
let mut rows = vec![Row::Buttons(
button(
0.0,
0.0,
310.0,
Text::literal("Controller Binds..."),
Act::Push(Page::PadBinds),
),
None,
)];
rows.extend(pairs(&[
Opt::PadEnabled,
Opt::PadVibration,
Opt::PadLookSensitivity,
Opt::PadToggleSneak,
Opt::PadInvertX,
Opt::PadInvertY,
Opt::PadMoveDeadzone,
Opt::PadLookDeadzone,
Opt::PadGlyphs,
]));
rows
}
Page::Mouse => pairs(&[
@@ -906,13 +1025,7 @@ impl OptionsUi {
}
}
/// Build every widget of the current page.
fn layout(
&mut self,
s: &Settings,
atlas: &HudAtlas,
w: f32,
h: f32,
) -> (Vec<Widget>, f32, f32, f32) {
fn layout(&mut self, s: &Settings, w: f32, h: f32) -> (Vec<Widget>, f32, f32, f32) {
let mut out = Vec::new();
let page = self.page();
let cx = (w / 2.0).floor();
@@ -993,12 +1106,13 @@ impl OptionsUi {
for (name, category) in mappings {
if category != last_category {
last_category = category;
let label = Text::translate(&format!("key.categories.{category}"), &[])
.with_style(&Style {
bold: Some(true),
underlined: Some(true),
..Style::default()
});
let label =
Text::translate(&format!("key.category.minecraft.{category}"), &[])
.with_style(&Style {
bold: Some(true),
underlined: Some(true),
..Style::default()
});
out.push(Widget {
x: 0.0,
y: y + 7.0,
@@ -1087,6 +1201,88 @@ impl OptionsUi {
));
out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done));
}
Page::PadBinds => {
out.push(Widget {
x: 0.0,
y: 12.0,
w,
h: 9.0,
kind: WKind::Text {
text: tr(Self::title(page)),
color: u32::MAX,
centered: true,
},
list: false,
});
let row_left = cx - 170.0;
let scrollbar_x = row_left + 340.0 + 6.0 + 2.0;
let list_start = out.len();
let mut y = top + 2.0 - self.scroll;
let pad = &s.controller;
for (action, _) in gamepad::ACTIONS {
out.push(Widget {
x: row_left + 2.0,
y: y + 6.0,
w: 200.0,
h: 9.0,
kind: WKind::Text {
text: tr(gamepad::action_caption(action)),
color: u32::MAX,
centered: false,
},
list: false,
});
let mut message = match pad.binding(action) {
Some(b) => {
let [r, g, bl] = b.color(self.pad_style);
Text::literal(b.label(self.pad_style))
.with_color(u32::from(r) << 16 | u32::from(g) << 8 | u32::from(bl))
}
None => tr("key.keyboard.unknown"),
};
if pad.conflicts(action) {
message = Text::literal("[ ")
.append(message)
.append(" ]")
.with_color(text::YELLOW);
}
if self.selected_pad_action == Some(*action) {
message = Text::literal("> ")
.append(message.with_style(&Style {
underlined: Some(true),
..Style::default()
}))
.append(" <")
.with_color(text::YELLOW);
}
let reset_x = scrollbar_x - 50.0 - 10.0;
let change_x = reset_x - 5.0 - 75.0;
out.push(button(change_x, y, 75.0, message, Act::PadKey(action)));
let reset = button(
reset_x,
y,
50.0,
tr("controls.reset"),
Act::ResetPadKey(action),
);
out.push(if pad.is_default(action) {
inactive(reset)
} else {
reset
});
y += 20.0;
}
content = y + self.scroll - top + 2.0;
out[list_start..].iter_mut().for_each(|w| w.list = true);
out.push(button(
cx - 154.0,
h - 27.0,
150.0,
tr("controls.resetAll"),
Act::ResetPadKeys,
));
out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done));
}
Page::Language => {
top = 36.0;
bottom = h - 53.0;
@@ -1234,7 +1430,15 @@ impl OptionsUi {
out.push(done(h - 27.0));
}
}
let _ = atlas;
// Layout may change the offset (language centering), or the list may
// shrink after a resize/search. Correct the rows in this same frame.
let previous_scroll = self.scroll;
self.clamp_scroll(top, bottom, content);
for widget in &mut out {
if widget.list {
widget.y += previous_scroll - self.scroll;
}
}
(out, top, bottom, content)
}
fn clamp_scroll(&mut self, top: f32, bottom: f32, content: f32) {
@@ -1267,8 +1471,7 @@ impl OptionsUi {
crate::screen_draw::paint(batch, atlas, &draws);
return;
}
let (widgets, top, bottom, content) = self.layout(s, atlas, w, h);
self.clamp_scroll(top, bottom, content);
let (widgets, top, bottom, content) = self.layout(s, w, h);
let in_world = self.in_world;
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world);
let list = bottom > top;
@@ -1371,7 +1574,7 @@ impl OptionsUi {
if list {
ui::separators(batch, atlas, top, bottom, in_world);
let sx = match self.page() {
Page::KeyBinds => (w / 2.0).floor() + 170.0 + 8.0,
Page::KeyBinds | Page::PadBinds => (w / 2.0).floor() + 170.0 + 8.0,
Page::Language => (w / 2.0).floor() + 110.0 + 8.0,
_ => (w / 2.0).floor() + 155.0 + 8.0,
};
@@ -1451,7 +1654,7 @@ impl OptionsUi {
}
return events;
}
let (widgets, top, bottom, _) = self.layout(s, atlas, size.0, size.1);
let (widgets, top, bottom, _) = self.layout(s, size.0, size.1);
let mut events = Vec::new();
if drag {
if let Some(opt) = self.dragging
@@ -1464,6 +1667,10 @@ impl OptionsUi {
}
return events;
}
// Controller Binds: a click cancels the wait.
if self.selected_pad_action.take().is_some() {
return events;
}
// Key Binds: a mouse button pressed while waiting binds it.
if let Some(name) = self.selected_key.take() {
let button = if right {
@@ -1504,6 +1711,16 @@ impl OptionsUi {
s.keys.reset_all();
events.push(Event::Changed);
}
Act::PadKey(action) => self.selected_pad_action = Some(action),
Act::ResetPadKey(action) => {
s.controller
.bind(action, gamepad::PadSettings::default_of(action));
events.push(Event::Changed);
}
Act::ResetPadKeys => {
s.controller.reset_bindings();
events.push(Event::Changed);
}
Act::HorizonMenus => {
self.horizon_menus();
if let Ok(dir) = std::env::current_dir() {
@@ -1551,24 +1768,26 @@ impl OptionsUi {
self.hdragging = None;
self.graphics.release();
}
pub fn scroll(&mut self, amount: f32) {
pub fn scroll(&mut self, s: &Settings, size: (f32, f32), amount: f32) {
let (_, top, bottom, content) = self.layout(s, size.0, size.1);
self.scroll -= amount * 18.0;
self.clamp_scroll(top, bottom, content);
}
/// The mouse wheel at the cursor.
pub fn scroll_at(&mut self, cursor: (f32, f32), amount: f32) {
pub fn scroll_at(&mut self, s: &Settings, size: (f32, f32), cursor: (f32, f32), amount: f32) {
if crate::ui_theme::horizon() && self.page() == Page::Main {
self.scroll_horizon(amount);
return;
}
if Self::graphics_level(self.page()).is_some() {
self.graphics.scroll(amount);
if let Some(level) = Self::graphics_level(self.page()) {
self.graphics.scroll(level, size.1, amount);
return;
}
match &mut self.pack_screen {
Some(p) if self.stack.last() == Some(&Page::Packs) => {
p.scroll(cursor.0 as f64, cursor.1 as f64, amount as f64)
}
_ => self.scroll(amount),
_ => self.scroll(s, size, amount),
}
}
/// The pack screen at this GUI size, made on first use.
@@ -1602,6 +1821,7 @@ impl OptionsUi {
self.scroll = 0.0;
self.dragging = None;
self.selected_key = None;
self.selected_pad_action = None;
match page {
Page::Language => {
if let Some(code) = self.language_choice.take()
@@ -1694,6 +1914,13 @@ impl OptionsUi {
_ => {}
}
}
if let Some(action) = self.selected_pad_action.take() {
// As on Key Binds, Escape unbinds; other keys cancel.
if key == K::Escape {
s.controller.bind(action, None);
}
return vec![Event::Changed];
}
if let Some(name) = self.selected_key.take() {
// KeyBindsScreen.keyPressed: Escape unbinds.
let value = if key == K::Escape {
@@ -1729,6 +1956,99 @@ mod tests {
use super::*;
use crate::ui_theme::{MenuStyle, set_style, style};
fn languages() -> Vec<LanguageInfo> {
(0..30)
.map(|i| LanguageInfo {
code: format!("language_{i}"),
name: format!("Language {i}"),
region: String::new(),
bidirectional: false,
})
.collect()
}
#[test]
fn classic_scroll_stops_at_both_limits_before_layout() {
let s = Settings::default();
let size = (480.0, 120.0);
for page in [Page::KeyBinds, Page::Chat, Page::Sound, Page::Language] {
let mut ui = OptionsUi {
languages: languages(),
..Default::default()
};
ui.show(page);
let (_, top, bottom, content) = ui.layout(&s, size.0, size.1);
let max = content - (bottom - top);
assert!(max > 4.5, "{page:?}");
for _ in 0..3 {
ui.scroll_at(&s, size, (240.0, 60.0), 1000.0);
assert_eq!(ui.scroll, 0.0, "{page:?}");
}
for _ in 0..3 {
ui.scroll_at(&s, size, (240.0, 60.0), -1000.0);
assert_eq!(ui.scroll, max, "{page:?}");
}
ui.scroll_at(&s, size, (240.0, 60.0), 0.25);
assert_eq!(ui.scroll, max - 4.5, "{page:?}");
ui.scroll_at(&s, size, (240.0, 60.0), 1000.0);
ui.scroll_at(&s, size, (240.0, 60.0), -0.25);
assert_eq!(ui.scroll, 4.5, "{page:?}");
}
}
#[test]
fn classic_pages_without_overflow_do_not_scroll() {
let s = Settings::default();
for page in [Page::Main, Page::Font, Page::Mouse] {
let mut ui = OptionsUi::default();
ui.show(page);
for amount in [-1000.0, 1000.0, -0.25] {
ui.scroll(&s, (480.0, 720.0), amount);
assert_eq!(ui.scroll, 0.0, "{page:?}");
}
}
}
#[test]
fn classic_resize_positions_rows_at_the_clamped_offset() {
let s = Settings::default();
let mut ui = OptionsUi::default();
ui.show(Page::KeyBinds);
ui.scroll(&s, (480.0, 120.0), -1000.0);
assert!(ui.scroll > 0.0);
let (widgets, _, _, _) = ui.layout(&s, 480.0, 4000.0);
assert_eq!(ui.scroll, 0.0);
let (expected, _, _, _) = ui.layout(&s, 480.0, 4000.0);
assert_eq!(
widgets.iter().map(|w| w.y).collect::<Vec<_>>(),
expected.iter().map(|w| w.y).collect::<Vec<_>>()
);
}
#[test]
fn language_centering_and_filtering_use_bounded_row_positions() {
let s = Settings {
language: "language_29".into(),
..Default::default()
};
let mut ui = OptionsUi {
languages: languages(),
..Default::default()
};
ui.show(Page::Language);
let (widgets, top, bottom, content) = ui.layout(&s, 480.0, 240.0);
assert_eq!(ui.scroll, content - (bottom - top));
let (expected, _, _, _) = ui.layout(&s, 480.0, 240.0);
assert_eq!(
widgets.iter().map(|w| w.y).collect::<Vec<_>>(),
expected.iter().map(|w| w.y).collect::<Vec<_>>()
);
ui.language_search.set_value("language_29");
let (widgets, top, _, _) = ui.layout(&s, 480.0, 240.0);
assert_eq!(ui.scroll, 0.0);
assert_eq!(widgets.iter().find(|w| w.list).unwrap().y, top + 2.0);
}
#[test]
fn classic_video_settings_lead_back_to_horizon_menus() {
let s = Settings::default();
+102
View File
@@ -0,0 +1,102 @@
//! OverlayTexture: the hurt red and white flash entity.wgsl mixes over a lit
//! entity before the lightmap (entity.fsh), and the overlay codes models carry.
//!
//! Vanilla's 16 by 16 texture: rows 0 to 7 are the hurt red, row 10 is white
//! with an alpha falling with u; LivingEntityRenderer.getOverlayCoords picks
//! u from the white overlay progress and row 3 when the entity is hurt.
/// The overlay code of white flashes: `WHITE + u`, u in 1..=15.
pub const WHITE: u32 = 16;
/// The hurt red (rows 0 to 7) as RGBA bytes: 0xB2FF0000.
pub const HURT_TEXEL: [u8; 4] = [255, 0, 0, 0xB2];
/// The white row's alpha at column u: `(int) ((1 - u / 15 * 0.75) * 255)`
/// in float precision.
pub fn white_alpha(u: u32) -> u8 {
((1.0f32 - u as f32 / 15.0 * 0.75) * 255.0) as u8
}
/// OverlayTexture.u: the column of a white overlay progress.
pub fn white_column(progress: f32) -> u32 {
(progress * 15.0) as u32
}
/// LivingEntityRenderer.getOverlayCoords as entity.wgsl's overlay code: the
/// red row hides the white column; column 0 of the white row is opaque white
/// with full alpha, so no overlay.
pub fn living(white_progress: f32, red: bool) -> u32 {
if red {
return 1;
}
match white_column(white_progress) {
0 => 0,
u => WHITE + u.min(15),
}
}
/// CreeperRenderer.getWhiteOverlayProgress: flashing every other tenth of
/// the swelling, at least half white.
pub fn creeper_progress(swelling: f32) -> f32 {
if (swelling * 10.0) as i32 % 2 == 0 {
0.0
} else {
swelling.clamp(0.5, 1.0)
}
}
/// The texels as WGSL constants, prepended to entity.wgsl.
pub fn wgsl_constants() -> String {
let [r, g, b, a] = HURT_TEXEL.map(|v| format!("{v}.0 / 255.0"));
let white: Vec<String> = (0..16)
.map(|u| format!("{}.0 / 255.0", white_alpha(u)))
.collect();
format!(
"// OverlayTexture (overlay.rs): the hurt texel and the white row's alpha by column.\n\
const HURT_OVERLAY = vec4({r}, {g}, {b}, {a});\n\
const WHITE_OVERLAY_ALPHA = array<f32, 16>({});\n",
white.join(", ")
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn texels_are_vanilla_s() {
// OverlayTexture's constructor, printed by the 26.3 JVM.
let vanilla = [
255, 242, 229, 216, 203, 191, 178, 165, 152, 140, 127, 114, 101, 89, 76, 63,
];
assert_eq!((0..16).map(white_alpha).collect::<Vec<_>>(), vanilla);
assert_eq!(
u32::from_be_bytes([HURT_TEXEL[3], HURT_TEXEL[0], HURT_TEXEL[1], HURT_TEXEL[2]]),
0xB2FF_0000
);
}
#[test]
fn creeper_flashes_like_vanilla() {
// (swelling, OverlayTexture.u(getWhiteOverlayProgress)) from the JVM.
let vanilla = [
(0.05, 0),
(0.1, 7),
(0.19, 7),
(0.2, 0),
(0.3, 7),
(0.49, 0),
(0.5, 7),
(0.55, 8),
(0.7, 10),
(0.75, 11),
(0.95, 14),
(1.0, 0),
];
for (swelling, u) in vanilla {
assert_eq!(white_column(creeper_progress(swelling)), u, "{swelling}");
}
assert_eq!(living(creeper_progress(0.55), false), WHITE + 8);
assert_eq!(living(creeper_progress(0.55), true), 1);
assert_eq!(living(0.0, false), 0);
}
}
+2
View File
@@ -466,6 +466,7 @@ pub fn encode_block_entity(
entries.push(("creaking", uuid_tag(uuid)));
}
}
BlockEntity::Spawner(s) => entries.extend(s.save()),
}
Tag::compound(entries)
}
@@ -588,6 +589,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_) => {}
BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag),
}
Some((pos, entity))
}
+11
View File
@@ -177,6 +177,8 @@ pub struct Settings {
pub sprint_window: i32,
/// Horizon's own graphics settings (`horizon-graphics.txt`, not options.txt).
pub horizon: crate::graphics::Graphics,
/// Controller settings (`horizon-controller.txt`, Horizon's own).
pub controller: crate::gamepad::PadSettings,
}
impl Default for Settings {
fn default() -> Self {
@@ -246,6 +248,7 @@ impl Default for Settings {
toggle_use: false,
sprint_window: 7,
horizon: Default::default(),
controller: Default::default(),
}
}
}
@@ -280,13 +283,19 @@ impl Settings {
.parent()
.map(crate::graphics::Graphics::load)
.unwrap_or_default();
let controller = path
.parent()
.map(crate::gamepad::PadSettings::load)
.unwrap_or_default();
let settings = match fs::read(path) {
Ok(bytes) => Self {
horizon,
controller,
..Self::parse(&String::from_utf8_lossy(&bytes))
},
Err(_) => Self {
horizon,
controller,
..Self::default()
},
};
@@ -385,6 +394,7 @@ impl Settings {
toggle_use: f.bool("toggleUse"),
sprint_window: f.int("sprintWindow"),
horizon: Default::default(),
controller: Default::default(),
auto_jump: f.bool("autoJump"),
language: f.string("lang"),
force_unicode: f.bool("forceUnicodeFont"),
@@ -517,6 +527,7 @@ impl Settings {
let _ = fs::write(path, self.serialize());
if let Some(dir) = path.parent() {
self.horizon.save(dir);
self.controller.save(dir);
}
}
/// Volume of a sound source (master excluded).
+20 -1
View File
@@ -11,10 +11,29 @@ pub struct Keys {
pub jump: bool,
pub shift: bool,
pub sprint: bool,
/// A controller stick's move vector (`[left, forward]`, Horizon's own),
/// used instead of the keys' direction while it is pushed.
pub analog: Option<[f32; 2]>,
}
impl Keys {
pub fn direction(self) -> [f32; 2] {
input::keyboard_direction(self.forward, self.backward, self.left, self.right)
match self.analog {
Some(v) => v,
None => input::keyboard_direction(self.forward, self.backward, self.left, self.right),
}
}
/// Add a stick's move vector: the direction flags code reading keys
/// (sprint, vehicles, the server's input packet) see are set past a
/// third of the travel.
pub fn with_stick(mut self, stick: Option<[f32; 2]>) -> Self {
if let Some([left, forward]) = stick {
self.forward |= forward > 0.3;
self.backward |= forward < -0.3;
self.left |= left > 0.3;
self.right |= left < -0.3;
self.analog = Some([left, forward]);
}
self
}
}
#[derive(Clone, Copy, Debug, Default)]
@@ -44,6 +44,10 @@ pub fn block_entities(
let Some(mut entity) = BlockEntity::for_block(block) else {
continue;
};
// MonsterRoomFeature and the structures' setEntityId.
if let BlockEntity::Spawner(s) = &mut entity {
**s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone()));
}
if let (BlockEntity::Chest(slots), Some(table), Some(loot)) =
(&mut entity, text(nbt, "LootTable"), loot)
{
+5 -5
View File
@@ -43,7 +43,7 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> {
}
@vertex fn vs_terrain(
@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>,
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>,
@location(5) origin: vec4<f32>) -> TerrainOut {
let pos = position + origin.xyz;
var out: TerrainOut;
@@ -66,13 +66,13 @@ fn apply_fog(color: vec4<f32>, spherical: f32, cylindrical: f32) -> vec4<f32> {
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
}
@fragment fn fs_solid(in: TerrainOut) -> @location(0) vec4<f32> {
// Bit 31 of the layer marks opaque leaves (forceOpaque): no alpha cutout.
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color;
if color.a < 0.5 && (in.layer & 0x80000000u) == 0u { discard; }
// Bit 15 of the layer marks opaque leaves (forceOpaque): no alpha cutout.
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffu)) * in.color;
if color.a < 0.5 && (in.layer & 0x8000u) == 0u { discard; }
return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical);
}
@fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4<f32> {
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color;
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffu)) * in.color;
if color.a < 0.01 { discard; }
return apply_fog(color, in.spherical, in.cylindrical);
}
+4
View File
@@ -283,6 +283,10 @@ pub fn slider(
hover: bool,
active: bool,
) {
if active {
// A controller's D-pad can focus it (Horizon's controller support).
crate::widgets::target([x, y, w, 20.0]);
}
let track = if hover && active {
"gui/sprites/widget/slider_highlighted"
} else {
+6
View File
@@ -521,6 +521,12 @@ impl<'a> Ui<'a> {
/// Register an interactive rectangle; returns its hover layer (0..1,
/// eased over `QUICK` like the launcher's `hover_layer`).
pub fn interact(&mut self, id: u64, x: f32, y: f32, w: f32, h: f32, enabled: bool) -> f32 {
if enabled && self.real {
// Where a controller's D-pad can move focus, in GUI pixels.
let k = self.density / self.scale;
let (ox, oy) = self.offset;
crate::widgets::target([(x + ox) * k, (y + oy) * k, w * k, h * k]);
}
if enabled {
let (ox, oy) = self.offset;
self.hits.push(Hit {
+19
View File
@@ -17,6 +17,24 @@ pub struct Widget {
thread_local! {
/// Buttons drawn since the last `end_frame`, and the last frame's.
static WIDGETS: RefCell<(Vec<Widget>, Vec<Widget>, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) };
/// Every interactive rectangle of Horizon-style menus (sidebar items,
/// switches, sliders, segments), labelled or not: where a controller's
/// D-pad can move focus. Drawn since `end_frame`, and the last frame's.
static TARGETS: RefCell<(Vec<[f32; 4]>, Vec<[f32; 4]>)> = const { RefCell::new((Vec::new(), Vec::new())) };
}
/// An interactive rectangle (GUI pixels) a controller can focus.
pub fn target(rect: [f32; 4]) {
TARGETS.with_borrow_mut(|(current, _)| {
if current.len() < 1024 {
current.push(rect);
}
});
}
/// The focus targets of the last drawn frame.
pub fn last_targets() -> Vec<[f32; 4]> {
TARGETS.with_borrow(|(_, last)| last.clone())
}
/// Called by the button drawers.
@@ -46,6 +64,7 @@ pub fn end_frame(frames: u64) {
if *seen != frames {
*seen = frames;
*last = std::mem::take(current);
TARGETS.with_borrow_mut(|(current, last)| *last = std::mem::take(current));
}
});
}
+8 -3
View File
@@ -22,6 +22,11 @@ fn hint(text: &str, version: &str) -> String {
text.replace("{version}", version)
}
/// What to do when the player's launcher install lacks the pinned version's files.
pub(crate) fn launcher_hint(version: &str) -> String {
hint(LAUNCHER_HINT, version)
}
/// research-lock.json and the folder the pinned version's files go to.
pub struct Lock {
pub json: Value,
@@ -120,7 +125,7 @@ pub fn minecraft_dir(chosen: Option<&Path>) -> PathBuf {
/// Copy one file from the player's install, checked like a download; an existing verified
/// copy is kept.
fn import_copy(
pub(crate) fn import_copy(
source: &Path,
destination: &Path,
checksum: &str,
@@ -156,7 +161,7 @@ fn import_copy(
/// The pinned version JSON from the launcher's versions/ directory. The launcher's copy wins
/// over the cached one so the manifest matches the asset index installed alongside it.
fn import_manifest(lock: &Lock, minecraft: &Path) -> Result<Value, String> {
pub(crate) fn import_manifest(lock: &Lock, minecraft: &Path) -> Result<Value, String> {
let version = &lock.version;
let destination = lock.directory.join("manifest.json");
let source = minecraft
@@ -355,7 +360,7 @@ fn client_library_artifacts(manifest: &Value) -> Result<Vec<&Value>, String> {
}
/// A relative path with only normal components and forward slashes, from a manifest or bundle.
fn safe_relative(path: &str) -> Option<PathBuf> {
pub(crate) fn safe_relative(path: &str) -> Option<PathBuf> {
if path.contains('\\') || path.starts_with('/') {
return None;
}
+3
View File
@@ -14,8 +14,11 @@ pub mod artifacts;
mod inventory;
pub mod java;
pub mod pyjson;
mod sounds;
mod survival;
pub use sounds::sounds;
use pyjson::Value;
use sha2::Digest;
use std::fs;
+16 -2
View File
@@ -9,6 +9,7 @@ const HELP: &str = "\
horizon-prepare: prepare Horizon's resources from your own Minecraft Java Edition
Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [--root PATH]
horizon-prepare sounds [--minecraft-dir PATH] [--root PATH]
--prepare Import the pinned game files from your own copy first
--server-jar PATH The pinned server jar you downloaded yourself
@@ -21,6 +22,10 @@ Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [-
Needs Minecraft played once from the official launcher, and Java (a JDK) of the version
research-lock.json pins: JAVA_HOME, else javac and java on the PATH.
The resources go to <root>/.local/horizon-client/<version>; pass that to horizon-client --resources.
horizon-prepare sounds copies the pinned version's sounds (about 380 MB) from the official
launcher's asset store into the same folder, checking every file. It is optional: without it the
game is silent. Nothing is downloaded; it needs the version played once from the official launcher.
";
/// The folder with research-lock.json: beside the executable in a release folder, else the
@@ -46,7 +51,8 @@ fn main() -> ExitCode {
server_jar: None,
};
let mut root = None;
let mut args = std::env::args_os().skip(1);
let mut args = std::env::args_os().skip(1).peekable();
let sounds = args.next_if(|a| a == "sounds").is_some();
while let Some(arg) = args.next() {
let text = arg.to_string_lossy().into_owned();
let (flag, inline) = match text.split_once('=') {
@@ -65,6 +71,9 @@ fn main() -> ExitCode {
}
};
let parsed = match flag.as_str() {
"--prepare" | "--server-jar" if sounds => {
Err(format!("{flag} is for preparing, not for sounds"))
}
"--prepare" if inline.is_none() => {
options.import = true;
Ok(())
@@ -99,7 +108,12 @@ fn main() -> ExitCode {
let _ = writeln!(out, "{line}");
let _ = out.flush();
};
match horizon_prepare::prepare(&options, &log) {
let result = if sounds {
horizon_prepare::sounds(&options.root, options.minecraft_dir.as_deref(), &log)
} else {
horizon_prepare::prepare(&options, &log)
};
match result {
Ok(_) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {e}");
+299
View File
@@ -0,0 +1,299 @@
//! The pinned version's sounds (sounds.json and the .ogg files) from the player's own official
//! launcher install, each object checked against the asset index's SHA-1, copied into
//! `.local/horizon-client/<version>/assets` where the game reads them (tools/fetch_sounds.py and
//! the tools/lab.py functions it called). Nothing is downloaded.
use crate::artifacts::{self, Lock};
use crate::pyjson::Value;
use crate::{digest, read_json, Log};
use std::fs;
use std::path::{Path, PathBuf};
/// The launcher's asset directory and the pinned version's verified asset index
/// (tools/lab.py `launcher_assets`).
fn launcher_assets(manifest: &Value, minecraft: &Path) -> Result<(PathBuf, PathBuf), String> {
let assets = minecraft.join("assets");
let info = manifest
.get("assetIndex")
.ok_or("The version JSON has no assetIndex")?;
let field = |key: &str| {
info.get(key)
.and_then(Value::as_str)
.ok_or_else(|| format!("The version JSON's assetIndex has no {key}"))
};
let (id, sha1) = (field("id")?, field("sha1")?);
if artifacts::safe_relative(id).is_none_or(|p| p.components().count() != 1) {
return Err(format!("Unsafe asset index id {id:?}"));
}
let index = assets.join("indexes").join(format!("{id}.json"));
if !index.is_file() {
let version = manifest.get("id").and_then(Value::as_str).unwrap_or("");
return Err(format!(
"Missing {}. {}",
index.display(),
artifacts::launcher_hint(version)
));
}
if digest(&index, "sha1")? != sha1 {
return Err(format!("{} is not the pinned asset index", index.display()));
}
Ok((assets, index))
}
/// Where the launcher's asset store keeps the object with this SHA-1.
fn object_path(assets: &Path, checksum: &str) -> Result<PathBuf, String> {
if checksum.len() != 40 || !checksum.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(format!("Bad asset hash {checksum:?} in the asset index"));
}
Ok(assets.join("objects").join(&checksum[..2]).join(checksum))
}
/// One verified object from the launcher's asset store (tools/lab.py `launcher_object`).
fn launcher_object(assets: &Path, checksum: &str) -> Result<PathBuf, String> {
let path = object_path(assets, checksum)?;
if !path.is_file() {
return Err(format!(
"Missing asset object {}. Play the pinned version once in the official launcher.",
path.display()
));
}
if digest(&path, "sha1")? != checksum {
return Err(format!(
"Corrupt asset object {}; let the launcher repair it",
path.display()
));
}
Ok(path)
}
/// Whether the game plays this asset: sounds.json and everything under sounds/.
fn is_sound(name: &str) -> bool {
name == "minecraft/sounds.json" || name.starts_with("minecraft/sounds/")
}
/// Copies the pinned version's asset index and sounds from the official launcher's game
/// directory (`minecraft`, else HORIZON_MINECRAFT_DIR, else the launcher's own) into `root`'s
/// `.local/horizon-client/<version>`; returns that folder. Files already there with the right
/// SHA-1 are kept.
pub fn sounds(root: &Path, minecraft: Option<&Path>, log: Log) -> Result<PathBuf, String> {
let lock = Lock::read(root)?;
let minecraft = artifacts::minecraft_dir(minecraft);
let manifest = artifacts::import_manifest(&lock, &minecraft)?;
let (store, index) = launcher_assets(&manifest, &minecraft)?;
let id = manifest
.get("id")
.and_then(Value::as_str)
.ok_or("The version JSON has no id")?;
let target = root.join(".local/horizon-client").join(id);
fs::create_dir_all(&target).map_err(|e| format!("{}: {e}", target.display()))?;
fs::copy(&index, target.join("asset-index.json"))
.map_err(|e| format!("{}: {e}", target.join("asset-index.json").display()))?;
let objects = read_json(&index)?;
let objects = objects
.get("objects")
.and_then(Value::as_object)
.ok_or_else(|| format!("{} has no objects", index.display()))?;
// A repeated name keeps its first place and its last value, as a Python dict does.
let mut wanted: Vec<(&str, &Value)> = Vec::new();
for (name, info) in objects.iter().filter(|(name, _)| is_sound(name)) {
match wanted.iter_mut().find(|(n, _)| n == name) {
Some(entry) => entry.1 = info,
None => wanted.push((name, info)),
}
}
let mut total: u64 = 0;
for (name, info) in &wanted {
let hash = info
.get("hash")
.and_then(Value::as_str)
.ok_or_else(|| format!("{name} has no hash in the asset index"))?;
let size = info
.get("size")
.and_then(Value::as_i64)
.and_then(|s| u64::try_from(s).ok())
.ok_or_else(|| format!("{name} has no size in the asset index"))?;
let relative = artifacts::safe_relative(name)
.ok_or_else(|| format!("Unsafe asset name {name:?} in the asset index"))?;
let source = launcher_object(&store, hash)?;
artifacts::import_copy(
&source,
&target.join("assets").join(relative),
hash,
"sha1",
"",
)?;
total += size;
}
log(&format!(
"Sound assets ready: {} files, {:.1} MB",
wanted.len(),
total as f64 / 1e6
));
Ok(target)
}
#[cfg(test)]
mod tests {
use super::*;
use sha1::Digest;
fn sha1_hex(data: &[u8]) -> String {
crate::hex(&sha1::Sha1::digest(data))
}
/// A Horizon folder and an official launcher directory holding version `9.9` with
/// sounds.json, two sounds and a language file in its asset store.
struct Fixture {
dir: PathBuf,
root: PathBuf,
minecraft: PathBuf,
objects: Vec<(&'static str, Vec<u8>)>,
}
impl Fixture {
fn new(name: &str) -> Fixture {
let dir = std::env::temp_dir().join(format!(
"horizon-prepare-sounds-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&dir);
let root = dir.join("horizon");
let minecraft = dir.join("minecraft");
let objects: Vec<(&'static str, Vec<u8>)> = vec![
("minecraft/sounds.json", b"{\"a\": {}}".to_vec()),
("minecraft/sounds/ambient/cave1.ogg", b"OggS cave".to_vec()),
("minecraft/sounds/dig/stone1.ogg", b"OggS stone".to_vec()),
("minecraft/lang/fr_fr.json", b"{}".to_vec()),
];
let mut index = String::from("{\"objects\": {");
for (i, (name, data)) in objects.iter().enumerate() {
let hash = sha1_hex(data);
let path = minecraft
.join("assets/objects")
.join(&hash[..2])
.join(&hash);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, data).unwrap();
let comma = if i > 0 { ", " } else { "" };
index += &format!(
"{comma}\"{name}\": {{\"hash\": \"{hash}\", \"size\": {}}}",
data.len()
);
}
index += "}}";
let indexes = minecraft.join("assets/indexes");
fs::create_dir_all(&indexes).unwrap();
fs::write(indexes.join("7.json"), &index).unwrap();
let manifest = format!(
"{{\"id\": \"9.9\", \"assetIndex\": {{\"id\": \"7\", \"sha1\": \"{}\"}}, \
\"downloads\": {{\"client\": {{\"sha1\": \"c\"}}, \"server\": {{\"sha1\": \"s\"}}}}, \
\"javaVersion\": {{\"majorVersion\": 25}}}}",
sha1_hex(index.as_bytes())
);
let versions = minecraft.join("versions/9.9");
fs::create_dir_all(&versions).unwrap();
fs::write(versions.join("9.9.json"), &manifest).unwrap();
fs::create_dir_all(&root).unwrap();
fs::write(
root.join("research-lock.json"),
format!(
"{{\"minecraft\": {{\"version\": \"9.9\", \"java_major\": 25, \
\"client_sha1\": \"c\", \"server_sha1\": \"s\", \"manifest_sha1\": \"{}\"}}}}",
sha1_hex(manifest.as_bytes())
),
)
.unwrap();
Fixture {
dir,
root,
minecraft,
objects,
}
}
fn run(&self) -> Result<PathBuf, String> {
sounds(&self.root, Some(&self.minecraft), &|_| {})
}
fn object(&self, i: usize) -> PathBuf {
let hash = sha1_hex(&self.objects[i].1);
self.minecraft
.join("assets/objects")
.join(&hash[..2])
.join(hash)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.dir);
}
}
#[test]
fn sounds_land_where_the_game_reads_them() {
let f = Fixture::new("layout");
let lines = std::cell::RefCell::new(Vec::new());
let target = sounds(&f.root, Some(&f.minecraft), &|l| {
lines.borrow_mut().push(l.to_string())
})
.unwrap();
assert_eq!(target, f.root.join(".local/horizon-client/9.9"));
for (name, data) in &f.objects[..3] {
assert_eq!(&fs::read(target.join("assets").join(name)).unwrap(), data);
}
assert!(!target.join("assets/minecraft/lang").exists());
assert_eq!(
fs::read(target.join("asset-index.json")).unwrap(),
fs::read(f.minecraft.join("assets/indexes/7.json")).unwrap()
);
assert!(f.root.join(".local/minecraft/9.9/manifest.json").is_file());
assert_eq!(*lines.borrow(), ["Sound assets ready: 3 files, 0.0 MB"]);
// Again: the verified copies are kept.
f.run().unwrap();
}
#[test]
fn every_object_is_checked() {
let f = Fixture::new("corrupt");
fs::write(f.object(1), b"not the sound").unwrap();
let error = f.run().unwrap_err();
assert!(error.starts_with("Corrupt asset object"), "{error}");
assert!(!f
.root
.join(".local/horizon-client/9.9/assets/minecraft/sounds/ambient/cave1.ogg")
.exists());
fs::remove_file(f.object(1)).unwrap();
assert!(f.run().unwrap_err().starts_with("Missing asset object"));
}
#[test]
fn the_index_must_be_the_pinned_one() {
let f = Fixture::new("index");
let index = f.minecraft.join("assets/indexes/7.json");
fs::write(&index, "{\"objects\": {}}").unwrap();
assert!(f
.run()
.unwrap_err()
.ends_with("is not the pinned asset index"));
fs::remove_file(&index).unwrap();
let error = f.run().unwrap_err();
assert!(
error.starts_with("Missing ") && error.contains("play 9.9 once"),
"{error}"
);
}
#[test]
fn object_paths_come_from_real_hashes() {
let store = Path::new("assets");
let hash = "abfaa525f923f807df8b4e4d29c1b5e3a104adbe";
assert_eq!(
object_path(store, hash).unwrap(),
store.join("objects/ab").join(hash)
);
assert!(object_path(store, "../../etc/passwd").is_err());
assert!(is_sound("minecraft/sounds/x.ogg") && is_sound("minecraft/sounds.json"));
assert!(!is_sound("minecraft/soundsx.json") && !is_sound("realms/sounds/x.ogg"));
}
}
+174
View File
@@ -0,0 +1,174 @@
# Controllers
Horizon plays with PlayStation (DualShock 4, DualSense), Xbox (360, One,
Series) and Nintendo Switch Pro controllers, and on the Steam Deck with its
built-in controls. Keyboard and mouse keep working exactly as before: with no
controller connected, or with controllers turned off, nothing changes.
## What vanilla has
Nothing. Minecraft Java 26.3 never calls GLFW's gamepad or joystick API, has
no controller options and ships no button glyphs. Its only non-mouse UI input
is keyboard focus navigation (`InputType.KEYBOARD_ARROW` / `KEYBOARD_TAB`:
arrows and Tab move a focus ring between widgets). So controller support is
Horizon's own feature. It follows what players already know from Minecraft on
consoles (Bedrock Edition's default controller layout) and Horizon's menu
design for any new screen.
## Input layer
[gilrs](https://crates.io/crates/gilrs) reads the pads: evdev on Linux (with
libudev for hot-plugging), IOKit on macOS, Windows.Gaming.Input on Windows.
Its SDL mapping database normalizes every pad to one positional layout
(South/East/West/North face buttons, bumpers, triggers, sticks, D-pad,
Select/Start). No second windowing or event stack: gilrs is polled once per
loop iteration next to winit's events.
- The pure logic (mapping table, deadzones and curves, button edges, the
settings file, glyph choice) lives in `crates/horizon-client/src/gamepad.rs`
and is unit-tested. The game owns a thin gilrs backend and applies actions.
- Controller actions go through the same path a keyboard key takes after
rebinding: an action names a vanilla key mapping (`key.jump`, `key.attack`,
...), and the game handles it as that mapping's default key or mouse button.
Toggle sneak/sprint/attack/use, screens releasing held keys, and the
multiplayer client all behave as they do on the keyboard.
- Movement is analog: the left stick's direction and tilt feed the player's
move vector directly (a half-tilted stick walks slowly, like Bedrock),
instead of being rounded to WASD. The forward/back/left/right flags other
code reads (sprint start, boats, minecarts, the server's input packet) are
set when the stick passes a threshold.
- The pad last touched is the active one. Several pads are not merged.
- `horizon-ctl pad ...` injects a virtual pad (buttons, sticks, triggers) into
a running game, for tests without hardware.
## Default mapping
| Action | Xbox | PlayStation | Mapping |
|---|---|---|---|
| Move | Left stick | Left stick | analog `key.forward/back/left/right` |
| Look | Right stick | Right stick | camera |
| Jump / fly up | A | ✕ | `key.jump` |
| Drop item | B | ○ | `key.drop` |
| Swap offhand | X | □ | `key.swapOffhand` |
| Inventory | Y | △ | `key.inventory` |
| Hotbar left / right | LB / RB | L1 / R1 | Horizon `pad.hotbarPrevious/Next` |
| Use / place | LT | L2 | `key.use` |
| Attack / break | RT | R2 | `key.attack` |
| Sprint | Left stick click | L3 | `key.sprint` |
| Sneak (toggles) | Right stick click | R3 | `key.sneak` |
| Change camera | D-pad up | D-pad up | `key.togglePerspective` |
| Pick block | D-pad left | D-pad left | `key.pickItem` |
| Chat | D-pad right | D-pad right | `key.chat` |
| Advancements | D-pad down | D-pad down | `key.advancements` |
| Player list (hold) | View | Create / Share | `key.playerlist` |
| Pause / back | Menu | Options | Escape (fixed) |
The Guide / PS / Steam button is left to the system. Sneak on a stick click
toggles by default (holding a stick in while steering the camera is
awkward, which is why Bedrock does the same); the controls options can make it
hold-to-sneak.
## Menus and inventories
Vanilla's screens are all mouse-driven, and Horizon draws them 1:1, so a pad
drives them through a **virtual cursor** (as Bedrock's classic inventory UI
and Java's controller mods do), not focus navigation:
- Left stick moves the cursor with acceleration; in container screens the
cursor is gently pulled toward the nearest slot centre.
- D-pad steps one slot (18 GUI pixels in containers) or one widget row in
menus and snaps to it.
- A = left click (take / place stack, press a button), X = right click
(half stack / place one), Y = quick move (shift-click), B = back / close.
- LB / RB switch creative tabs and recipe book pages; right stick scrolls
(creative grid, lists, chat).
- Sliders: hold A on the slider and move the stick, or nudge with the D-pad.
- Text fields: the Steam Deck's keyboard (Steam + X) types into them like a
real keyboard. Other platforms have no on-screen keyboard yet; text input
needs a keyboard.
The cursor is drawn only while the pad is the last-used input; moving the
mouse hands control back immediately.
## Glyphs
Horizon draws its own button glyphs in the HUD and screens (no Mojang
assets, nothing new from the player's jar): a small round or pill shape with
the label in the game font, sized to the GUI scale, with two styles:
- **Xbox / Steam Deck / generic**: A B X Y in their usual colours, LB RB LT
RT, View, Menu, stick icons.
- **PlayStation**: × ○ □ △ in their colours (× rather than ✕, which the game fonts lack), L1 R1 L2 R2,
Create/Share, Options.
- **Nintendo**: B A Y X by position.
The style comes from the pad's USB vendor (Sony 054c, Microsoft 045e,
Nintendo 057e, Valve 28de) unless the controls options force one. Glyphs
replace key names where a prompt names a key (the controls list, tutorial
hints, "Press X to dismount") only while the pad is the last-used input.
## Options and remapping
Controller settings are Horizon's own and live in `horizon-controller.txt`
next to `options.txt`, like `horizon-graphics.txt`: `options.txt` stays
exactly vanilla's, so a vanilla client can share the game folder.
```
enabled:true
vibration:true
lookSensitivity:0.5
invertX:false
invertY:false
moveDeadzone:0.15
lookDeadzone:0.12
triggerThreshold:0.4
toggleSneak:true
glyphs:auto
bind_key.jump:south
bind_pad.hotbarNext:rb
```
Only bindings that differ from the defaults are written. The controls
options get a Controller page: on/off, vibration, look sensitivity, invert
X/Y, deadzones, glyph style, sneak toggle, and a binding list like the key
binds screen (pick an action, press a button; conflicts marked as vanilla
does; reset).
Deadzones are radial (the stick's length, so diagonals aren't clipped) and the
remaining range is rescaled to 0..1. Look uses a squared curve for precise
aim near the centre, up to 200°/s yaw and 140°/s pitch at the default
sensitivity, slower while scoping with a spyglass.
## Rumble
Vibration (on by default, off in the options) through gilrs force feedback:
taking damage (stronger with the damage), a block broken, an explosion nearby
(scaled by distance), a totem of undying, an elytra boost, a fish biting.
Short, low-intensity pulses, as on Bedrock. Linux (evdev force feedback,
including Steam Input's virtual pad) and Windows support it; macOS gilrs has
no force feedback, so it is silently skipped there.
## Steam Deck
- In Game Mode, or any game launched through Steam, Steam Input presents the
Deck's controls as a virtual Xbox pad: Horizon sees it like any Xbox pad
and uses Xbox-letter glyphs (the Deck's face buttons are A B X Y). Steam's
default "Gamepad" layout works with no setup; the trackpads stay mouse.
- Started outside Steam on the Deck, the kernel's `hid-steam` driver exposes
the controls as a gamepad too (while Steam isn't holding them), so it also
works out of the box.
- Text entry uses Steam's keyboard (Steam + X).
## PR plan
1. **Input layer and gameplay** (this note, gilrs, defaults, movement,
camera, actions, hotbar, B/Start to leave screens, `horizon-ctl pad`,
`horizon-controller.txt` with the look/deadzone settings).
2. **Menus and inventories**: virtual cursor, slot snapping, clicks, quick
move, tabs, scrolling, sliders.
3. **Glyphs and the Controller options page**: glyph drawing per pad type,
the options page, remapping UI.
4. **Rumble**.
Each is shippable alone. Testing is with unit tests, the injected pad and
vscreen screenshots; each PR says what still needs a real controller.
+6 -5
View File
@@ -14,23 +14,24 @@ missing; [Rust rewrite status](rust-parity.md) has the details.
## Run from a checkout
Use current stable Rust (1.90+) and JDK 25 (Python 3.10+ for the sounds and the
development harnesses). Horizon never
Use current stable Rust (1.90+) and JDK 25 (Python 3.10+ only for the development
harnesses). Horizon never
downloads the game: resource preparation imports **your own copy** (the 26.3
client from your official launcher install, and the 26.3 server jar you
downloaded yourself; see [Build from source](../README.md#build-from-source)),
verifies it against the pinned checksums, runs vanilla's data generator and small
exporters against those jars, and extracts the jar's assets and data into ignored
`.local/horizon-client/26.3/`. Sounds (about 380 MB) are copied from your
launcher's asset store. Prepared resources are private; never commit them.
launcher's asset store by `horizon-prepare sounds`, each file checked against the asset
index's SHA-1. Prepared resources are private; never commit them.
Preparation is `horizon-prepare` (`crates/horizon-prepare`, Rust): it needs no Python, only
the JDK, for the small exporters that call Mojang's own code. Release folders ship it beside
`horizon-client`, and the launcher prepares with it.
`horizon-client`, and the launcher prepares with it and copies the sounds as part of preparing.
```sh
cargo run --release -p horizon-prepare -- --prepare --server-jar ~/Downloads/server.jar
python3 tools/fetch_sounds.py
cargo run --release -p horizon-prepare -- sounds
cargo run --release -p horizon-client -- --render-distance 12
```
+1 -1
View File
@@ -2565,7 +2565,7 @@ dependencies = [
[[package]]
name = "horizon-launcher"
version = "0.1.4"
version = "0.1.5"
dependencies = [
"clap",
"dirs 5.0.1",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "horizon-launcher"
version = "0.1.4"
version = "0.1.5"
edition = "2021"
license = "MIT"
description = "Downloads, prepares and starts Horizon builds"
+3 -1
View File
@@ -15,7 +15,9 @@ The opening, then Play ([clip](docs/opening.webm)):
- **Versions**: lists the published releases of ludovic111/horizon, installs the build for
this platform into its own folder, and removes it again.
- **Play**: prepares resources as `PLAY.txt` describes (your launcher's 26.3 install, the
26.3 server jar from that version's own json, and Java 25), then starts the client, or a
26.3 server jar from that version's own json, and Java 25) and copies its sounds from your
launcher's asset store (`horizon-prepare sounds`; a launcher install without them only
leaves the game silent), then starts the client, or a
server (`--dedicated --nogui`) in a folder you choose, with a live console. Preparing is
horizon-prepare: linked into the launcher, used in-process when a version ships the same
preparer sources, else that version's own `horizon-prepare`; versions released before it
+48 -1
View File
@@ -441,7 +441,7 @@ fn resources_compatible(from: &Path, to: &Path, manifest: &serde_json::Value) ->
sources.iter().all(|s| same(s))
}
/// Where a version folder keeps the preparer's sources (packaging/package.sh copies them).
/// Where a version folder keeps the preparer's sources (the release package copies them).
const PREPARER_CRATE: &str = "crates/horizon-prepare";
/// The files under `dir/relative`, as paths relative to `dir`.
@@ -679,6 +679,53 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result<Pre
Ok(Preparer::Process(cmd))
}
/// Copies the pinned version's sounds from the player's own launcher install into the version's
/// resources (`horizon-prepare sounds`), each line to `log`. Sound is optional, so a launcher
/// install without them is a line in the log, never a failed preparation. The version's own
/// preparer does it when it is not the launcher's and knows how; versions from before it read
/// the sounds where the launcher's preparer puts them.
pub fn sounds(tag: &str, minecraft: &Path, log: &dyn Fn(String)) {
let dir = version_dir(tag);
let own = horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref()
== Some(horizon_prepare::SOURCES_SHA256);
let binary = preparer_binary(&dir).filter(|binary| {
!own && Command::new(binary)
.arg("--help")
.output()
.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("horizon-prepare sounds"))
});
log("Copying the sounds from your Minecraft install".into());
let result = match binary {
Some(binary) => Command::new(binary)
.current_dir(&dir)
.arg("sounds")
.arg("--root")
.arg(&dir)
.arg("--minecraft-dir")
.arg(minecraft)
.output()
.map_err(|e| e.to_string())
.and_then(|o| {
let text = |b: &[u8]| String::from_utf8_lossy(b).trim().to_string();
for line in text(&o.stdout).lines() {
log(line.to_string());
}
match o.status.success() {
true => Ok(()),
false => Err(text(&o.stderr).trim_start_matches("error: ").to_string()),
}
}),
None => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
horizon_prepare::sounds(&dir, Some(minecraft), &|line| log(line.to_string()))
}))
.unwrap_or_else(|_| Err("The sound copy stopped unexpectedly".into()))
.map(|_| ()),
};
if let Err(e) = result {
log(format!("No sound (the game will be silent): {e}"));
}
}
/// Runs `Preparer::InProcess` on this thread, each progress line to `log`. A panic is an
/// error like any other, so the window never waits on a preparation that died.
pub fn prepare_in_process(
+3 -1
View File
@@ -215,7 +215,9 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
Cmd::Prepare { minecraft, version } => {
let tag = backend::resolve_version(version.as_deref())?;
let minecraft = backend::minecraft_dir(minecraft)?;
match backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))? {
let preparer = backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
backend::sounds(&tag, &minecraft, &|line| println!("{line}"));
match preparer {
backend::Preparer::Process(cmd) => attached(cmd)?,
backend::Preparer::InProcess(options) => {
backend::prepare_in_process(&options, &|line| println!("{line}"))?
+10 -8
View File
@@ -515,14 +515,16 @@ impl Launcher {
let log = |line| {
let _ = tx.send(Msg::Line(Job::Prepare, line));
};
let result = backend::preparer(&tag, &minecraft, &log).and_then(|p| match p {
backend::Preparer::Process(cmd) => {
backend::spawn(Job::Prepare, cmd, tx.clone()).map(|_running| false)
}
backend::Preparer::InProcess(options) => {
backend::prepare_in_process(&options, &log).map(|_| true)
}
});
let result = backend::preparer(&tag, &minecraft, &log)
.inspect(|_| backend::sounds(&tag, &minecraft, &log))
.and_then(|p| match p {
backend::Preparer::Process(cmd) => {
backend::spawn(Job::Prepare, cmd, tx.clone()).map(|_running| false)
}
backend::Preparer::InProcess(options) => {
backend::prepare_in_process(&options, &log).map(|_| true)
}
});
match result {
// A process sends its own Exit when it ends.
Ok(false) => {}
+5 -1
View File
@@ -97,7 +97,10 @@ impl Session {
let tag = backend::resolve_version(arg_str(args, "version"))?;
let minecraft =
backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?;
let (result, tail) = match backend::preparer(&tag, &minecraft, &|_| {})? {
let preparer = backend::preparer(&tag, &minecraft, &|_| {})?;
let sound = std::cell::RefCell::new(Vec::new());
backend::sounds(&tag, &minecraft, &|line| sound.borrow_mut().push(line));
let (result, tail) = match preparer {
backend::Preparer::Process(cmd) => {
let run = Logged::start(Job::Prepare, cmd)?;
let result = run.wait();
@@ -120,6 +123,7 @@ impl Session {
(result, tail)
}
};
let tail = format!("{}\n{tail}", sound.into_inner().join("\n"));
result
.map(|_| format!("{tag} is prepared.\n{tail}"))
.map_err(|e| format!("{e}\n{tail}"))
@@ -478,6 +478,9 @@ public final class VanillaBlockUpdateOracle {
/** The levels by dimension (the portal oracle's two). */
Map<net.minecraft.resources.ResourceKey<net.minecraft.world.level.Level>, net.minecraft.server.level.ServerLevel> levels;
@Override public net.minecraft.server.level.ServerLevel getLevel(net.minecraft.resources.ResourceKey<net.minecraft.world.level.Level> key) { return levels == null ? null : levels.get(key); }
/** The player list of the oracles whose player is an operator; null elsewhere. */
static net.minecraft.server.players.PlayerList players;
@Override public net.minecraft.server.players.PlayerList getPlayerList() { return players; }
@Override public int getMaxPlayers() { return 0; }
@Override public net.minecraft.server.permissions.LevelBasedPermissionSet operatorUserPermissions() { return null; }
@Override public net.minecraft.server.permissions.PermissionSet getFunctionCompilationPermissions() { return null; }
@@ -250,6 +250,7 @@ public final class VanillaDispenserOracle {
if (f.has("rules")) {
for (var rule : f.getAsJsonObject("rules").entrySet()) {
if (rule.getKey().equals("tnt_explodes")) w.rules.set(GameRules.TNT_EXPLODES, rule.getValue().getAsBoolean(), null);
if (rule.getKey().equals("spawner_blocks_work")) w.rules.set(GameRules.SPAWNER_BLOCKS_WORK, rule.getValue().getAsBoolean(), null);
}
}
if (f.has("items")) {
@@ -284,6 +285,10 @@ public final class VanillaDispenserOracle {
// Creating the targets must not move the stream the dispenser draws from.
w.rng = new LegacyRandomSource(f.get("seed").getAsLong());
VanillaBlockUpdateOracle.set(Level.class, w, "random", w.rng);
// Spawners have their block entity from the start (the oracle level makes them on demand).
for (var cell : List.copyOf(w.cells.entrySet())) {
if (cell.getValue().getBlock() instanceof net.minecraft.world.level.block.SpawnerBlock) w.getBlockEntity(cell.getKey());
}
w.log = new StringBuilder();
w.blockEvents.clear();
Map<BlockPos, BlockState> before = new HashMap<>(w.cells);
@@ -330,6 +335,18 @@ public final class VanillaDispenserOracle {
+ " signal=" + crafter.getRedstoneSignal() + " disabled=" + disabled);
}
}
for (BlockPos at : containers) {
// A spawner's next spawn data, potentials and delay (BaseSpawner.save).
if (w.blockEntities.get(at) instanceof net.minecraft.world.level.block.entity.SpawnerBlockEntity spawner) {
var out = net.minecraft.world.level.storage.TagValueOutput.createWithContext(net.minecraft.util.ProblemReporter.DISCARDING, ParityData.access);
spawner.getSpawner().save(out);
var saved = out.buildResult();
var entity = saved.getCompound("SpawnData").flatMap(d -> d.getCompound("entity"));
String next = entity.map(e -> e.getString("id").orElse("?") + "/" + e.size()).orElse("-");
result.add("spawner " + VanillaBlockUpdateOracle.pos(at) + " next=" + next + " potentials=" + saved.getListOrEmpty("SpawnPotentials").size()
+ " delay=" + saved.getShortOr("Delay", (short) 0));
}
}
for (BlockPos at : containers) {
if (!(w.blockEntities.get(at) instanceof Container) || w.getBlockEntity(at) != w.blockEntities.get(at)) continue;
List<ItemStack> items = w.blockEntities.get(at) instanceof Container c && !hasList(c) ? List.of(c.getItem(0)) : slots(w.blockEntities.get(at));
@@ -449,6 +466,16 @@ public final class VanillaDispenserOracle {
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) {
stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count);
}
@Override public net.minecraft.server.players.NameAndId nameAndId() { return new net.minecraft.server.players.NameAndId(new UUID(0L, 0L), "Player"); }
@Override public void sendSystemMessage(net.minecraft.network.chat.Component message) {
stats.add("msg " + (message.getContents() instanceof net.minecraft.network.chat.contents.TranslatableContents t ? t.getKey() : message.getString()));
}
}
/** The single player's list: the player is an operator (cheats are on). */
static final class Ops extends net.minecraft.server.players.PlayerList {
Ops() { super(null, null, null, null); }
@Override public boolean isOp(net.minecraft.server.players.NameAndId nameAndId) { return true; }
}
/**
@@ -460,6 +487,9 @@ public final class VanillaDispenserOracle {
* the item the player started using follow.
*/
static List<String> useItem(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception {
if (VanillaBlockUpdateOracle.Server.players == null) {
VanillaBlockUpdateOracle.Server.players = (Ops) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Ops.class);
}
Clicker player = (Clicker) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Clicker.class);
player.world = w;
player.creative = use.get("creative").getAsBoolean();
@@ -113,6 +113,23 @@ public final class VanillaNaturalSpawnOracle {
@Override public double nextGaussian() { return 0.0; }
}
/**
* finalizeSpawn's random in spawner cases: the neutral answers, except that
* nextInt(100) answers 99 so no spider spawns with a skeleton riding it.
*/
static final class SpawnerNeutral implements RandomSource {
@Override public RandomSource fork() { return this; }
@Override public net.minecraft.world.level.levelgen.PositionalRandomFactory forkPositional() { throw new UnsupportedOperationException(); }
@Override public void setSeed(long seed) {}
@Override public int nextInt() { return 0; }
@Override public int nextInt(int bound) { return bound == 100 ? 99 : 0; }
@Override public long nextLong() { return 0L; }
@Override public boolean nextBoolean() { return false; }
@Override public float nextFloat() { return 0.75F; }
@Override public double nextDouble() { return 0.75; }
@Override public double nextGaussian() { return 0.0; }
}
static final class Lvl extends ServerLevel {
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
RegistryAccess registries;
@@ -140,6 +157,11 @@ public final class VanillaNaturalSpawnOracle {
ServerChunkCache chunkSource;
StructureManager structures;
RandomSource neutral = new Neutral();
RandomSource spawnerNeutral = new SpawnerNeutral();
/** Spawner cases: the level's own random, but for finalizeSpawn's draws. */
RandomSource spawnerRandom;
/** Spawner cases: the tick whose events are logged (-1 while loading). */
int tick = -1;
List<String> log;
boolean logColumns;
int next = 1;
@@ -183,7 +205,23 @@ public final class VanillaNaturalSpawnOracle {
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
@Override public WorldBorder getWorldBorder() { return border; }
@Override public GameRules getGameRules() { return rules; }
@Override public RandomSource getRandom() { return neutral; }
@Override public RandomSource getRandom() {
if (spawnerRandom == null) return neutral;
boolean finalizing = StackWalker.getInstance().walk(f -> f.anyMatch(x -> x.getMethodName().equals("finalizeSpawn")));
return finalizing ? spawnerNeutral : spawnerRandom;
}
@Override public boolean tryAddFreshEntityWithPassengers(Entity entity) {
addFreshEntityWithPassengers(entity);
log.add(tick + " spawn " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()) + " " + bits(entity.getX()) + " " + bits(entity.getY()) + " " + bits(entity.getZ()) + " " + yaw(entity));
return true;
}
@Override public void blockEvent(BlockPos pos, net.minecraft.world.level.block.Block block, int b0, int b1) { if (tick >= 0) log.add(tick + " bevent " + b0 + " " + b1); }
@Override public void sendBlockUpdated(BlockPos pos, BlockState old, BlockState current, int flags) { if (tick >= 0) log.add(tick + " update"); }
@Override public void levelEvent(Entity source, int type, BlockPos pos, int data) { if (tick >= 0) log.add(tick + " levent " + type + " " + data); }
@Override public void gameEvent(Holder<net.minecraft.world.level.gameevent.GameEvent> event, Vec3 at, net.minecraft.world.level.gameevent.GameEvent.Context context) {
if (tick >= 0) log.add(tick + " gevent " + event.unwrapKey().orElseThrow().identifier() + " " + Mth.floor(at.x) + " " + Mth.floor(at.y) + " " + Mth.floor(at.z));
}
@Override public void broadcastEntityEvent(Entity entity, byte event) { if (tick >= 0) log.add(tick + " eevent " + event); }
@Override public ServerChunkCache getChunkSource() { return chunkSource; }
@Override public StructureManager structureManager() { return structures; }
@Override public LevelData.RespawnData getRespawnData() { return respawn; }
@@ -299,6 +337,7 @@ public final class VanillaNaturalSpawnOracle {
@Override public boolean isSpectator() { return mode == GameType.SPECTATOR; }
@Override public boolean isCreative() { return mode == GameType.CREATIVE; }
@Override public GameType gameMode() { return mode; }
@Override public boolean isAlive() { return true; }
}
static String bits(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); }
@@ -358,6 +397,7 @@ public final class VanillaNaturalSpawnOracle {
level.playerList = new ArrayList<>();
level.border = new WorldBorder();
level.neutral = new Neutral();
level.spawnerNeutral = new SpawnerNeutral();
level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
level.biomeManager = new BiomeManager((x, y, z) -> level.biome, 0L) {
@Override public Holder<Biome> getBiome(BlockPos pos) { return level.biomeAt(pos.getX(), pos.getY(), pos.getZ()); }
@@ -424,6 +464,7 @@ public final class VanillaNaturalSpawnOracle {
level.seed = Long.parseLong(c.getOrDefault("wseed", "0"));
level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal"));
level.rules.set(net.minecraft.world.level.gamerules.GameRules.SPAWN_MOBS, !c.getOrDefault("rules", "1").equals("0"), null);
level.rules.set(net.minecraft.world.level.gamerules.GameRules.SPAWNER_BLOCKS_WORK, !c.getOrDefault("spawners", "1").equals("0"), null);
// The dimension and biome layers; the moon timeline's surface slime chance as a constant.
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addStaticLayers(level)
.addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder()
@@ -476,7 +517,37 @@ public final class VanillaNaturalSpawnOracle {
Chunk chunk = (Chunk) alloc(Chunk.class);
chunk.level = level;
chunk.at = new ChunkPos(Integer.parseInt(cp[0]), Integer.parseInt(cp[1]));
if (mode.equals("gen")) {
if (mode.equals("spawner")) {
// SpawnerBlockEntity.serverTick, `ticks` times, at `spos`, loaded from `snbt` (base64 SNBT).
level.spawnerRandom = mainRandom;
level.tick = -1;
String[] sp = c.get("spos").split(",");
BlockPos at = new BlockPos(Integer.parseInt(sp[0]), Integer.parseInt(sp[1]), Integer.parseInt(sp[2]));
var nbt = net.minecraft.nbt.TagParser.parseCompoundFully(new String(Base64.getDecoder().decode(c.get("snbt")), StandardCharsets.UTF_8));
var spawner = new net.minecraft.world.level.block.entity.SpawnerBlockEntity(at, Blocks.SPAWNER.defaultBlockState());
spawner.getSpawner().load(level, at, net.minecraft.world.level.storage.TagValueInput.create(net.minecraft.util.ProblemReporter.DISCARDING, access, nbt));
int ticks = Integer.parseInt(c.getOrDefault("ticks", "1"));
try {
for (int t = 0; t < ticks; t++) {
level.tick = t;
net.minecraft.world.level.block.entity.SpawnerBlockEntity.serverTick(level, at, Blocks.SPAWNER.defaultBlockState(), spawner);
}
} finally {
level.tick = -1;
level.spawnerRandom = null;
}
var out = net.minecraft.world.level.storage.TagValueOutput.createWithContext(net.minecraft.util.ProblemReporter.DISCARDING, access);
spawner.getSpawner().save(out);
CompoundTag saved = out.buildResult();
String next = saved.getCompound("SpawnData").flatMap(d -> d.getCompound("entity")).flatMap(e -> e.getString("id")).orElse("-");
StringBuilder pots = new StringBuilder();
for (var p : saved.getListOrEmpty("SpawnPotentials")) {
String id = ((CompoundTag) p).getCompound("data").flatMap(d -> d.getCompound("entity")).flatMap(e -> e.getString("id")).orElse("-");
pots.append(pots.isEmpty() ? "" : ",").append(id).append('*').append(((CompoundTag) p).getIntOr("weight", 0));
}
log.add("end delay=" + saved.getShortOr("Delay", (short) 0) + " next=" + next + " pots=" + pots);
log.add("next " + mainRandom.nextInt(1000));
} else if (mode.equals("gen")) {
level.logColumns = true;
int n = level.entities.size();
RandomSource random = RandomSource.create(Long.parseLong(c.getOrDefault("gseed", "0")));
@@ -392,7 +392,7 @@ public final class VanillaSceneMotionOracle {
case "frozen"->p.frozen=op.get("value").getAsInt();
case "portal_tick"->p.portalTick(op.get("creative").getAsBoolean());
case "weaving"->p.weaving=op.get("value").getAsBoolean();
case "flying"->{var a=p.getAbilities();a.mayfly=a.flying=op.get("value").getAsBoolean();}
case "flying"->{var a=p.getAbilities();a.flying=op.get("value").getAsBoolean();a.mayfly=op.has("may_fly")?op.get("may_fly").getAsBoolean():a.flying;}
case "trigger"->trigger.setInt(p,op.get("value").getAsInt());
case "delay"->delay.setInt(p,op.get("value").getAsInt());
case "ack_attributes"->{p.attrs.getAttributesToUpdate().clear();p.attrs.getAttributesToSync().clear();}
+4 -4
View File
@@ -19,10 +19,10 @@ Downloaded this archive directly?
To prepare this folder by hand you need Minecraft Java Edition 26.3, played
once from the official launcher, and Java 25 (a JDK). Then, in this folder:
./horizon-prepare --prepare --server-jar PATH/TO/server.jar
python3 tools/fetch_sounds.py (optional, for sound; needs Python 3.10+)
(Windows: horizon-prepare.exe, and py instead of python3.) The 26.3 server jar is the
downloads.server.url in your launcher's versions/26.3/26.3.json. Add
--minecraft-dir PATH if your launcher keeps the game elsewhere. Then run
./horizon-prepare sounds (optional, for sound)
(Windows: horizon-prepare.exe.) The 26.3 server jar is the downloads.server.url
in your launcher's versions/26.3/26.3.json. Add --minecraft-dir PATH to both if
your launcher keeps the game elsewhere. Then run
./horizon-client (horizon-client.exe on Windows; on macOS the first time:
right-click > Open). horizon-client --help lists the options.
-27
View File
@@ -1,27 +0,0 @@
#!/usr/bin/env bash
# packaging/package.sh BINARY OUTDIR: a playable Horizon folder with the game
# binary, horizon-ctl and horizon-prepare (built beside it: cargo build --release
# -p horizon-client --bins -p horizon-prepare), the exporters horizon-prepare compiles,
# its sources (the launcher compares them to its own), and PLAY.txt.
# It holds none of Minecraft's files: players prepare those from their own copy.
set -euo pipefail
bin=$1
out=$2
repo=$(git -C "$(dirname "$0")" rev-parse --show-toplevel)
rm -rf "$out"
mkdir -p "$out"
git -C "$repo" archive HEAD tools mods/horizon/src/test/java crates/horizon-prepare research-lock.json LICENSE \
| tar -x -C "$out"
cp "$bin" "$out/"
# horizon-ctl, the command line and MCP server that play the game, and horizon-prepare, which
# prepares the resources from the player's own Minecraft, sit beside the client.
for tool in horizon-ctl horizon-prepare; do
path="$(dirname "$bin")/$tool"
case "$bin" in *.exe) path="$path.exe" ;; esac
if [ ! -f "$path" ]; then
echo "package.sh: $path is missing; build it too: cargo build --release -p horizon-client --bins -p horizon-prepare" >&2
exit 1
fi
cp "$path" "$out/"
done
cp "$repo/packaging/PLAY.txt" "$out/PLAY.txt"
+1 -1
View File
@@ -33,7 +33,7 @@ COMMON_SOURCES = [
def require_sounds():
if not (RESOURCES / 'assets/minecraft/sounds.json').is_file():
raise SystemExit('Sound assets missing: run tools/fetch_sounds.py first')
raise SystemExit('Sound assets missing: run cargo run -p horizon-prepare -- sounds first')
def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args=(), rust_args=(), scope='', timeout=1800):
+1 -1
View File
@@ -28,7 +28,7 @@ WINDOWS_SYSTEM = {
LINUX_LOADER = "/lib64/ld-linux-x86-64.so.2"
LINUX_SYSTEM = {
"libc.so.6", "libm.so.6", "libgcc_s.so.1", "libdl.so.2", "libpthread.so.0", "librt.so.1",
"ld-linux-x86-64.so.2", "libasound.so.2",
"ld-linux-x86-64.so.2", "libasound.so.2", "libudev.so.1",
}
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env python3
"""Copy the pinned version's sound assets (sounds.json and .ogg files) from your
own official launcher install into the private client resource directory,
verifying every object's SHA-1. Nothing is downloaded; the files stay in
ignored .local/ and are never committed."""
import argparse
from pathlib import Path
import shutil
import lab
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--minecraft-dir', type=Path,
help="official launcher game directory (default: the launcher's own)")
args = parser.parse_args()
lock, directory = lab.config()
manifest = lab.import_manifest(lock, directory, args.minecraft_dir)
store, index = lab.launcher_assets(manifest, args.minecraft_dir)
target = lab.LOCAL / 'horizon-client' / manifest['id']
target.mkdir(parents=True, exist_ok=True)
shutil.copyfile(index, target / 'asset-index.json')
objects = lab.json.loads(index.read_text())['objects']
wanted = {name: info for name, info in objects.items()
if name == 'minecraft/sounds.json' or name.startswith('minecraft/sounds/')}
total = 0
for name, info in wanted.items():
source = lab.launcher_object(store, info['hash'])
lab.import_copy(source, target / 'assets' / name, info['hash'])
total += info['size']
print(f'Sound assets ready: {len(wanted)} files, {total / 1e6:.1f} MB')
if __name__ == '__main__':
main()
+1 -1
View File
@@ -87,7 +87,7 @@ def main():
if not (args.resources / 'horizon-resources.json').is_file():
raise SystemExit(f'missing prepared resources in {args.resources}: run horizon-prepare --prepare (cargo run --release -p horizon-prepare -- --prepare)')
if not (args.resources / 'assets/minecraft/sounds.json').is_file():
print('warning: no sound assets; run tools/fetch_sounds.py for audio')
print('warning: no sound assets; run cargo run -p horizon-prepare -- sounds for audio')
system = {'Linux': 'linux', 'Darwin': 'macos'}.get(platform.system())
if system is None:
+12
View File
@@ -340,6 +340,18 @@ def corpus():
yield dict(position=vec((25.5,4,25.5)),ops=[op('seed',seed),op('block',name='minecraft:'+name,position=[25,3,25],properties=properties),
*[v for _ in range(8) for v in [op('fall',bits(8)),op('landing',bits(-.1),ground=True,position=[25,3,25])]],
op('block',name='minecraft:stone',position=[25,3,25])])
# Creative players are exempt even while walking. Compare small/big falls,
# block damage multipliers and switching back to survival on the same actor.
for name in ['stone','hay_block','pointed_dripstone']:
for distance in [4,8,20]:
for flying in [False,True]:
ops=[op('block',name='minecraft:'+name,position=[25,3,25]),
op('flying',flying,may_fly=True),op('fall',bits(distance)),
op('landing',bits(-.125),ground=True,position=[25,3,25]),
op('flying',False,may_fly=False),op('fall',bits(distance)),
op('landing',bits(-.125),ground=True,position=[25,3,25]),
op('block',name='minecraft:stone',position=[25,3,25])]
yield dict(position=vec((25.5,4,25.5)),ops=ops)
for safe in [0,1,3,6,20]:
for multiplier in [0,.5,1,2]:
for impact in [None,3,4,4.1,7,18]:
+281
View File
@@ -0,0 +1,281 @@
#!/usr/bin/env python3
"""Compare monster spawners (BaseSpawner.serverTick) with vanilla.
Java (VanillaNaturalSpawnOracle, mode=spawner) loads a SpawnerBlockEntity from
each case's NBT on the oracle's stand-in ServerLevel and runs
`SpawnerBlockEntity.serverTick` for a number of ticks. Rust
(natural_spawn_fixture, mode=spawner) loads `mobs::spawner::Spawner` from the
same NBT and ticks it on the same world. Both log, tick by tick, every spawn
(type, exact position and yaw bits), `sendBlockUpdated`, the block event, the
2004 level event, the entity_place game event and the spawn animation, then
the saved delay, next spawn data and potentials, and the next draw of the
level random, which pins every draw in between.
Worlds are rooms around the spawner (dungeons, caves, open fields, flooded
rooms, nether halls) with dark, dim and lit light, players inside and outside
the required range (spectators, a negative range), mobs of the spawner's type
already around it, every difficulty and the spawner_blocks_work rule. Spawn
data covers generated spawners (no potentials), loaded ones (potentials
missing, so shared with the next data), weighted potentials (zero weights
included), custom light rules, fixed `Pos`, configured entities (no
finalizeSpawn), ids without a namespace, unknown, invalid and missing ids, and
delays, counts, caps and ranges from the edge values up.
finalizeSpawn runs with a fixed random in the oracle (nextInt(100) answers 99
so spiders do not grow skeleton jockeys); its own outcomes are not compared.
Entity types that are not mobs (Horizon creates only mobs from a spawner) are
not in the corpus.
"""
import argparse
import base64
import json
import os
from pathlib import Path
import platform
import random
import subprocess
try:
from . import lab, test_rust_parity as base, test_natural_spawn_parity as natural
except ImportError:
import lab
import test_rust_parity as base
import test_natural_spawn_parity as natural
box = natural.box
MONSTERS = ['zombie', 'skeleton', 'spider', 'cave_spider', 'blaze', 'silverfish', 'magma_cube', 'creeper', 'witch',
'enderman', 'zombified_piglin', 'husk', 'stray', 'bogged', 'slime', 'drowned', 'piglin', 'wither_skeleton',
'endermite', 'parched', 'zombie_villager', 'breeze']
CREATURES = ['pig', 'cow', 'chicken', 'sheep', 'rabbit', 'wolf', 'bat', 'squid', 'cod', 'strider', 'fox', 'horse']
FLOORS = ['minecraft:cobblestone', 'minecraft:mossy_cobblestone', 'minecraft:stone', 'minecraft:deepslate',
'minecraft:grass_block', 'minecraft:netherrack', 'minecraft:sand', 'minecraft:infested_stone']
def entity_snbt(rng, mob, spos):
r = rng.random()
if r < 0.55:
return f'{{id:"minecraft:{mob}"}}'
if r < 0.65:
return f'{{id:"{mob}"}}'
if r < 0.75:
return f'{{id:"minecraft:{mob}",PersistenceRequired:1b}}'
if r < 0.83:
x, y, z = (spos[0] + rng.uniform(-3, 3), spos[1] + rng.choice([0, 0, 1, -1, 3]), spos[2] + rng.uniform(-3, 3))
return f'{{id:"minecraft:{mob}",Pos:[{x:.4f}d,{y}.0d,{z:.4f}d]}}'
if r < 0.88:
return '{id:"minecraft:not_an_entity"}'
if r < 0.93:
return f'{{id:"{mob.capitalize()}"}}'
return '{}'
def spawn_data(rng, mob, spos, rules=True):
out = f'entity:{entity_snbt(rng, mob, spos)}'
if rules and rng.random() < 0.2:
def limit():
lo = rng.randrange(0, 16)
hi = rng.randrange(lo, 16)
return rng.choice([str(lo), f'[I;{lo},{hi}]', f'{{min_inclusive:{lo},max_inclusive:{hi}}}'])
parts = []
if rng.random() < 0.7:
parts.append(f'block_light_limit:{limit()}')
if rng.random() < 0.7:
parts.append(f'sky_light_limit:{limit()}')
out += ',custom_spawn_rules:{' + ','.join(parts) + '}'
return '{' + out + '}'
def spawner_snbt(rng, mob, spos, pool):
fields = []
shape = rng.random()
if shape < 0.35:
# Generated (setEntityId): the next data and no potentials.
fields.append(f'SpawnData:{{entity:{{id:"minecraft:{mob}"}}}}')
fields.append('SpawnPotentials:[]')
elif shape < 0.55:
# Potentials missing: the next data becomes the one potential.
fields.append(f'SpawnData:{spawn_data(rng, mob, spos)}')
elif shape < 0.85:
n = rng.randrange(1, 5)
entries = []
for _ in range(n):
other = mob if rng.random() < 0.5 else rng.choice(pool)
weight = rng.choice([1, 1, 2, 5, 0, 20])
entries.append(f'{{data:{spawn_data(rng, other, spos)},weight:{weight}}}')
fields.append('SpawnPotentials:[' + ','.join(entries) + ']')
if rng.random() < 0.5:
fields.append(f'SpawnData:{spawn_data(rng, mob, spos)}')
elif shape < 0.95:
fields.append(f'SpawnData:{spawn_data(rng, mob, spos)}')
fields.append(f'SpawnPotentials:[{{data:{spawn_data(rng, mob, spos)},weight:1}}]')
# else: an empty spawner (placed from the item).
fields.append(f'Delay:{rng.choice([0, 0, 1, 3, 20, -1, 5])}s')
if rng.random() < 0.8:
lo = rng.choice([0, 1, 5, 10, 20, 200])
hi = rng.choice([lo, lo + 1, lo + 10, lo + 40, max(lo - 5, 0)])
fields.append(f'MinSpawnDelay:{lo}s')
fields.append(f'MaxSpawnDelay:{hi}s')
if rng.random() < 0.6:
fields.append(f'SpawnCount:{rng.choice([1, 2, 4, 4, 6, 8, 0])}s')
if rng.random() < 0.5:
fields.append(f'MaxNearbyEntities:{rng.choice([0, 1, 3, 6, 6, 10])}s')
if rng.random() < 0.4:
fields.append(f'RequiredPlayerRange:{rng.choice([16, 16, 4, 32, -1, 0])}s')
if rng.random() < 0.5:
fields.append(f'SpawnRange:{rng.choice([1, 2, 4, 4, 6, 8])}s')
return '{' + ','.join(fields) + '}'
def room(rng):
"""A world around the spawner; returns (world, spawner position, the mob)."""
w = natural.World(rng)
dim = rng.choices(['overworld', 'nether', 'end'], [80, 17, 3])[0]
w.dim = f'minecraft:{"the_" if dim != "overworld" else ""}{dim}'
w.kv['dim'] = w.dim
w.min_y = -64 if dim == 'overworld' else 0
sx, sy, sz = rng.randrange(-8, 9), rng.randrange(-20, 60) if dim == 'overworld' else rng.randrange(30, 90), rng.randrange(-8, 9)
w.surface = sy
if dim == 'nether':
w.kv['biome'] = rng.choice(list(natural.NETHER))
pool = ['blaze', 'magma_cube', 'zombified_piglin', 'wither_skeleton', 'piglin', 'skeleton', 'strider', 'ghast']
elif dim == 'end':
w.kv['biome'] = 'minecraft:the_end'
pool = ['enderman', 'endermite', 'zombie', 'shulker']
else:
w.kv['biome'] = rng.choice(['minecraft:plains', 'minecraft:desert', 'minecraft:dripstone_caves',
'minecraft:deep_dark', 'minecraft:swamp', 'minecraft:forest'])
pool = MONSTERS + CREATURES
mob = rng.choice(pool)
half, height = rng.choice([3, 4, 4, 5, 6]), rng.choice([3, 4, 4, 6])
kind = rng.random()
floor = rng.choice(FLOORS if dim == 'overworld' else ['minecraft:netherrack', 'minecraft:nether_bricks', 'minecraft:end_stone'])
if kind < 0.65:
# A dungeon or hall: solid all around, an air room.
w.block(box(sx - 12, sy - 6, sz - 12, sx + 12, sy + 10, sz + 12), rng.choice(['minecraft:stone', 'minecraft:cobblestone', 'minecraft:netherrack']))
w.block(box(sx - half, sy - 1, sz - half, sx + half, sy - 1, sz + half), floor)
w.block(box(sx - half, sy, sz - half, sx + half, sy + height - 1, sz + half), rng.choice(['minecraft:cave_air', 'minecraft:air']))
elif kind < 0.85:
# Open ground.
w.block(box(sx - 16, sy - 6, sz - 16, sx + 16, sy - 2, sz + 16), 'minecraft:dirt')
w.block(box(sx - 16, sy - 1, sz - 16, sx + 16, sy - 1, sz + 16), floor)
else:
# A flooded room.
w.block(box(sx - 12, sy - 6, sz - 12, sx + 12, sy + 10, sz + 12), 'minecraft:stone')
w.block(box(sx - half, sy - 1, sz - half, sx + half, sy - 1, sz + half), floor)
w.block(box(sx - half, sy, sz - half, sx + half, sy + height - 1, sz + half), 'minecraft:water')
if rng.random() < 0.5:
mob = rng.choice(['drowned', 'squid', 'cod', 'guardian', 'zombie'])
if rng.random() < 0.3:
# Pillars and slabs in the way.
for _ in range(rng.randrange(1, 6)):
px, pz = sx + rng.randrange(-half, half + 1), sz + rng.randrange(-half, half + 1)
w.block(box(px, sy, pz, px, sy + rng.randrange(0, 3), pz), rng.choice(['minecraft:cobblestone', 'minecraft:oak_slab', 'minecraft:torch', 'minecraft:glass']))
w.block(box(sx, sy, sz, sx, sy, sz), 'minecraft:spawner')
sky, light = rng.choice([(0, 0), (0, 0), (0, 0), (0, 3), (0, 7), (0, 12), (15, 0), (15, 15), (8, 8)])
w.light(box(sx - 16, sy - 2, sz - 16, sx + 16, sy + 12, sz + 16), sky, light)
if rng.random() < 0.25:
# A torch's glow on one side.
w.light(box(sx, sy - 1, sz - half, sx + half, sy + height, sz + half), sky, rng.choice([7, 11, 14]))
return w, (sx, sy, sz), mob, pool
def players(w, rng, spos):
for _ in range(rng.choice([1, 1, 1, 2, 0])):
r = rng.random()
if r < 0.7:
d = rng.uniform(0, 15)
elif r < 0.85:
d = rng.uniform(14, 18)
else:
d = rng.uniform(18, 40)
import math
a, b = rng.uniform(0, 6.283), rng.uniform(-0.6, 0.6)
x = spos[0] + 0.5 + d * math.cos(a) * math.cos(b)
y = spos[1] + 0.5 + d * math.sin(b)
z = spos[2] + 0.5 + d * math.sin(a) * math.cos(b)
mode = rng.choice(['survival'] * 7 + ['creative', 'adventure', 'spectator'])
w.players.append(f'{x:.3f},{y:.3f},{z:.3f}/{mode}')
def corpus():
rng = random.Random(0x5350574E)
cases = []
for k in range(6000):
w, spos, mob, pool = room(rng)
players(w, rng, spos)
if rng.random() < 0.5:
for _ in range(rng.choice([1, 2, 3, 5, 6, 8])):
t = mob if rng.random() < 0.8 else rng.choice(pool)
x, z = spos[0] + rng.uniform(-6, 7), spos[2] + rng.uniform(-6, 7)
w.entities.append(f'minecraft:{t}/{x:.3f},{spos[1] + rng.choice([0, 0, -1, 2])},{z:.3f}')
natural.common(w, rng, rng.randrange(-2**47, 2**47))
w.kv.pop('unloaded', None)
if rng.random() < 0.05:
w.kv['spawners'] = 0
snbt = spawner_snbt(rng, mob, spos, pool)
w.kv['spos'] = f'{spos[0]},{spos[1]},{spos[2]}'
w.kv['snbt'] = base64.b64encode(snbt.encode()).decode()
w.kv['ticks'] = rng.choice([1, 2, 5, 21, 40, 80, 120])
cases.append(f'spawner/{k} mode=spawner {w.tokens()}')
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'rust-spawner-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs']
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
cases = corpus()
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture'
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
if bad or len(vanilla) != len(rust):
report = '\n'.join(f' vanilla {a[:2000]}\n rust {b[:2000]}' for a, b in bad[:12])
raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}')
base.ensure_sources_unchanged(sources, tested)
spawns = sum(line.count(' spawn minecraft:') for line in vanilla)
delays = sum(line.count(' bevent 1 ') for line in vanilla)
updates = sum(line.count(' update') for line in vanilla)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'spawns': spawns, 'delays': delays, 'block_updates': updates, 'sources_sha256': tested,
'scope': 'BaseSpawner: load (SpawnData and potentials codecs, shared next data), serverTick (player range, '
'spawner_blocks_work, delay, getOrCreateNextSpawnData, Pos, getSpawnAABB collision, custom spawn '
'rules and peaceful, SpawnPlacements, the nearby cap, yaw, checkSpawnRules and checkSpawnObstruction, '
'events) and delay (weighted potentials), with every level random draw. finalizeSpawn runs with a '
'fixed random in the oracle; its own outcomes are not compared.'})
print(f'{len(cases):,} spawner cases match vanilla ({spawns:,} spawns, {delays:,} delays, {updates:,} block updates)')
if __name__ == '__main__':
main()
+18 -7
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Compare a player's right click on a block with vanilla's, for items that are
both food and blocks (sweet and glow berries, carrots, potatoes) and for sweet
berry bushes.
both food and blocks (sweet and glow berries, carrots, potatoes), for sweet
berry bushes and for spawn eggs used on a monster spawner.
Every case has a block at the origin, something above it, and a player three
blocks south, survival or creative, hungry or full, sneaking or not, who
@@ -10,11 +10,13 @@ right-clicks the top face of the origin holding an item. Vanilla runs the real
harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and
`useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn`
passing bone meal on), then `ItemStack.useOn` (`BlockItem.place` with its
`mayPlaceOn` rules, `BoneMealItem.useOn`, and eating a consumable that could
not be placed). Horizon runs `use_item_as_player` on that hit in a headless
game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items,
`mayPlaceOn` rules, `BoneMealItem.useOn`, eating a consumable that could
not be placed, and `SpawnEggItem.useOn` setting a spawner's mob). Horizon runs
`use_item_as_player` on that hit in a headless game
(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items,
level events, sounds, game events, the used statistic, the held stack, the
item the player started using, and the level random afterwards.
item the player started using, spawners' next spawn data, potentials and
delay, system messages and the level random afterwards.
"""
import json
import os
@@ -34,6 +36,7 @@ ITEMS = ['sweet_berries', 'sweet_berries', 'sweet_berries', 'glow_berries', 'car
'wheat_seeds', 'beetroot_seeds', 'apple']
# What is in the way above the clicked block.
ABOVE = ['air'] * 8 + ['short_grass', 'snow', 'stone', 'water', 'dead_bush', 'fern']
EGGS = ['zombie', 'skeleton', 'spider', 'cave_spider', 'pig', 'creeper', 'blaze', 'ghast', 'villager', 'bee', 'cod']
def cases(facts, count, seed):
@@ -45,7 +48,15 @@ def cases(facts, count, seed):
case.pop('thundering', None)
cells = []
item = rng.choice(ITEMS)
if rng.random() < 0.3:
if rng.random() < 0.15:
# A spawn egg on a fresh monster spawner (SpawnEggItem.useOn).
cells.append([0, 0, 0, states.get('spawner')])
if rng.random() < 0.3:
cells.append([0, 1, 0, states.get(rng.choice(['stone', 'water', 'short_grass']))])
item = rng.choice([f'{e}_spawn_egg' for e in EGGS] + ['apple', '-'])
if rng.random() < 0.15:
case['rules'] = {'spawner_blocks_work': False}
elif rng.random() < 0.3:
# A sweet berry bush on grass: pick it, bone meal it, or plant against it.
age = rng.randrange(4)
cells.append([0, 0, 0, states.get('sweet_berry_bush', age=str(age))])
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "xtask"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish = false
description = "Repository tasks: cargo run -p xtask -- package BINARY OUTDIR"
[lints]
workspace = true
+316
View File
@@ -0,0 +1,316 @@
//! Repository tasks, run with `cargo run -p xtask -- TASK`.
//!
//! `package BINARY OUTDIR`: a playable Horizon folder with the game binary, horizon-ctl and
//! horizon-prepare (built beside it: cargo build --release -p horizon-client --bins -p
//! horizon-prepare), the exporters horizon-prepare compiles, its sources (the launcher compares
//! them to its own), and PLAY.txt. It holds none of Minecraft's files: players prepare those
//! from their own copy. .github/workflows/release.yml makes the release folders with it.
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, ExitCode};
const USAGE: &str = "usage: cargo run -p xtask -- package BINARY OUTDIR";
/// What the release folder takes from the repository at HEAD, as `git archive` writes it.
const ARCHIVED: [&str; 5] = [
"tools",
"mods/horizon/src/test/java",
"crates/horizon-prepare",
"research-lock.json",
"LICENSE",
];
/// The programs that sit beside the client: horizon-ctl, the command line and MCP server that
/// play the game, and horizon-prepare, which prepares the resources from the player's own
/// Minecraft.
const TOOLS: [&str; 2] = ["horizon-ctl", "horizon-prepare"];
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let result = match args.as_slice() {
[task, binary, out] if task == "package" => package(Path::new(binary), Path::new(out)),
_ => Err(USAGE.to_string()),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("xtask: {e}");
ExitCode::FAILURE
}
}
}
fn git(repo: &Path, args: &[&str]) -> Result<Vec<u8>, String> {
let output = Command::new("git")
.arg("-C")
.arg(repo)
.args(args)
.output()
.map_err(|e| format!("git: {e}"))?;
if !output.status.success() {
return Err(format!(
"git {}: {}",
args.join(" "),
String::from_utf8_lossy(&output.stderr).trim()
));
}
Ok(output.stdout)
}
fn package(binary: &Path, out: &Path) -> Result<(), String> {
let top = git(
Path::new(env!("CARGO_MANIFEST_DIR")),
&["rev-parse", "--show-toplevel"],
)?;
let repo = PathBuf::from(String::from_utf8_lossy(&top).trim());
match fs::remove_dir_all(out) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
return Err(format!("{}: {e}", out.display()));
}
_ => {}
}
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut args = vec!["archive", "--format=tar", "HEAD"];
args.extend(ARCHIVED);
extract(&git(&repo, &args)?, out)?;
copy_into(binary, out)?;
let exe = binary.extension().is_some_and(|e| e == "exe");
for tool in TOOLS {
let name = if exe {
format!("{tool}.exe")
} else {
tool.to_string()
};
let path = binary.parent().unwrap_or(Path::new("")).join(name);
if !path.is_file() {
return Err(format!(
"{} is missing; build it too: cargo build --release -p horizon-client --bins -p horizon-prepare",
path.display()
));
}
copy_into(&path, out)?;
}
let play = repo.join("packaging/PLAY.txt");
copy(&play, &out.join("PLAY.txt"))
}
/// `cp FILE DIR/`.
fn copy_into(file: &Path, dir: &Path) -> Result<(), String> {
let name = file
.file_name()
.ok_or_else(|| format!("{} is not a file", file.display()))?;
copy(file, &dir.join(name))
}
/// `cp FROM TO` to a new file: the source's mode within the umask, so the programs stay
/// executable.
fn copy(from: &Path, to: &Path) -> Result<(), String> {
let error = |e: std::io::Error| format!("{}: {e}", from.display());
let data = fs::read(from).map_err(error)?;
let permissions = fs::metadata(from).map_err(error)?.permissions();
#[cfg(unix)]
let mode = std::os::unix::fs::PermissionsExt::mode(&permissions);
#[cfg(not(unix))]
let mode = if permissions.readonly() { 0o444 } else { 0o666 };
create(to, &data, mode)
}
/// A new file holding `data`, created with `mode` within the process umask as tar and cp create
/// theirs (on Windows only the read-only bit counts).
fn create(path: &Path, data: &[u8], mode: u32) -> Result<(), String> {
use std::io::Write;
let error = |e: std::io::Error| format!("{}: {e}", path.display());
let mut options = fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, mode & 0o7777);
options
.open(path)
.and_then(|mut file| file.write_all(data))
.map_err(error)?;
if cfg!(not(unix)) && mode & 0o222 == 0 {
let mut permissions = fs::metadata(path).map_err(error)?.permissions();
permissions.set_readonly(true);
fs::set_permissions(path, permissions).map_err(error)?;
}
Ok(())
}
/// A NUL-terminated tar header field.
fn field(bytes: &[u8]) -> &[u8] {
&bytes[..bytes.iter().position(|b| *b == 0).unwrap_or(bytes.len())]
}
fn octal(bytes: &[u8]) -> Result<u64, String> {
let text = std::str::from_utf8(field(bytes)).map_err(|e| e.to_string())?;
let text = text.trim_matches(|c: char| c == ' ' || c == '\0');
u64::from_str_radix(if text.is_empty() { "0" } else { text }, 8)
.map_err(|e| format!("bad tar number {text:?}: {e}"))
}
/// `path` under `out`, refusing anything that would land outside it.
fn inside(out: &Path, path: &str) -> Result<PathBuf, String> {
let relative = Path::new(path.trim_end_matches('/'));
if !relative
.components()
.all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
{
return Err(format!("unsafe path in the archive: {path}"));
}
Ok(out.join(relative))
}
/// The `path` record of a pax extended header, if it has one.
fn pax_path(mut records: &[u8]) -> Result<Option<String>, String> {
let mut path = None;
while !records.is_empty() {
let space = records
.iter()
.position(|b| *b == b' ')
.ok_or("bad pax record")?;
let length: usize = std::str::from_utf8(&records[..space])
.ok()
.and_then(|n| n.parse().ok())
.filter(|n| *n > space && *n <= records.len())
.ok_or("bad pax record length")?;
let record = &records[space + 1..length - 1];
if let Some(value) = record.strip_prefix(b"path=") {
path = Some(String::from_utf8(value.to_vec()).map_err(|e| e.to_string())?);
}
records = &records[length..];
}
Ok(path)
}
/// `tar -x -C out` for the ustar/pax archives `git archive` writes: directories and regular
/// files, created with the archive's modes within the process umask as tar creates them for an
/// ordinary user, so executables stay executable.
fn extract(tar: &[u8], out: &Path) -> Result<(), String> {
let mut pos = 0;
let mut long_path = None;
while pos + 512 <= tar.len() {
let header = &tar[pos..pos + 512];
if header.iter().all(|b| *b == 0) {
return Ok(());
}
let size = octal(&header[124..136])? as usize;
let start = pos + 512;
let data = tar
.get(start..start + size)
.ok_or("the archive ends inside an entry")?;
pos = start + size.div_ceil(512) * 512;
let path = match long_path.take() {
Some(path) => path,
None => {
let name = String::from_utf8_lossy(field(&header[..100])).into_owned();
let prefix = String::from_utf8_lossy(field(&header[345..500])).into_owned();
if prefix.is_empty() {
name
} else {
format!("{prefix}/{name}")
}
}
};
let mode = octal(&header[100..108])? as u32;
match header[156] {
// The global header holds the commit id.
b'g' => {}
b'x' => long_path = pax_path(data)?,
b'5' => {
let dir = inside(out, &path)?;
let mut builder = fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, mode & 0o7777);
builder
.create(&dir)
.map_err(|e| format!("{}: {e}", dir.display()))?;
}
b'0' | 0 => {
let file = inside(out, &path)?;
if let Some(parent) = file.parent() {
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
create(&file, data, mode)?;
}
kind => {
return Err(format!(
"{path}: unsupported entry type {:?} in the archive",
kind as char
));
}
}
}
Err("the archive has no end".into())
}
#[cfg(test)]
mod tests {
use super::*;
fn header(name: &str, mode: u32, size: usize, kind: u8) -> Vec<u8> {
let mut h = vec![0u8; 512];
h[..name.len()].copy_from_slice(name.as_bytes());
h[100..107].copy_from_slice(format!("{mode:07o}").as_bytes());
h[124..135].copy_from_slice(format!("{size:011o}").as_bytes());
h[156] = kind;
h[257..263].copy_from_slice(b"ustar\0");
h
}
fn entry(tar: &mut Vec<u8>, name: &str, mode: u32, kind: u8, data: &[u8]) {
tar.extend(header(name, mode, data.len(), kind));
tar.extend(data);
tar.resize(tar.len().div_ceil(512) * 512, 0);
}
#[test]
fn archives_extract_with_their_paths_and_modes() {
let out = std::env::temp_dir().join(format!("xtask-extract-{}", std::process::id()));
let _ = fs::remove_dir_all(&out);
let long = format!("tools/{}/run.sh", "d".repeat(120));
let pax = format!("path={long}\n");
let pax = format!("{} {pax}", pax.len() + 4);
let mut tar = Vec::new();
entry(
&mut tar,
"pax_global_header",
0o666,
b'g',
b"52 comment=abc\n",
);
entry(&mut tar, "tools/", 0o775, b'5', b"");
entry(&mut tar, "tools/a.py", 0o664, b'0', b"print(1)\n");
entry(&mut tar, "tools/b.sh", 0o775, b'0', b"#!/bin/sh\n");
entry(&mut tar, "PaxHeaders/x", 0o666, b'x', pax.as_bytes());
entry(&mut tar, "ignored-name", 0o775, b'0', b"long\n");
tar.extend([0; 1024]);
extract(&tar, &out).unwrap();
assert_eq!(fs::read(out.join("tools/a.py")).unwrap(), b"print(1)\n");
assert_eq!(fs::read(out.join(&long)).unwrap(), b"long\n");
assert!(!out.join("ignored-name").exists());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = |p: &str| fs::metadata(out.join(p)).unwrap().permissions().mode();
assert_eq!(mode("tools/a.py") & 0o111, 0);
assert_eq!(mode("tools/b.sh") & 0o100, 0o100);
assert_eq!(mode(&long) & 0o100, 0o100);
assert_eq!(mode("tools") & 0o100, 0o100);
}
fs::remove_dir_all(&out).unwrap();
}
#[test]
fn archives_stay_inside_the_folder() {
let out = Path::new("out");
assert!(inside(out, "../x").is_err());
assert!(inside(out, "/etc/x").is_err());
assert_eq!(inside(out, "tools/").unwrap(), out.join("tools"));
let mut tar = Vec::new();
entry(&mut tar, "link", 0o777, b'2', b"");
tar.extend([0; 1024]);
assert!(extract(&tar, out).unwrap_err().contains("unsupported"));
}
}