diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml
index 79ea852fb..3346e1986 100644
--- a/.github/workflows/launcher.yml
+++ b/.github/workflows/launcher.yml
@@ -188,9 +188,6 @@ jobs:
retry "$launcher" install latest
"$launcher" versions --installed
"$launcher" links --json
- "$launcher" menu-style classic
- grep -qx 'menuStyle:classic' "$HORIZON_HOME/horizon.txt"
- "$launcher" menu-style horizon
clients=("$HORIZON_LAUNCHER_HOME"/versions/v*/horizon-client*)
client="${clients[0]}"
echo "installed client: $client"
diff --git a/README.md b/README.md
index 72b6a3496..4abb52b86 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these.
- **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status).
- **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings).
- **Resource packs, shader packs and data packs:** resource packs work, Java shader packs run their full-screen effects (experimental), and data packs load functions, predicates and item modifiers.
-- **Playing with others:** invite friends from the pause menu with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
+- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
- **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods).
Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders:
@@ -56,8 +56,8 @@ Screenshots, captured in the Rust client itself with vanilla assets and no mods
-
-
+
+
diff --git a/crates/horizon-client/examples/firework_tooltip_fixture.rs b/crates/horizon-client/examples/firework_tooltip_fixture.rs
index 196fa9955..7f10278b7 100644
--- a/crates/horizon-client/examples/firework_tooltip_fixture.rs
+++ b/crates/horizon-client/examples/firework_tooltip_fixture.rs
@@ -1,7 +1,7 @@
//! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the
//! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line;
//! the `#resources` line names the prepared resources for en_us).
-use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language};
+use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines};
use std::{error::Error, fmt::Write, path::PathBuf};
fn main() -> Result<(), Box> {
@@ -12,8 +12,9 @@ fn main() -> Result<(), Box> {
.find_map(|l| l.strip_prefix("#resources "))
.map(PathBuf::from)
.ok_or("no #resources line")?;
- let language = Language::load(&[&root], "en_us");
- let translate = |key: &str| language.get(key).map(str::to_owned);
+ // Use the inventory's filtered translations so missing tooltip keys are caught.
+ let enchantments = Enchantments::load(&root);
+ let translate = |key: &str| enchantments.translate(key).map(str::to_owned);
let mut output = String::new();
for line in input.lines().filter(|l| !l.starts_with('#')) {
let stack = parse_stack(line)?.ok_or("empty stack")?;
diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/held_drop_fixture.rs
index 87ca9870c..a0c5d92ba 100644
--- a/crates/horizon-client/examples/held_drop_fixture.rs
+++ b/crates/horizon-client/examples/held_drop_fixture.rs
@@ -14,13 +14,22 @@ fn main() {
for count in [0, 1, 4, 64] {
let mut slot = Some(ItemStack::new("minecraft:stone", count));
let mut dropped = 0;
+ let mut swings = 0;
+ let mut packets = 0;
for _ in 0..2 {
if let Some(stack) =
take_held_drop(&mut slot, all, mode == GameMode::Spectator)
{
dropped += stack.count;
+ swings += 1;
}
- println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped);
+ if mode != GameMode::Spectator {
+ packets += 1;
+ }
+ println!(
+ "{} {dropped} {swings} {packets}",
+ slot.as_ref().map_or(0, |s| s.count),
+ );
}
}
}
diff --git a/crates/horizon-client/examples/load_bench.rs b/crates/horizon-client/examples/load_bench.rs
new file mode 100644
index 000000000..5c30a71ff
--- /dev/null
+++ b/crates/horizon-client/examples/load_bench.rs
@@ -0,0 +1,153 @@
+//! Read-only saved chunk benchmark. All timings exclude resource/corpus setup.
+//!
+//! load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum]
+//! Add --profile-worker when a sampling collector cannot sample the main thread.
+//! Reports warm filesystem SaveDir::load (read, inflate, NBT, decode and light),
+//! plus isolated inflate/NBT and native decode. No files in the save are changed.
+use horizon_client::{
+ assets::Assets,
+ biome::Biomes,
+ blocks::BlockFacts,
+ save::{SaveDir, SaveTables, decode_with},
+};
+use horizon_world::{nbt::Limits, region::RegionFile};
+use sha2::{Digest, Sha256};
+use std::{hint::black_box, path::PathBuf, sync::Arc, time::Instant};
+
+type Result = std::result::Result>;
+
+fn main() -> Result<()> {
+ if std::env::args().any(|a| a == "--profile-worker") {
+ std::thread::spawn(|| run().map_err(|e| e.to_string()))
+ .join()
+ .expect("benchmark worker")
+ .map_err(Into::into)
+ } else {
+ run()
+ }
+}
+
+fn run() -> Result<()> {
+ let args: Vec = std::env::args().skip(1).collect();
+ let usage = "load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum]";
+ let root = PathBuf::from(args.first().ok_or(usage)?);
+ let dimension = PathBuf::from(args.get(1).ok_or(usage)?);
+ let flag = |name: &str, default: usize| -> Result {
+ Ok(match args.iter().position(|a| a == name) {
+ Some(i) => args.get(i + 1).ok_or(usage)?.parse()?,
+ None => default,
+ })
+ };
+ let rounds = flag("--rounds", 5)?;
+ let limit = flag("--limit", 256)?;
+ if rounds == 0 || limit == 0 {
+ return Err("rounds and limit must be positive".into());
+ }
+ let assets = Assets::load(&root)?;
+ let facts = BlockFacts::load(&root, assets.registry)?;
+ let biomes = Biomes::load(&root)?;
+ let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts));
+ let source = SaveDir::new(dimension.clone());
+ let _ = source.tables.set(tables.clone());
+ let mut paths: Vec<_> = std::fs::read_dir(dimension.join("region"))?
+ .map(|e| e.map(|e| e.path()))
+ .collect::>()?;
+ paths.retain(|p| p.extension().is_some_and(|e| e == "mca"));
+ paths.sort();
+ let mut corpus = Vec::new();
+ 'regions: for path in paths {
+ let mut region = RegionFile::open(path)?;
+ let mut positions: Vec<_> = region.chunks().map(|(pos, _)| pos).collect();
+ positions.sort_by_key(|p| (p.x, p.z));
+ for pos in positions {
+ let record = region.read(pos)?.ok_or("missing record")?;
+ let tag = record.nbt(Limits::default())?;
+ if decode_with(&tag, assets.registry, &biomes, Some(&tables)).is_none() {
+ continue;
+ }
+ corpus.push((pos, record, tag));
+ if corpus.len() == limit {
+ break 'regions;
+ }
+ }
+ }
+ if corpus.is_empty() {
+ return Err("no full chunks in corpus".into());
+ }
+ let mut records_hash = Sha256::new();
+ for (pos, record, _) in &corpus {
+ records_hash.update(pos.x.to_le_bytes());
+ records_hash.update(pos.z.to_le_bytes());
+ records_hash.update((record.compressed.len() as u64).to_le_bytes());
+ records_hash.update(&record.compressed);
+ }
+ println!(
+ "{}",
+ serde_json::json!({"corpus": dimension, "chunks": corpus.len(), "rounds": rounds,
+ "compressed_records_sha256": format!("{:x}", records_hash.finalize()),
+ "compressed_bytes": corpus.iter().map(|(_, r, _)| r.compressed.len()).sum::()})
+ );
+ // Prime SaveDir's region handles and the filesystem cache before measurement.
+ for (pos, _, _) in &corpus {
+ black_box(
+ source
+ .load(pos.x, pos.z, assets.registry, &biomes)
+ .ok_or("load failed")?,
+ );
+ }
+ for round in 0..rounds {
+ let started = Instant::now();
+ for (pos, _, _) in &corpus {
+ black_box(
+ source
+ .load(pos.x, pos.z, assets.registry, &biomes)
+ .ok_or("load failed")?,
+ );
+ }
+ let load_s = started.elapsed().as_secs_f64();
+ let started = Instant::now();
+ for (_, record, _) in &corpus {
+ black_box(record.nbt(Limits::default())?);
+ }
+ let nbt_s = started.elapsed().as_secs_f64();
+ let started = Instant::now();
+ for (_, _, tag) in &corpus {
+ black_box(
+ decode_with(tag, assets.registry, &biomes, Some(&tables)).ok_or("decode failed")?,
+ );
+ }
+ let decode_s = started.elapsed().as_secs_f64();
+ println!(
+ "{}",
+ serde_json::json!({"round": round, "load_s": load_s,
+ "inflate_nbt_s": nbt_s, "decode_s": decode_s})
+ );
+ }
+ if args.iter().any(|a| a == "--checksum") {
+ let mut hash = Sha256::new();
+ let mut light_loaded = 0;
+ for (pos, _, _) in &corpus {
+ let chunk = source
+ .load(pos.x, pos.z, assets.registry, &biomes)
+ .ok_or("load failed")?;
+ hash.update(pos.x.to_le_bytes());
+ hash.update(pos.z.to_le_bytes());
+ light_loaded += usize::from(chunk.light_loaded);
+ for section in &chunk.sections {
+ for i in 0..4096 {
+ hash.update(section.get(i).to_le_bytes());
+ hash.update([section.light(i)]);
+ }
+ for i in 0..64 {
+ hash.update(section.biomes.get(i).to_le_bytes());
+ }
+ }
+ }
+ println!(
+ "{}",
+ serde_json::json!({"blocks_biomes_light_sha256": format!("{:x}", hash.finalize()),
+ "light_loaded": light_loaded})
+ );
+ }
+ Ok(())
+}
diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs
index 2a4969221..a3abb54d9 100644
--- a/crates/horizon-client/examples/mob_ai_probe.rs
+++ b/crates/horizon-client/examples/mob_ai_probe.rs
@@ -1027,6 +1027,7 @@ fn main() -> horizon_client::Result<()> {
nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position),
others: $snapshot,
others_grid: $grid,
+ others_index: None,
daylight: (world.day_time.rem_euclid(24000)) < 12000,
game_time: world.game_time,
day_time: world.day_time,
@@ -1132,7 +1133,7 @@ fn main() -> horizon_client::Result<()> {
}
#[allow(unused_mut)] // filled only with the rng-trace feature
let mut traces: Vec = Vec::new();
- let mut pushes = Vec::new();
+ let mut pushes = horizon_client::mobs::PendingPushes::default();
let mut born = Vec::new();
for i in 0..mobs.len() {
if mobs[i].removed {
diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs
index 9f8e99899..b8c56b28c 100644
--- a/crates/horizon-client/examples/streaming_bench.rs
+++ b/crates/horizon-client/examples/streaming_bench.rs
@@ -3,6 +3,7 @@
//! what the render thread pays for it in `Streaming::update`.
//!
//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F]
+//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z]
//!
//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x
//! at that speed for T seconds while frames run at F per second. Each phase reports
@@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator;
type Result = std::result::Result>;
+fn cpu_seconds() -> f64 {
+ std::fs::read_to_string("/proc/self/stat")
+ .ok()
+ .and_then(|stat| {
+ let fields = stat
+ .rsplit_once(')')?
+ .1
+ .split_whitespace()
+ .collect::>();
+ Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0)
+ })
+ .unwrap_or(0.0)
+}
+
#[derive(Default)]
struct Phase {
updates: Vec,
local: (u64, u64),
uploads: usize,
+ stage_samples: [u64; 7],
+ cpu_start: f64,
}
impl Phase {
fn update(&mut self, streaming: &mut Streaming, world: &mut World) {
+ if self.updates.is_empty() {
+ self.cpu_start = cpu_seconds();
+ }
let before = LOCAL.with(Cell::get);
let started = Instant::now();
let (uploads, _) = streaming.update(world);
@@ -89,6 +109,9 @@ impl Phase {
self.local.1 += after.1 - before.1;
self.uploads += uploads.len();
drop(uploads);
+ for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) {
+ *sum += count as u64;
+ }
}
fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) {
let mut sorted = self.updates.clone();
@@ -106,6 +129,16 @@ impl Phase {
at(0.99),
sorted.last().copied().unwrap_or(0.0),
);
+ println!(
+ "BENCH {}",
+ serde_json::json!({
+ "phase": name, "wall_s": wall.as_secs_f64(),
+ "cpu_s": cpu_seconds() - self.cpu_start,
+ "chunks": streaming.generated_total - generated, "sections": self.uploads,
+ "updates": self.updates.len(), "update_ms": total,
+ "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64),
+ })
+ );
if TRACK {
println!(
" update allocations: {} ({:.1} MiB)",
@@ -142,6 +175,22 @@ fn main() -> Result<()> {
let fly = flag("--fly", 0.0);
let seconds = flag("--seconds", 10.0);
let hz = flag("--hz", 240.0);
+ let dimension = args
+ .iter()
+ .position(|a| a == "--dimension")
+ .and_then(|i| args.get(i + 1))
+ .map(|d| {
+ if d.contains(':') {
+ d.clone()
+ } else {
+ format!("minecraft:{d}")
+ }
+ })
+ .unwrap_or_else(|| "minecraft:overworld".into());
+ let center = (
+ flag("--center-x", 0.0) as i32,
+ flag("--center-z", 0.0) as i32,
+ );
let assets = Arc::new(Assets::load(&root)?);
let render = Arc::new(assets.reload(&root)?);
@@ -154,11 +203,12 @@ fn main() -> Result<()> {
models::load_visibility(&root, assets.registry)?,
)?);
let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?);
- let terrain = Arc::new(VanillaTerrain::new(
+ let terrain = Arc::new(VanillaTerrain::for_dimension(
&root.join("worldgen"),
assets.registry,
&biomes,
seed,
+ &dimension,
)?);
let context = Arc::new(WorkerContext {
assets,
@@ -170,8 +220,12 @@ fn main() -> Result<()> {
let mut world = World::new(facts.air, seed);
let mut streaming = Streaming::new(terrain, context, threads);
streaming.radius = radius;
- streaming.center = (0, 0);
- println!("{threads} workers, radius {radius}, seed {seed}");
+ streaming.center = center;
+ streaming.nether_shading = dimension == "minecraft:the_nether";
+ streaming.sky_light = dimension != "minecraft:the_nether";
+ println!(
+ "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}"
+ );
let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed));
// Fill: update as often as the game would uncapped, until settled.
@@ -198,12 +252,12 @@ fn main() -> Result<()> {
let mut behind = Vec::new();
while started.elapsed().as_secs_f64() < seconds {
let next = Instant::now() + frame;
- let x = (started.elapsed().as_secs_f64() * fly) as i32;
- streaming.center = (x, 0);
+ let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32;
+ streaming.center = (x, center.1);
phase.update(&mut streaming, &mut world);
// Columns within 2 chunks of the player still missing their meshes.
let near = (-2..=2)
- .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz)))
+ .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz)))
.filter(|&(cx, cz)| !streaming.is_lit(cx, cz))
.count();
behind.push(near);
diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/weather_fixture.rs
index 15aab6bdb..3cf6c31be 100644
--- a/crates/horizon-client/examples/weather_fixture.rs
+++ b/crates/horizon-client/examples/weather_fixture.rs
@@ -11,6 +11,7 @@ fn bits(value: f32) -> String {
fn main() -> Result<(), Box> {
let args: Vec<_> = std::env::args().collect();
let mut output = String::new();
+ let mut parameters = weather::ParameterCache::default();
for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() {
let p: Vec<&str> = line.split_whitespace().collect();
let int = |i: usize| p[i].parse::().unwrap();
@@ -38,6 +39,13 @@ fn main() -> Result<(), Box> {
bits(column.v_offset),
column.light_coords
)?;
+ assert_eq!(
+ parameters
+ .get(x, z)
+ .column(kind != 0, ticks, x, bottom, top, z, light, partial),
+ column,
+ "cached parameters differ from original random source at case {case}"
+ );
let max_alpha = if kind == 0 { 1.0 } else { 0.8 };
for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) {
write!(
diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs
index 6a135799c..854332815 100644
--- a/crates/horizon-client/src/containers.rs
+++ b/crates/horizon-client/src/containers.rs
@@ -528,7 +528,7 @@ impl Furnace {
let has_fuel = self.items[1].is_some();
if lit || has_fuel && has_ingredient {
if let Some(ingredient) = self.items[0].clone() {
- if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient).cloned() {
+ if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient) {
if self.cooking_timer == 0 {
self.cooking_total = total_time(recipe.time, self.speed);
}
diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs
index e96ca0067..d0b8906ee 100644
--- a/crates/horizon-client/src/crafting.rs
+++ b/crates/horizon-client/src/crafting.rs
@@ -1102,7 +1102,11 @@ pub struct Recipes {
facts: HashMap, Facts>,
/// The `#minecraft:curse` enchantments.
curses: HashSet,
+ /// The first cooking recipe of each kind taking each item, built at the
+ /// first lookup (furnaces look theirs up every tick).
+ cook_index: std::sync::OnceLock,
}
+type CookIndex = HashMap>;
/// `MinMaxBounds.Ints` as (min, max) with the given defaults.
fn bounds(v: Option<&Value>, default: (i64, i64), open: (i64, i64)) -> (i64, i64) {
match v {
@@ -1421,6 +1425,7 @@ impl Recipes {
meta,
facts,
curses,
+ cook_index: Default::default(),
})
}
/// Match a `size`x`size` grid (row-major) against the crafting recipes.
@@ -1606,6 +1611,22 @@ impl Recipes {
out
}
pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> {
+ let index = self.cook_index.get_or_init(|| {
+ let mut index = CookIndex::new();
+ for (i, c) in self.cooking.iter().enumerate() {
+ let of_kind = index.entry(c.kind.clone()).or_default();
+ for item in &c.ingredient.0 {
+ of_kind.entry(item.clone()).or_insert(i);
+ }
+ }
+ index
+ });
+ let i = *index.get(kind)?.get(&*input.item)?;
+ self.cooking.get(i)
+ }
+ /// `cook` by scanning every recipe, as it was before the index.
+ #[cfg(test)]
+ fn cook_scan(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> {
self.cooking
.iter()
.find(|c| c.kind == kind && c.ingredient.test(input))
@@ -1625,6 +1646,80 @@ mod tests {
s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")];
s
}
+ /// About vanilla's count of cooking recipes: four kinds, ingredients of
+ /// one to twelve items, overlapping (several recipes take some items).
+ fn cooking_book() -> Recipes {
+ let kinds = ["smelting", "blasting", "smoking", "campfire_cooking"];
+ let cooking = (0..320usize)
+ .map(|i| Cooking {
+ id: format!("r{i}"),
+ category: "misc".into(),
+ group: String::new(),
+ kind: kinds[i % 4].into(),
+ ingredient: ingredient(
+ &(0..1 + i % 12)
+ .map(|k| format!("minecraft:item_{}", (i * 7 + k * 13) % 400))
+ .collect::>()
+ .iter()
+ .map(String::as_str)
+ .collect::>(),
+ ),
+ result: ItemStack::new("minecraft:stone", 1),
+ experience: 0.1,
+ time: 200,
+ })
+ .collect();
+ Recipes {
+ crafting: Vec::new(),
+ cooking,
+ meta: HashMap::new(),
+ facts: HashMap::new(),
+ curses: HashSet::new(),
+ cook_index: Default::default(),
+ }
+ }
+ #[test]
+ fn cook_finds_the_first_recipe_the_scan_finds() {
+ let recipes = cooking_book();
+ for kind in [
+ "smelting",
+ "blasting",
+ "smoking",
+ "campfire_cooking",
+ "other",
+ ] {
+ for n in 0..420 {
+ let stack = ItemStack::new(&format!("minecraft:item_{n}"), 1);
+ let a = recipes.cook(kind, &stack).map(|c| &c.id);
+ let b = recipes.cook_scan(kind, &stack).map(|c| &c.id);
+ assert_eq!(a, b, "{kind} item_{n}");
+ }
+ }
+ }
+ /// A furnace's recipe lookup, once per lit furnace per tick.
+ #[test]
+ #[ignore]
+ fn cook_cost() {
+ let recipes = cooking_book();
+ let stacks: Vec = (0..1000)
+ .map(|n| ItemStack::new(&format!("minecraft:item_{}", n % 400), 1))
+ .collect();
+ let t = std::time::Instant::now();
+ let a = stacks
+ .iter()
+ .filter(|s| recipes.cook_scan("smelting", s).cloned().is_some())
+ .count();
+ let before = t.elapsed().as_secs_f64() * 1e3;
+ recipes.cook("smelting", &stacks[0]);
+ let t = std::time::Instant::now();
+ let b = stacks
+ .iter()
+ .filter(|s| recipes.cook("smelting", s).is_some())
+ .count();
+ let after = t.elapsed().as_secs_f64() * 1e3;
+ assert_eq!(a, b);
+ println!("1000 furnace lookups (scan and clone -> index): {before:.3} ms -> {after:.3} ms");
+ }
fn run(special: &Special, cells: &[ItemStack]) -> Option {
let recipes = Recipes {
crafting: Vec::new(),
@@ -1632,6 +1727,7 @@ mod tests {
meta: HashMap::new(),
facts: HashMap::new(),
curses: HashSet::new(),
+ cook_index: Default::default(),
};
let ctx = Context {
recipes: &recipes,
diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs
index 039ea658f..ca2ea6f5c 100644
--- a/crates/horizon-client/src/enchant.rs
+++ b/crates/horizon-client/src/enchant.rs
@@ -193,6 +193,8 @@ impl Enchantments {
|| k.starts_with("item.minecraft.splash_potion")
|| k.starts_with("item.minecraft.lingering_potion")
|| k.starts_with("item.minecraft.tipped_arrow")
+ || k.starts_with("item.minecraft.firework_rocket.")
+ || k.starts_with("item.minecraft.firework_star.")
|| k.starts_with("trim_")
|| k.starts_with("potion.")
|| k.starts_with("container.")
diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs
index ed8fe4dec..cfbdb0636 100644
--- a/crates/horizon-client/src/entities.rs
+++ b/crates/horizon-client/src/entities.rs
@@ -583,6 +583,10 @@ pub struct ArmorStand {
pub no_base_plate: bool,
pub invisible: bool,
pub marker: bool,
+ /// `CustomName`: the text of a hologram.
+ pub custom_name: Option,
+ /// `CustomNameVisible`.
+ pub name_visible: bool,
/// Game time of the last hit (the wobble and the second-hit window).
pub last_hit: i64,
}
@@ -603,6 +607,8 @@ impl ArmorStand {
no_base_plate: false,
invisible: false,
marker: false,
+ custom_name: None,
+ name_visible: false,
last_hit: i64::MIN / 2,
}
}
diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl
index 2c6af26f9..2e865dfb1 100644
--- a/crates/horizon-client/src/entity.wgsl
+++ b/crates/horizon-client/src/entity.wgsl
@@ -43,6 +43,7 @@ struct Out {
@location(8) back_color: vec4,
// entity.vsh's lightMapColor, multiplied in after the overlay.
@location(9) light_color: vec4,
+ @location(10) @interpolate(flat) weather_rect: vec4,
}
// Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed.
fn entity_light(normal: vec3, nether: bool) -> f32 {
@@ -109,6 +110,13 @@ fn entity_vertex(position: vec3, uv: vec2,
@location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out {
return entity_vertex(position, uv, overlay, color, light, normal);
}
+// Retained bolt-local geometry, translated using the same f64 camera
+// subtraction as the former CPU path before adding each local f32 position.
+@vertex fn vs_lightning(@location(0) position: vec3, @location(1) uv: vec2,
+ @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4,
+ @location(6) offset: vec3) -> Out {
+ return entity_vertex(offset + position, uv, overlay, color, light, normal);
+}
struct CloudInfo {
offset: vec4,
colors: array, 4>,
@@ -209,3 +217,135 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
@fragment fn fs_water_mask() -> @location(0) vec4 {
return vec4(0.0);
}
+
+// WEATHER_MATH_BEGIN
+// Unsigned 64-bit helpers (low word first). Snow adds a random double to a
+// float drift before casting to float. Retaining the 53-bit base avoids early
+// rounding, including ties, without requiring optional GPU float64 support.
+fn weather_shr_jam(v: vec2, n: u32) -> vec2 {
+ if n == 0u { return v; }
+ if n < 32u {
+ return vec2((v.x >> n) | (v.y << (32u - n)) | select(0u, 1u, (v.x << (32u - n)) != 0u), v.y >> n);
+ }
+ if n == 32u { return vec2(v.y | select(0u, 1u, v.x != 0u), 0u); }
+ if n < 64u {
+ return vec2((v.y >> (n - 32u)) | select(0u, 1u, v.x != 0u || (v.y << (64u - n)) != 0u), 0u);
+ }
+ return vec2(select(0u, 1u, any(v != vec2(0u))), 0u);
+}
+fn weather_add64(a: vec2, b: vec2) -> vec2 {
+ let lo = a.x + b.x;
+ return vec2(lo, a.y + b.y + select(0u, 1u, lo < a.x));
+}
+fn weather_sub64(a: vec2, b: vec2) -> vec2 {
+ return vec2(a.x - b.x, a.y - b.y - select(0u, 1u, a.x < b.x));
+}
+fn weather_double_plus_float(base: vec2, delta: f32) -> f32 {
+ // The random base is nonnegative and either zero or >= 2^-53.
+ if all(base == vec2(0u)) { return select(delta, 0.0, delta == 0.0); }
+ let db = bitcast(delta);
+ let mag = db & 0x7fffffffu;
+ let be = i32((base.y >> 20u) & 2047u) - 1023;
+ var de = i32(mag >> 23u) - 127;
+ var dm = (mag & 0x7fffffu) | 0x800000u;
+ if mag < 0x800000u {
+ dm = mag;
+ if dm == 0u { de = -200; }
+ else {
+ let shift = countLeadingZeros(dm) - 8u;
+ dm <<= shift;
+ de = -126 - i32(shift);
+ }
+ }
+ let e = max(be, de);
+ // Leading significand bit at 61, with room for addition and guard bits.
+ var a = vec2(base.x << 9u, ((base.y & 0xfffffu) | 0x100000u) << 9u | (base.x >> 23u));
+ var b = vec2(0u, dm << 6u);
+ a = weather_shr_jam(a, u32(e - be));
+ b = weather_shr_jam(b, u32(e - de));
+ var sign = 0u;
+ var value: vec2;
+ if (db >> 31u) == 0u { value = weather_add64(a, b); }
+ else if a.y > b.y || (a.y == b.y && a.x >= b.x) { value = weather_sub64(a, b); }
+ else { value = weather_sub64(b, a); sign = 0x80000000u; }
+ if all(value == vec2(0u)) { return 0.0; }
+ let leading = select(31u - countLeadingZeros(value.x), 63u - countLeadingZeros(value.y), value.y != 0u);
+ var exponent = e + i32(leading) - 61;
+ // Normalize the leading bit to 62. After jamming, bit 38 is the guard
+ // bit and bits 0..37 distinguish a tie from a value above the midpoint.
+ let shift = 62u - leading;
+ if shift >= 32u { value = vec2(0u, value.x << (shift - 32u)); }
+ else if shift != 0u { value = vec2(value.x << shift, (value.y << shift) | (value.x >> (32u - shift))); }
+ // Vanilla first rounds the addition to double, then casts to float.
+ // Round at bit 10 (53 retained bits) before the 24-bit rounding below;
+ // otherwise a double-rounding midpoint can select the wrong float.
+ let double_guard = (value.x & 512u) != 0u;
+ let double_sticky = (value.x & 511u) != 0u;
+ let double_odd = (value.x & 1024u) != 0u;
+ value.x &= 0xfffffc00u;
+ if double_guard && (double_sticky || double_odd) {
+ value = weather_add64(value, vec2(1024u, 0u));
+ }
+ if (value.y & 0x80000000u) != 0u {
+ value = weather_shr_jam(value, 1u);
+ exponent += 1;
+ }
+ var mantissa = value.y >> 7u;
+ let guard = (value.y & 64u) != 0u;
+ let sticky = (value.y & 63u) != 0u || value.x != 0u;
+ if guard && (sticky || (mantissa & 1u) != 0u) { mantissa += 1u; }
+ if mantissa >= 0x1000000u { mantissa >>= 1u; exponent += 1; }
+ return bitcast(sign | (u32(exponent + 127) << 23u) | (mantissa & 0x7fffffu));
+}
+fn weather_phase(animation: vec4, bases: vec4, snow: u32, time: vec4) -> vec2 {
+ if snow == 0u {
+ let ticks = time.x + animation.y;
+ let t = ticks + time.z;
+ let step = -t / 32.0;
+ let offset = step * animation.x;
+ return vec2(0.0, offset % 32.0);
+ }
+ let t = time.x + time.z;
+ let u_time = t * 0.01;
+ let du = u_time * animation.z;
+ let v_time = t * animation.w;
+ let dv = v_time * 0.001;
+ let u = weather_double_plus_float(bases.xy, du);
+ let v = weather_double_plus_float(bases.zw, dv);
+ let fall_time = time.y + time.z;
+ let fall = -fall_time / 512.0;
+ return vec2(u, fall + v);
+}
+// Atlas sampler is nearest with no mipmaps. Clamp the integer texel inside
+// the sprite even when a fractional coordinate rounds up at its far edge.
+fn weather_texel(uv: vec2, rect: vec4, dimensions: vec2) -> vec2 {
+ let size = vec2(dimensions);
+ let origin = vec2(round(rect.xy * size));
+ let extent = max(vec2(round(rect.zw * size)), vec2(1));
+ let local = min(vec2(floor(fract(uv) * vec2(extent))), extent - vec2(1));
+ return origin + local;
+}
+// WEATHER_MATH_END
+
+struct WeatherTime { values: vec4 }
+@group(1) @binding(1) var weather_time: WeatherTime;
+@vertex fn vs_weather(@location(0) position: vec3, @location(1) uv: vec2,
+ @location(2) rect: vec4, @location(3) animation: vec4,
+ @location(4) bases: vec4, @location(5) color: vec4,
+ @location(6) light: vec4, @location(7) snow: u32) -> Out {
+ let phase = weather_phase(animation, bases, snow, weather_time.values);
+ var out = entity_vertex(position, uv + phase, 0u, color, light, vec4(0.0));
+ out.weather_rect = rect;
+ return out;
+}
+@fragment fn fs_weather(in: Out) -> @location(0) vec4 {
+ // Repeat within this sprite, never across the atlas. The atlas uses nearest
+ // filtering and no mipmaps, so fractional UVs have no seam derivatives.
+ let texel = weather_texel(in.uv, in.weather_rect, textureDimensions(atlas));
+ var color = textureLoad(atlas, texel, 0) * in.color;
+ if color.a < 0.1 { discard; }
+ color *= in.light_color;
+ let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
+ linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
+ return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
+}
diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs
index d9cf20db5..aaccdd844 100644
--- a/crates/horizon-client/src/entity_nbt.rs
+++ b/crates/horizon-client/src/entity_nbt.rs
@@ -13,6 +13,7 @@ use crate::{
doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text,
uuid_from_tag,
},
+ text::Text,
};
use horizon_core::geometry::Vec3;
use horizon_world::nbt::{Compound, Tag};
@@ -555,6 +556,14 @@ fn custom_name(tag: &Tag) -> Option {
_ => None,
}
}
+/// `CustomName` as text: a string keeps its legacy formatting codes, anything
+/// else is a component (`ComponentSerialization`).
+pub fn name_text(tag: &Tag) -> Text {
+ match tag {
+ Tag::String(s) => Text::legacy(&s.to_string_lossy()),
+ t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)),
+ }
+}
pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option {
let kind = types.get(&self::kind(tag)?)?.clone();
let position = position(tag)?;
@@ -606,6 +615,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -
m.persistent = flag(tag, "PersistenceRequired");
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
m.custom_name = custom_name(tag);
+ m.custom_name_text = tag.get("CustomName").map(name_text);
if m.kind.category == "creature" {
m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32;
m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32;
@@ -1266,6 +1276,21 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) ->
} else if let Tag::Compound(map) = &mut tag {
map.remove(&"Marker".into());
}
+ if a.name_visible {
+ put(&mut tag, "CustomNameVisible", Tag::Byte(1));
+ } else if let Tag::Compound(map) = &mut tag {
+ map.remove(&"CustomNameVisible".into());
+ }
+ // A name from the save keeps its own shape unless it changed.
+ if let Some(name) = &a.custom_name
+ && !tag.get("CustomName").is_some_and(|t| name_text(t) == *name)
+ {
+ put(
+ &mut tag,
+ "CustomName",
+ crate::scoreboard::json_to_tag(&name.component()),
+ );
+ }
put(&mut tag, "Health", Tag::Float(a.health.to_bits()));
put(&mut tag, "Fire", Tag::Short(a.fire_ticks as i16));
// LivingEntity.addAdditionalSaveData and ArmorStand's own fields.
@@ -1294,6 +1319,8 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option {
a.velocity = motion(tag);
a.health = float(tag.get("Health")).unwrap_or(20.0) as f32;
a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32;
+ a.custom_name = tag.get("CustomName").map(name_text);
+ a.name_visible = flag(tag, "CustomNameVisible");
if let Some(eq) = tag.get("equipment") {
for (i, slot) in ArmorStand::SLOTS.iter().enumerate() {
a.equipment[i] = eq.get(slot).and_then(item_from_nbt);
@@ -1574,6 +1601,31 @@ mod tests {
assert!(ominous_item_spawner_from_nbt(&raw).is_none());
}
+ #[test]
+ fn armor_stand_names_keep_their_formatting_across_a_save() {
+ let tag = Tag::compound([
+ (
+ "Pos",
+ Tag::List(vec![
+ Tag::Double(0.0f64.to_bits()),
+ Tag::Double(64.0f64.to_bits()),
+ Tag::Double(0.0f64.to_bits()),
+ ]),
+ ),
+ ("CustomName", string("§6Hello")),
+ ("CustomNameVisible", Tag::Byte(1)),
+ ]);
+ let a = armor_stand_from_nbt(&tag, 7).unwrap();
+ let name = a.custom_name.as_ref().unwrap();
+ assert_eq!(name.plain(), "Hello");
+ assert!(name.spans[0].style.color.is_some());
+ assert!(a.name_visible);
+ let saved = armor_stand_to_nbt(&a, [0; 4], Some(&tag));
+ let restored = armor_stand_from_nbt(&saved, 7).unwrap();
+ assert_eq!(restored.custom_name, a.custom_name);
+ assert!(restored.name_visible);
+ }
+
#[test]
fn falling_block_round_trip_keeps_impact_distance_and_settings() {
let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]);
diff --git a/crates/horizon-client/src/friends_screen.rs b/crates/horizon-client/src/friends_screen.rs
new file mode 100644
index 000000000..7577e2add
--- /dev/null
+++ b/crates/horizon-client/src/friends_screen.rs
@@ -0,0 +1,303 @@
+//! Play with Friends: Horizon's own sharing of the open world behind an
+//! invite code (`game/friends.rs`). The pause menu's Friends button, the icon
+//! vanilla's PauseScreen already has, opens it. It is drawn the way a mod adds
+//! a screen to vanilla: the menu background, a centred title and text,
+//! vanilla's buttons and Done in the footer.
+use crate::{
+ hud::{HudAtlas, HudBatch, rgba},
+ multiplayer::wrap,
+ text::Text,
+ ui,
+};
+
+pub const TITLE: &str = "Play with Friends";
+/// What the screen shows (game/friends.rs fills it).
+#[derive(Clone, Debug, Default)]
+pub struct FriendsView {
+ /// A singleplayer world (not a server): sharing is offered.
+ pub shown: bool,
+ pub sharing: bool,
+ pub code: Option,
+ /// Who can join and what to do when friends on the internet can't (or,
+ /// before the code, what the game is doing).
+ pub status: String,
+ /// Friends on the internet can reach the host.
+ pub reachable: bool,
+ /// Where the troubleshooting is, when they can't.
+ pub help: Option,
+ /// The players in the world besides the host.
+ pub guests: Vec,
+ pub notice: Option,
+ /// The code was just copied.
+ pub copied: bool,
+}
+
+/// A button's action.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Action {
+ Share,
+ Copy,
+ Stop,
+ /// Open the troubleshooting page.
+ Help,
+ Done,
+}
+
+fn grey() -> u32 {
+ rgba(160, 160, 160, 255)
+}
+const WHITE: u32 = u32::MAX;
+const HINT: &str = "Friends paste the code after the title screen's Friends button, in Direct Connection, or on the launcher's Play page.";
+
+struct Button {
+ x: f32,
+ y: f32,
+ w: f32,
+ label: &'static str,
+ action: Action,
+ active: bool,
+}
+
+/// The centred lines (text, colour, y) and the buttons.
+fn layout(
+ atlas: &HudAtlas,
+ (w, h): (f32, f32),
+ view: &FriendsView,
+) -> (Vec<(String, u32, f32)>, Vec) {
+ let width = (w - 40.0).min(310.0);
+ let cx = (w / 2.0).floor();
+ let mut lines = Vec::new();
+ let mut y = 40.0;
+ let add = |lines: &mut Vec<(String, u32, f32)>, text: &str, color: u32, y: &mut f32| {
+ for line in wrap(text, width, atlas) {
+ lines.push((line, color, *y));
+ *y += 10.0;
+ }
+ };
+ let mut buttons = Vec::new();
+ if view.sharing {
+ lines.push(("Invite Code".to_owned(), grey(), y));
+ y += 12.0;
+ match &view.code {
+ Some(code) => {
+ for line in code_lines(atlas, code, width) {
+ lines.push((line, WHITE, y));
+ y += 10.0;
+ }
+ }
+ None => add(&mut lines, &view.status, WHITE, &mut y),
+ }
+ y += 6.0;
+ buttons.push(Button {
+ x: cx - 154.0,
+ y,
+ w: 150.0,
+ label: if view.copied { "Copied" } else { "Copy Code" },
+ action: Action::Copy,
+ active: view.code.is_some(),
+ });
+ buttons.push(Button {
+ x: cx + 4.0,
+ y,
+ w: 150.0,
+ label: "Stop Sharing",
+ action: Action::Stop,
+ active: true,
+ });
+ y += 30.0;
+ if view.code.is_some() {
+ // Who can join: grey when friends anywhere can, white (it asks
+ // for something) when only the LAN and VPNs can.
+ let tint = if view.reachable { grey() } else { WHITE };
+ add(&mut lines, &view.status, tint, &mut y);
+ y += 4.0;
+ }
+ let here = if view.guests.is_empty() {
+ "No friends here yet.".to_owned()
+ } else {
+ format!("Here now: {}", view.guests.join(", "))
+ };
+ add(&mut lines, &here, grey(), &mut y);
+ if let Some(notice) = &view.notice {
+ add(&mut lines, notice, WHITE, &mut y);
+ }
+ // Where friends paste the code, while it fits above the footer.
+ if y + 10.0 * wrap(HINT, width, atlas).len() as f32 <= h - 33.0 {
+ add(&mut lines, HINT, grey(), &mut y);
+ }
+ } else {
+ add(
+ &mut lines,
+ "Share this world behind an invite code: it opens to LAN, and friends on the internet join with the code. No server of ours is involved.",
+ WHITE,
+ &mut y,
+ );
+ y += 4.0;
+ add(&mut lines, HINT, grey(), &mut y);
+ buttons.push(Button {
+ x: cx - 100.0,
+ y: y + 8.0,
+ w: 200.0,
+ label: "Start Sharing",
+ action: Action::Share,
+ active: view.shown,
+ });
+ }
+ // HeaderAndFooterLayout's footer: Done, beside Troubleshooting when
+ // friends on the internet can't reach the host.
+ if view.sharing && view.help.is_some() {
+ buttons.push(Button {
+ x: cx - 154.0,
+ y: h - 27.0,
+ w: 150.0,
+ label: "Troubleshooting...",
+ action: Action::Help,
+ active: true,
+ });
+ buttons.push(Button {
+ x: cx + 4.0,
+ y: h - 27.0,
+ w: 150.0,
+ label: "gui.done",
+ action: Action::Done,
+ active: true,
+ });
+ } else {
+ buttons.push(Button {
+ x: cx - 100.0,
+ y: h - 27.0,
+ w: 200.0,
+ label: "gui.done",
+ action: Action::Done,
+ active: true,
+ });
+ }
+ (lines, buttons)
+}
+/// The code's groups packed into lines of at most `width`.
+fn code_lines(atlas: &HudAtlas, code: &str, width: f32) -> Vec {
+ let mut lines: Vec = Vec::new();
+ for group in code.split('-') {
+ match lines.last_mut() {
+ Some(l) if HudBatch::text_width(atlas, &format!("{l}-{group}")) <= width => {
+ l.push('-');
+ l.push_str(group);
+ }
+ _ => lines.push(group.to_owned()),
+ }
+ }
+ lines
+}
+fn label(key: &str) -> Text {
+ if key.starts_with("gui.") {
+ Text::translate(key, &[])
+ } else {
+ Text::literal(key)
+ }
+}
+pub fn draw(
+ batch: &mut HudBatch,
+ atlas: &HudAtlas,
+ cursor: (f32, f32),
+ view: &FriendsView,
+ in_world: bool,
+) {
+ let (w, h) = (batch.width, batch.height);
+ ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world);
+ let title = Text::literal(TITLE);
+ let tw = atlas.font.width_text(&title);
+ batch.text_styled(atlas, &title, ((w - tw) / 2.0).floor(), 15.0, WHITE, true);
+ let (lines, buttons) = layout(atlas, (w, h), view);
+ for (line, color, y) in lines {
+ let lw = HudBatch::text_width(atlas, &line);
+ batch.text(atlas, &line, ((w - lw) / 2.0).floor(), y, color, true);
+ }
+ for b in buttons {
+ let hover = b.active && ui::hovered(cursor, b.x, b.y, b.w, 20.0);
+ ui::button(
+ batch,
+ atlas,
+ b.x,
+ b.y,
+ b.w,
+ 20.0,
+ &label(b.label),
+ b.active,
+ hover,
+ );
+ }
+}
+/// The button under a click, if it is active.
+pub fn click(
+ atlas: &HudAtlas,
+ size: (f32, f32),
+ cursor: (f32, f32),
+ view: &FriendsView,
+) -> Option {
+ layout(atlas, size, view)
+ .1
+ .into_iter()
+ .find(|b| b.active && ui::hovered(cursor, b.x, b.y, b.w, 20.0))
+ .map(|b| b.action)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn atlas() -> HudAtlas {
+ HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
+ }
+
+ #[test]
+ fn share_then_copy_and_stop() {
+ let atlas = atlas();
+ let size = (427.0, 240.0);
+ let idle = FriendsView {
+ shown: true,
+ ..FriendsView::default()
+ };
+ let (_, buttons) = layout(&atlas, size, &idle);
+ let share = buttons.iter().find(|b| b.action == Action::Share).unwrap();
+ assert_eq!(
+ click(&atlas, size, (share.x + 1.0, share.y + 1.0), &idle),
+ Some(Action::Share)
+ );
+ let sharing = FriendsView {
+ shown: true,
+ sharing: true,
+ status: "Finding how friends can reach you…".into(),
+ ..FriendsView::default()
+ };
+ let (_, buttons) = layout(&atlas, size, &sharing);
+ let copy = buttons.iter().find(|b| b.action == Action::Copy).unwrap();
+ assert!(!copy.active, "nothing to copy before the code");
+ let with_code = FriendsView {
+ code: Some("0B33K-Q405Q-1Z5CV-X6NHY-R12N0-VK8T1-60N00-RA134-952PE-1HA08-910P0-K5M01-ST1NB-JDTB6-K4W1P-0".into()),
+ status: "Friends on your network or VPN can join. For friends on the internet: turn on UPnP on your router, or forward TCP port 25580 to 10.0.0.2, or use a relay, or a VPN such as Tailscale or ZeroTier (the code already holds your VPN address).".into(),
+ help: Some("https://example.invalid/help".into()),
+ ..sharing
+ };
+ let (lines, buttons) = layout(&atlas, size, &with_code);
+ assert!(
+ lines.iter().all(|(_, _, y)| y + 9.0 <= size.1 - 27.0),
+ "the text stays above the footer"
+ );
+ for action in [Action::Copy, Action::Stop, Action::Help, Action::Done] {
+ let b = buttons.iter().find(|b| b.action == action).unwrap();
+ assert_eq!(
+ click(&atlas, size, (b.x + 1.0, b.y + 1.0), &with_code),
+ Some(action)
+ );
+ }
+ }
+
+ #[test]
+ fn a_server_offers_no_sharing() {
+ let atlas = atlas();
+ let view = FriendsView::default();
+ let (_, buttons) = layout(&atlas, (427.0, 240.0), &view);
+ let share = buttons.iter().find(|b| b.action == Action::Share).unwrap();
+ assert!(!share.active);
+ }
+}
diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs
deleted file mode 100644
index 75c072eb6..000000000
--- a/crates/horizon-client/src/front.rs
+++ /dev/null
@@ -1,1572 +0,0 @@
-//! The front-end screens in Horizon's menu style (`ui_theme`), laid out like
-//! the launcher: a 200-wide sidebar with the sliding selection (Home,
-//! Singleplayer, Multiplayer, Options), content pages with a page header,
-//! settings rows and 1px dividers, and the launcher's opening (the wordmark,
-//! then the interface). They drive the same state as the classic layouts in
-//! `title` and `multiplayer`; only drawing and hit testing differ. The pause
-//! menu's Horizon layout is `pause`, below.
-use crate::{
- hud::{HudAtlas, HudBatch},
- multiplayer::{Outcome, Ping, Screen},
- title::{Action, Mode, Title, list_worlds},
- ui_theme::{
- self as t, BODY, CONTROL, CONTROL_LARGE, Face, Kind, SIDEBAR, SMALL, Ui, color, id,
- },
-};
-use std::time::Instant;
-
-const NAV: u64 = id("title.nav", 0);
-const QUIT: u64 = id("title.quit", 0);
-const PLAY: u64 = id("home.play", 0);
-const MULTIPLAYER: u64 = id("home.multiplayer", 0);
-const RESUME: u64 = id("home.resume", 0);
-const BACK: u64 = id("front.back", 0);
-const PLAY_WORLD: u64 = id("worlds.play", 0);
-const CREATE: u64 = id("worlds.create", 0);
-const WORLD: u64 = id("worlds.row", 0);
-const DELETE_WORLD: u64 = id("worlds.delete", 0);
-const CONFIRM_DELETE: u64 = id("delete.confirm", 0);
-const NAME: u64 = id("create.name", 0);
-const SEED: u64 = id("create.seed", 0);
-const MODE: u64 = id("create.mode", 0);
-const MAKE: u64 = id("create.make", 0);
-const SERVER: u64 = id("mp.row", 0);
-const JOIN: u64 = id("mp.join", 0);
-const DIRECT: u64 = id("mp.direct", 0);
-const FRIEND: u64 = id("mp.friend", 0);
-const ADD: u64 = id("mp.add", 0);
-const EDIT: u64 = id("mp.edit", 0);
-const DELETE: u64 = id("mp.delete", 0);
-const REFRESH: u64 = id("mp.refresh", 0);
-const FIELD_A: u64 = id("mp.field", 0);
-const FIELD_B: u64 = id("mp.field", 1);
-const DONE: u64 = id("mp.done", 0);
-const CANCEL_RETRY: u64 = id("mp.cancel_retry", 0);
-
-/// The launcher's opening (`launcher/src/main.rs`): the wordmark holds over
-/// the backdrop, then the interface comes in. A click or a key skips ahead.
-#[derive(Clone, Copy, Debug)]
-pub struct Opening {
- started: Instant,
- reveal: Option,
-}
-impl Opening {
- pub fn new() -> Self {
- Self {
- started: Instant::now(),
- reveal: None,
- }
- }
- /// The reveal's progress, 0 to 1; `ready` says the backdrop is showing.
- fn phase(&mut self, ready: bool) -> f32 {
- let held = self.started.elapsed();
- if self.reveal.is_none()
- && ((held >= horizon_theme::OPENING_HOLD && ready)
- || held >= horizon_theme::OPENING_MAX)
- {
- self.reveal = Some(Instant::now());
- }
- self.reveal.map_or(0.0, |at| {
- at.elapsed().as_secs_f32() / horizon_theme::OPENING_REVEAL.as_secs_f32()
- })
- }
- pub fn skip(&mut self) {
- self.reveal.get_or_insert_with(Instant::now);
- }
-}
-impl Default for Opening {
- fn default() -> Self {
- Self::new()
- }
-}
-
-/// Which sidebar item a mode belongs to.
-fn page(mode: &Mode) -> usize {
- match mode {
- Mode::Main => 0,
- Mode::Select { .. }
- | Mode::Create { .. }
- | Mode::Edit { .. }
- | Mode::Backup { .. }
- | Mode::Delete { .. }
- | Mode::Error { .. } => 1,
- Mode::Multiplayer(_) => 2,
- }
-}
-const PAGES: [&str; 4] = ["Home", "Singleplayer", "Multiplayer", "Options"];
-/// World editing and backups still use the classic screens, and so do their
-/// errors; the rest of the singleplayer flow has Horizon pages.
-fn classic(mode: &Mode) -> bool {
- match mode {
- Mode::Edit { .. } | Mode::Backup { .. } => true,
- Mode::Error { return_to, .. } => classic(return_to),
- _ => false,
- }
-}
-
-impl Title {
- /// Horizon's layout for every title mode. `backdrop` is how much of the
- /// live backdrop is visible (0 shows the plain cold background).
- pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) {
- if classic(&self.mode) {
- self.draw(ui.atlas, ui.batch, ui.cursor, false);
- return;
- }
- let reveal = self.opening_phase(backdrop >= 1.0);
- if backdrop < 1.0 {
- ui.cold_background(1.0 - backdrop);
- }
- let shade = t::ease_out_cubic(reveal);
- // The world stays in view on the home page; deeper pages veil it more.
- let veil = if matches!(self.mode, Mode::Main) {
- horizon_theme::HOME_VEIL
- } else {
- horizon_theme::VEIL
- };
- ui.muted = if matches!(self.mode, Mode::Main) {
- color::MUTED
- } else {
- color::FAINT
- };
- ui.atmosphere(veil, shade);
- let side = t::ease_out_cubic((reveal - 0.2) / 0.7);
- let main = t::ease_out_cubic((reveal - 0.35) / 0.65);
-
- // The sidebar slides in from the left.
- ui.opacity = side;
- ui.offset = (-16.0 * (1.0 - side), 0.0);
- if side > 0.0 {
- self.sidebar(ui);
- }
- // The content rises; each new page fades in and rises 8 over MOVE.
- let entered = self.entered();
- let p = t::ease_out_quint(entered.elapsed().as_secs_f32() / t::move_());
- ui.opacity = main * p;
- ui.offset = (0.0, 16.0 * (1.0 - main) + 8.0 * (1.0 - p));
- if main > 0.0 {
- let x = SIDEBAR + 48.0;
- let w = (ui.w - x - 48.0).min(760.0);
- match &self.mode {
- Mode::Main => self.home(ui, x, w),
- Mode::Select { worlds, selected } => worlds_page(ui, x, w, worlds, *selected),
- Mode::Create {
- name,
- seed,
- creative,
- focus,
- ..
- } => {
- let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
- create_page(ui, x, w, name, seed, *creative, *focus, caret);
- }
- Mode::Delete { world } => delete_page(ui, x, w, world),
- Mode::Error { message, .. } => error_page(ui, x, w, message),
- Mode::Multiplayer(screen) => {
- let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
- multiplayer_page(ui, x, w, screen, caret);
- }
- Mode::Edit { .. } | Mode::Backup { .. } => {
- unreachable!("World editing uses the classic layout")
- }
- }
- }
- ui.opacity = 1.0;
- ui.offset = (0.0, 0.0);
- if reveal < 1.0 {
- // The wordmark rises and fades as the interface comes in.
- let word = 1.0 - t::ease_out_cubic(reveal / 0.6);
- ui.opacity = word;
- let tw = ui.measure(Face::Display, t::WORDMARK, "horizon");
- let line = (t::WORDMARK * 1.2).round();
- ui.text_line(
- Face::Display,
- t::WORDMARK,
- line,
- ((ui.w - tw) / 2.0).round(),
- (ui.h - line) / 2.0 - 28.0 * (1.0 - word),
- color::TEXT,
- "horizon",
- );
- ui.opacity = 1.0;
- }
- }
- fn opening_phase(&self, ready: bool) -> f32 {
- let mut opening = self.opening.get();
- let phase = opening.as_mut().map_or(1.0, |o| o.phase(ready));
- self.opening.set(opening.filter(|_| phase < 1.0));
- phase.min(1.0)
- }
- /// A click or key during the opening jumps to the reveal; true if it did.
- pub fn skip_opening(&self) -> bool {
- let mut opening = self.opening.get();
- let skipped = opening.as_mut().is_some_and(|o| {
- let holding = o.reveal.is_none();
- o.skip();
- holding
- });
- self.opening.set(opening);
- skipped
- }
- fn sidebar(&self, ui: &mut Ui) {
- let (h, muted) = (ui.h, ui.muted);
- ui.sidebar_frame("Horizon");
- ui.sidebar_list(NAV, 12.0, 72.0, SIDEBAR - 24.0, &PAGES, page(&self.mode));
- let qy = h - 12.0 - 18.0 - 12.0 - CONTROL;
- let hover = ui.interact(QUIT, 12.0, qy, SIDEBAR - 24.0, CONTROL, true);
- ui.rounded(
- 12.0,
- qy,
- SIDEBAR - 24.0,
- CONTROL,
- t::PILL,
- color::with_alpha(color::RAISED, 0.8 * hover),
- );
- ui.text_line(
- Face::Regular,
- BODY,
- CONTROL,
- 24.0,
- qy,
- color::mix(muted, color::TEXT, hover),
- "Quit game",
- );
- ui.caps(
- 24.0,
- h - 12.0 - 18.0,
- muted,
- &format!("Horizon {}", horizon_core::VANILLA_VERSION),
- );
- }
- /// Home: the launcher's Play page over the backdrop.
- fn home(&self, ui: &mut Ui, x: f32, w: f32) {
- ui.wordmark(x, w, ui.h - 64.0, 220.0);
- let muted = ui.muted;
- let mut y = 36.0 + 28.0;
- ui.caps(
- x,
- y,
- muted,
- &format!(
- "Minecraft {} · Java Edition, rewritten in Rust",
- horizon_core::VANILLA_VERSION
- ),
- );
- y += 24.0;
- let line = (t::HERO * 1.1).round();
- ui.text_line(Face::Display, t::HERO, line, x, y, color::TEXT, "Horizon");
- y += line + 10.0;
- ui.text(
- Face::Regular,
- t::LARGE,
- x,
- y,
- muted,
- "The world you know, rebuilt from the ground up.",
- );
- y += 22.0 + 28.0;
- let pw = ui.button_width("Singleplayer", true).max(132.0);
- ui.button(
- PLAY,
- [x, y, pw, CONTROL_LARGE],
- "Singleplayer",
- Kind::Primary,
- true,
- );
- let mw = ui.button_width("Multiplayer", true);
- ui.button(
- MULTIPLAYER,
- [x + pw + 8.0, y, mw, CONTROL_LARGE],
- "Multiplayer",
- Kind::Secondary,
- true,
- );
- y += CONTROL_LARGE + 32.0;
- ui.row_index = 0;
- ui.divider(x, y, w);
- let worlds = self.recent_worlds();
- let last = worlds.first();
- let value = last.map_or("None yet".to_owned(), |l| {
- let secs = l
- .modified
- .duration_since(std::time::UNIX_EPOCH)
- .map_or(0, |d| d.as_secs());
- format!("{} · {}", l.name, crate::title::date_label(secs))
- });
- let rh = ui.row(x, y, "Last played", &value, w - t::ROW_LABEL - 120.0);
- if last.is_some() {
- let bw = ui.button_width("Resume", false);
- ui.button(
- RESUME,
- [x + w - bw, y + (rh - CONTROL) / 2.0, bw, CONTROL],
- "Resume",
- Kind::Secondary,
- true,
- );
- }
- y += rh;
- ui.divider(x, y, w);
- let count = match worlds.len() {
- 1 => "1 world".to_owned(),
- n => format!("{n} worlds"),
- };
- y += ui.row(x, y, "Saves", &count, w - t::ROW_LABEL - 16.0);
- ui.divider(x, y, w);
- ui.caps(
- x,
- ui.h - 12.0 - 18.0,
- muted,
- "Not affiliated with Mojang or Microsoft",
- );
- }
- /// A click in Horizon's layout (`x`, `y` in GUI pixels).
- pub fn click_horizon(
- &mut self,
- atlas: &HudAtlas,
- batch: &mut HudBatch,
- x: f32,
- y: f32,
- ) -> Action {
- self.remember_direct_address();
- if self.skip_opening() {
- return Action::None;
- }
- if classic(&self.mode) {
- return self.click(x, y, (batch.width, batch.height)).0;
- }
- let hit = {
- let mut ui = Ui::dry(atlas, batch, (x, y));
- self.draw_horizon(&mut ui, 1.0);
- ui.hit((x, y))
- };
- let Some(hit) = hit else {
- if let Mode::Create { focus, .. } = &mut self.mode {
- *focus = 2;
- }
- return Action::None;
- };
- let saves = self.saves.clone();
- let select = |saves: &std::path::Path| Mode::Select {
- worlds: list_worlds(saves),
- selected: None,
- };
- match hit {
- QUIT => return Action::Quit,
- h if h == NAV => {
- self.mode = Mode::Main;
- return Action::None;
- }
- h if h == NAV + 1 => {
- if !matches!(self.mode, Mode::Select { .. }) {
- self.mode = select(&saves);
- }
- return Action::None;
- }
- h if h == NAV + 2 => {
- if !matches!(self.mode, Mode::Multiplayer(_)) {
- self.mode = Mode::Multiplayer(Screen::list(&saves));
- }
- return Action::None;
- }
- h if h == NAV + 3 => return Action::Options,
- _ => {}
- }
- match &mut self.mode {
- Mode::Main => match hit {
- PLAY => self.mode = select(&saves),
- MULTIPLAYER => self.mode = Mode::Multiplayer(Screen::list(&saves)),
- RESUME => {
- if let Some(w) = list_worlds(&saves).into_iter().next() {
- return Action::Play { folder: w.folder };
- }
- }
- _ => {}
- },
- Mode::Select { worlds, selected } => match hit {
- PLAY_WORLD => {
- if let Some(w) = selected.and_then(|i| worlds.get(i)) {
- return Action::Play {
- folder: w.folder.clone(),
- };
- }
- }
- CREATE => self.mode = Title::new_world(),
- DELETE_WORLD => {
- if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() {
- self.mode = Mode::Delete { world };
- }
- }
- h if (WORLD..WORLD + 10_000).contains(&h) => {
- let i = (h - WORLD) as usize;
- if *selected == Some(i) {
- return Action::Play {
- folder: worlds[i].folder.clone(),
- };
- }
- *selected = Some(i);
- }
- _ => {}
- },
- Mode::Create {
- creative, focus, ..
- } => match hit {
- BACK => self.mode = select(&saves),
- NAME => *focus = 0,
- SEED => *focus = 1,
- h if h == MODE || h == MODE + 1 => *creative = h == MODE + 1,
- MAKE => return self.create_action(),
- _ => {}
- },
- Mode::Delete { .. } => match hit {
- // The selection stays in place: on the world that moved up
- // into the deleted one's row, or the new last one.
- CONFIRM_DELETE => {
- if let Some(row) = self.confirm_delete()
- && let Mode::Select { worlds, selected } = &mut self.mode
- {
- *selected = worlds.len().checked_sub(1).map(|last| row.min(last));
- }
- }
- BACK => self.escape(),
- _ => {}
- },
- Mode::Error { return_to, .. } => {
- if hit == BACK {
- self.mode = *return_to.clone();
- }
- }
- Mode::Edit { .. } | Mode::Backup { .. } => {}
- Mode::Multiplayer(screen) => {
- let id = match hit {
- JOIN => Some(40),
- DIRECT => Some(41),
- FRIEND => Some(47),
- ADD => Some(42),
- EDIT => Some(43),
- DELETE => Some(44),
- REFRESH => Some(45),
- BACK => Some(match screen {
- Screen::List { .. } => 46,
- Screen::Edit { .. } => 51,
- Screen::Direct { .. } => 53,
- Screen::Friend { .. } => 57,
- Screen::Disconnected { .. } => 54,
- Screen::ConfirmDelete { .. } => 59,
- }),
- CONFIRM_DELETE => Some(58),
- CANCEL_RETRY => Some(55),
- DONE => Some(match screen {
- Screen::Direct { .. } => 52,
- Screen::Friend { .. } => 56,
- _ => 50,
- }),
- FIELD_A | FIELD_B => {
- if let Screen::Edit { focus, .. } | Screen::Friend { focus, .. } = screen {
- *focus = u8::from(hit == FIELD_B);
- }
- None
- }
- h if (SERVER..SERVER + 10_000).contains(&h) => {
- let i = (h - SERVER) as usize;
- let again =
- matches!(screen, Screen::List { selected, .. } if *selected == Some(i));
- if again {
- if let Some(address) = screen.address_of(i) {
- return Action::Connect { address };
- }
- } else if let Screen::List { selected, .. } = screen {
- *selected = Some(i);
- }
- None
- }
- _ => None,
- };
- if let Some(id) = id {
- match self.multiplayer_click(Some(id), 0.0, 0.0, (0.0, 0.0)) {
- Outcome::Back => self.mode = Mode::Main,
- Outcome::Connect(address) => return Action::Connect { address },
- Outcome::None => {}
- }
- }
- }
- }
- Action::None
- }
-}
-
-/// The end of `text` that fits `width`, led by an ellipsis when cut.
-fn tail_fit(ui: &Ui, text: &str, width: f32) -> String {
- if ui.measure(Face::Regular, BODY, text) <= width {
- return text.to_owned();
- }
- let chars: Vec = text.chars().collect();
- let mut start = 0;
- while start < chars.len() {
- let tail: String = std::iter::once('…')
- .chain(chars[start..].iter().copied())
- .collect();
- if ui.measure(Face::Regular, BODY, &tail) <= width {
- return tail;
- }
- start += 1;
- }
- String::new()
-}
-
-/// The page header plus a row of actions under it; returns the y below.
-fn header(ui: &mut Ui, x: f32, title: &str, description: &str) -> f32 {
- let y = 36.0;
- y + ui.page_header(x, y, title, description) + 24.0
-}
-/// Actions laid out right to left from `right`; returns the left edge.
-fn actions_right(ui: &mut Ui, right: f32, y: f32, items: &[(u64, &str, Kind, bool)]) -> f32 {
- let mut rx = right;
- for &(bid, label, kind, on) in items {
- let large = kind == Kind::Primary;
- let (bw, bh) = if large {
- (ui.button_width(label, true).max(120.0), CONTROL_LARGE)
- } else {
- (ui.button_width(label, false), CONTROL)
- };
- rx -= bw;
- ui.button(
- bid,
- [rx, y + (CONTROL_LARGE - bh) / 2.0, bw, bh],
- label,
- kind,
- on,
- );
- rx -= 8.0;
- }
- rx
-}
-/// A selectable list row: its number, the name and a line under it, a mono
-/// detail on the right; a soft plate fades in under the pointer and stays
-/// under the selection, reaching past the row. Returns the row height.
-#[allow(clippy::too_many_arguments)]
-fn list_row(
- ui: &mut Ui,
- rid: u64,
- x: f32,
- y: f32,
- w: f32,
- selected: bool,
- title: &str,
- meta: &str,
- right: &str,
- dot: Option,
-) -> f32 {
- let h = 64.0;
- let hover = ui.interact(rid, x - 16.0, y + 2.0, w + 32.0, h - 4.0, true);
- let sel = ui.tween(rid ^ 0x5e1ec7, if selected { 1.0 } else { 0.0 }, t::quick());
- ui.rounded(
- x - 16.0,
- y + 3.0,
- w + 32.0,
- h - 6.0,
- t::RADIUS_PLATE,
- color::with_alpha(color::RAISED, (0.7 * hover).max(sel)),
- );
- ui.row_index += 1;
- let n = format!("{:02}", ui.row_index);
- ui.text(
- Face::Mono,
- t::MICRO,
- x,
- y + 15.0,
- color::mix(color::FAINT, color::TEXT, sel),
- &n,
- );
- let mut tx = x + t::INDEX;
- if let Some(dot) = dot {
- ui.rounded(tx, y + 19.0, 6.0, 6.0, 3.0, dot);
- tx += 16.0;
- }
- let title = ui.fit(Face::Medium, t::LARGE + 2.0, title, w - 240.0);
- ui.text(
- Face::Medium,
- t::LARGE + 2.0,
- tx,
- y + 10.0,
- color::TEXT,
- &title,
- );
- let meta = ui.fit(Face::Regular, SMALL, meta, w - 240.0);
- ui.text(Face::Regular, SMALL, tx, y + 35.0, color::FAINT, &meta);
- let right = right.to_uppercase();
- ui.text_right(Face::Mono, t::MICRO, x + w, y + 25.0, color::FAINT, &right);
- ui.divider(x, y + h, w);
- h
-}
-/// An empty list: a short line in heading type and a hint.
-fn empty(ui: &mut Ui, x: f32, y: f32, title: &str, hint: &str) {
- ui.text_line(
- Face::Display,
- t::HEADING,
- 28.0,
- x,
- y + 32.0,
- color::TEXT,
- title,
- );
- ui.text(Face::Regular, BODY, x, y + 64.0, color::FAINT, hint);
-}
-
-fn worlds_page(
- ui: &mut Ui,
- x: f32,
- w: f32,
- worlds: &[crate::title::WorldEntry],
- selected: Option,
-) {
- let count = match worlds.len() {
- 0 => "No worlds yet. They live in the saves folder.".to_owned(),
- 1 => "1 world in the saves folder.".to_owned(),
- n => format!("{n} worlds in the saves folder."),
- };
- let mut y = header(ui, x, "Singleplayer", &count);
- let mut items = vec![
- (PLAY_WORLD, "Play", Kind::Primary, selected.is_some()),
- (CREATE, "Create world", Kind::Secondary, true),
- ];
- if selected.is_some() {
- items.push((DELETE_WORLD, "Delete", Kind::Danger, true));
- }
- actions_right(ui, x + w, y - 24.0 - 58.0, &items);
- ui.divider(x, y, w);
- if worlds.is_empty() {
- empty(ui, x, y, "A blank map.", "Create a world to begin.");
- return;
- }
- let bottom = ui.h - 36.0;
- for (i, world) in worlds.iter().enumerate() {
- if y + 60.0 > bottom {
- break;
- }
- let secs = world
- .modified
- .duration_since(std::time::UNIX_EPOCH)
- .map_or(0, |d| d.as_secs());
- let meta = format!("{} · {}", crate::title::date_label(secs), world.folder);
- let mode = if world.creative {
- "Creative"
- } else {
- "Survival"
- };
- y += list_row(
- ui,
- WORLD + i as u64,
- x,
- y,
- w,
- selected == Some(i),
- &world.name,
- &meta,
- mode,
- None,
- );
- }
-}
-
-/// The launcher's notice: a plate led by a danger dot, the first line in
-/// medium type, wrapped lines under it. Returns its height.
-fn notice(ui: &mut Ui, x: f32, y: f32, w: f32, title: Option<&str>, text: &str) -> f32 {
- let lines = wrap(ui, text, w - 48.0);
- let title_h = if title.is_some() { 26.0 } else { 0.0 };
- let h = 32.0 + title_h + lines.len() as f32 * 19.0;
- ui.rounded(x, y, w, h, t::RADIUS_PLATE, color::RAISED);
- ui.rounded(x + 16.0, y + 22.0, 6.0, 6.0, 3.0, color::DANGER);
- let mut ty = y + 16.0;
- if let Some(title) = title {
- let title = ui.fit(Face::Medium, t::LARGE + 2.0, title, w - 48.0);
- ui.text_line(
- Face::Medium,
- t::LARGE + 2.0,
- 19.0,
- x + 32.0,
- ty,
- color::TEXT,
- &title,
- );
- ty += title_h;
- }
- for (i, line) in lines.iter().enumerate() {
- let tint = if title.is_some() {
- color::MUTED
- } else {
- color::TEXT
- };
- ui.text_line(
- Face::Regular,
- BODY,
- 19.0,
- x + 32.0,
- ty + i as f32 * 19.0,
- tint,
- line,
- );
- }
- h
-}
-
-/// `ConfirmScreen` for a world: what goes, that it can't come back, then
-/// Delete (danger) and Cancel under it.
-fn delete_page(ui: &mut Ui, x: f32, w: f32, world: &crate::title::WorldEntry) {
- let mut y = header(
- ui,
- x,
- "Delete this world?",
- "It will be lost forever. This can't be undone.",
- );
- ui.divider(x, y, w);
- y += 16.0;
- let secs = world
- .modified
- .duration_since(std::time::UNIX_EPOCH)
- .map_or(0, |d| d.as_secs());
- let text = format!(
- "Last played {}. The folder saves/{} and everything built in it will be removed.",
- crate::title::date_label(secs),
- world.folder
- );
- y += notice(ui, x, y, w, Some(&world.name), &text) + 16.0;
- let dw = ui.button_width("Delete world", false);
- ui.button(
- CONFIRM_DELETE,
- [x, y, dw, CONTROL],
- "Delete world",
- Kind::Danger,
- true,
- );
- let cw = ui.button_width("Cancel", false);
- ui.button(
- BACK,
- [x + dw + 8.0, y, cw, CONTROL],
- "Cancel",
- Kind::Ghost,
- true,
- );
-}
-
-fn error_page(ui: &mut Ui, x: f32, w: f32, message: &str) {
- let mut y = header(
- ui,
- x,
- "Something went wrong",
- "Horizon couldn't finish that.",
- );
- ui.divider(x, y, w);
- y += 16.0;
- y += notice(ui, x, y, w, None, message) + 16.0;
- let bw = ui.button_width("Back", false);
- ui.button(BACK, [x, y, bw, CONTROL], "Back", Kind::Secondary, true);
-}
-
-#[allow(clippy::too_many_arguments)]
-fn create_page(
- ui: &mut Ui,
- x: f32,
- w: f32,
- name: &str,
- seed: &str,
- creative: bool,
- focus: u8,
- caret: bool,
-) {
- let mut y = header(
- ui,
- x,
- "Create world",
- "Generated by Horizon from the seed, as vanilla would.",
- );
- actions_right(
- ui,
- x + w,
- y - 24.0 - 58.0,
- &[
- (MAKE, "Create", Kind::Primary, true),
- (BACK, "Cancel", Kind::Ghost, true),
- ],
- );
- ui.divider(x, y, w);
- let fx = x + t::ROW_LABEL + 16.0;
- let fw = (w - t::ROW_LABEL - 16.0).min(360.0);
- for (i, label) in ["World name", "Seed", "Game mode"].iter().enumerate() {
- let rh = 12.0 + CONTROL + 12.0;
- ui.text_line(Face::Regular, BODY, rh, x, y, color::MUTED, label);
- let r = [fx, y + 12.0, fw, CONTROL];
- match i {
- 0 => ui.field(NAME, r, name, "New World", focus == 0, caret),
- 1 => ui.field(SEED, r, seed, "Random", focus == 1, caret),
- _ => {
- ui.segmented(
- MODE,
- fx,
- y + 12.0,
- &["Survival", "Creative"],
- usize::from(creative),
- );
- }
- }
- y += rh;
- ui.divider(x, y, w);
- }
-}
-
-fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
- match screen {
- Screen::List {
- servers,
- selected,
- pings,
- lan,
- ..
- } => {
- let games = lan.games();
- let sub = match servers.len() {
- 0 => "No saved servers. Worlds opened to LAN show up here too.".to_owned(),
- 1 => "1 saved server, and worlds opened to LAN.".to_owned(),
- n => format!("{n} saved servers, and worlds opened to LAN."),
- };
- let mut y = header(ui, x, "Multiplayer", &sub);
- let has = selected.is_some();
- let saved = selected.is_some_and(|i| i < servers.len());
- let mut items = vec![
- (JOIN, "Join", Kind::Primary, has),
- (FRIEND, "Join a friend", Kind::Secondary, true),
- (ADD, "Add server", Kind::Secondary, true),
- (DIRECT, "Direct connect", Kind::Secondary, true),
- (REFRESH, "Refresh", Kind::Ghost, true),
- ];
- if saved {
- items.push((EDIT, "Edit", Kind::Ghost, true));
- items.push((DELETE, "Delete", Kind::Danger, true));
- }
- actions_right(ui, x + w, y - 24.0 - 58.0, &items);
- ui.divider(x, y, w);
- let pings = pings.lock().map(|p| p.clone()).unwrap_or_default();
- let mut rows: Vec<(String, String, String, u32)> = servers
- .iter()
- .map(|s| {
- let (line, right, dot) = match pings.get(&s.ip) {
- Some(Ping::Ok {
- motd, players, ms, ..
- }) => (
- motd.resolve_legacy()
- .plain()
- .lines()
- .next()
- .unwrap_or("")
- .trim()
- .to_owned(),
- format!("{} · {ms} ms", Ping::player_count(*players).plain()),
- color::ACCENT,
- ),
- Some(Ping::Failed(_)) => (
- "Can't reach the server".to_owned(),
- String::new(),
- color::DANGER,
- ),
- _ => ("Pinging…".to_owned(), String::new(), color::FAINT),
- };
- (s.name.clone(), format!("{line} · {}", s.ip), right, dot)
- })
- .collect();
- rows.extend(games.iter().map(|g| {
- (
- "LAN world".to_owned(),
- format!("{} · {}", g.motd, g.address),
- "On your network".to_owned(),
- color::ACCENT,
- )
- }));
- if rows.is_empty() {
- empty(
- ui,
- x,
- y,
- "Nobody here yet.",
- "Add a server, connect directly, or open a world to LAN.",
- );
- return;
- }
- let bottom = ui.h - 36.0;
- for (i, (name, meta, right, dot)) in rows.iter().enumerate() {
- if y + 60.0 > bottom {
- break;
- }
- y += list_row(
- ui,
- SERVER + i as u64,
- x,
- y,
- w,
- *selected == Some(i),
- name,
- meta,
- right,
- Some(*dot),
- );
- }
- }
- Screen::Edit {
- index,
- name,
- address,
- focus,
- } => {
- let title = if index.is_some() {
- "Edit server"
- } else {
- "Add server"
- };
- let mut y = header(
- ui,
- x,
- title,
- "Saved to servers.dat, like vanilla's server list.",
- );
- let ok = horizon_protocol::servers::parse_address(address).is_some();
- actions_right(
- ui,
- x + w,
- y - 24.0 - 58.0,
- &[
- (DONE, "Save", Kind::Primary, ok),
- (BACK, "Cancel", Kind::Ghost, true),
- ],
- );
- ui.divider(x, y, w);
- let fx = x + t::ROW_LABEL + 16.0;
- let fw = (w - t::ROW_LABEL - 16.0).min(360.0);
- for (i, (label, value, hint)) in [
- ("Name", name, "Minecraft Server"),
- ("Address", address, "play.example.net"),
- ]
- .iter()
- .enumerate()
- {
- let rh = 12.0 + CONTROL + 12.0;
- ui.text_line(Face::Regular, BODY, rh, x, y, color::MUTED, label);
- let fid = if i == 0 { FIELD_A } else { FIELD_B };
- ui.field(
- fid,
- [fx, y + 12.0, fw, CONTROL],
- value,
- hint,
- usize::from(*focus) == i,
- caret,
- );
- y += rh;
- ui.divider(x, y, w);
- }
- }
- Screen::Direct { address } => {
- let y = header(
- ui,
- x,
- "Direct connect",
- "Join a server once without saving it.",
- );
- let ok = horizon_protocol::servers::parse_address(address).is_some();
- actions_right(
- ui,
- x + w,
- y - 24.0 - 58.0,
- &[
- (DONE, "Join", Kind::Primary, ok),
- (BACK, "Cancel", Kind::Ghost, true),
- ],
- );
- ui.divider(x, y, w);
- let rh = 12.0 + CONTROL + 12.0;
- ui.text_line(Face::Regular, BODY, rh, x, y, color::MUTED, "Address");
- let fx = x + t::ROW_LABEL + 16.0;
- ui.field(
- FIELD_A,
- [fx, y + 12.0, (w - t::ROW_LABEL - 16.0).min(360.0), CONTROL],
- address,
- "host:port",
- true,
- caret,
- );
- ui.divider(x, y + rh, w);
- }
- Screen::Friend { code, relay, focus } => {
- let y = header(
- ui,
- x,
- "Join a friend",
- "Paste the invite code your friend sees in their pause menu.",
- );
- let parsed = horizon_friends::invite::parse_detailed(code);
- let ok = parsed.is_ok();
- actions_right(
- ui,
- x + w,
- y - 24.0 - 58.0,
- &[
- (DONE, "Join", Kind::Primary, ok),
- (BACK, "Cancel", Kind::Ghost, true),
- ],
- );
- ui.divider(x, y, w);
- let rh = 12.0 + CONTROL + 12.0;
- let fx = x + t::ROW_LABEL + 16.0;
- let fw = w - t::ROW_LABEL - 16.0;
- let rows = [
- (FIELD_A, "Invite code", code, "Paste the code here", fw),
- (
- FIELD_B,
- "Relay (optional)",
- relay,
- "host:port, for short codes",
- fw.min(360.0),
- ),
- ];
- let mut ry = y;
- for (i, (fid, label, value, hint, width)) in rows.into_iter().enumerate() {
- ui.text_line(Face::Regular, BODY, rh, x, ry, color::MUTED, label);
- // A long code shows its end, where the typing is.
- let shown = tail_fit(ui, value, width - 28.0);
- ui.field(
- fid,
- [fx, ry + 12.0, width, CONTROL],
- &shown,
- hint,
- usize::from(*focus) == i,
- caret,
- );
- ry += rh;
- ui.divider(x, ry, w);
- }
- let note = match parsed {
- _ if code.trim().is_empty() => None,
- Err(e) => Some(e.to_string()),
- Ok(horizon_friends::invite::Parsed::Short(_)) if relay.trim().is_empty() => Some(
- "This is a relay's short code: fill in your friend's relay above, or ask for the full code."
- .to_owned(),
- ),
- Ok(_) => None,
- };
- if let Some(note) = note {
- ui.text(Face::Regular, SMALL, x, ry + 12.0, color::MUTED, ¬e);
- }
- }
- Screen::ConfirmDelete { name, .. } => {
- let mut y = header(
- ui,
- x,
- "Remove this server?",
- "It leaves your list. You can add it again later.",
- );
- ui.divider(x, y, w);
- y += 16.0;
- y += notice(
- ui,
- x,
- y,
- w,
- Some(name),
- "Its address and icon will be forgotten.",
- ) + 16.0;
- let dw = ui.button_width("Delete server", false);
- ui.button(
- CONFIRM_DELETE,
- [x, y, dw, CONTROL],
- "Delete server",
- Kind::Danger,
- true,
- );
- let cw = ui.button_width("Cancel", false);
- ui.button(
- BACK,
- [x + dw + 8.0, y, cw, CONTROL],
- "Cancel",
- Kind::Ghost,
- true,
- );
- }
- Screen::Disconnected { reason, retry } => {
- let mut y = header(
- ui,
- x,
- "Connection lost",
- "The server closed the connection.",
- );
- ui.divider(x, y, w);
- y += 16.0;
- y += notice(ui, x, y, w, None, reason) + 16.0;
- if let Some(r) = retry {
- // Auto-reconnect's countdown, with a way out.
- let text = r.text(std::time::Instant::now());
- ui.text_line(Face::Regular, BODY, 19.0, x, y, color::MUTED, &text);
- y += 19.0 + 12.0;
- }
- let bw = ui.button_width("Back to servers", false);
- ui.button(
- BACK,
- [x, y, bw, CONTROL],
- "Back to servers",
- Kind::Secondary,
- true,
- );
- if retry.is_some() {
- let cw = ui.button_width("Cancel reconnecting", false);
- ui.button(
- CANCEL_RETRY,
- [x + bw + 8.0, y, cw, CONTROL],
- "Cancel reconnecting",
- Kind::Ghost,
- true,
- );
- }
- }
- }
-}
-/// Greedy word wrap in dp.
-pub fn wrap(ui: &Ui, text: &str, width: f32) -> Vec {
- let mut lines = Vec::new();
- for para in text.lines() {
- let mut line = String::new();
- for word in para.split_whitespace() {
- let next = if line.is_empty() {
- word.to_owned()
- } else {
- format!("{line} {word}")
- };
- if !line.is_empty() && ui.measure(Face::Regular, BODY, &next) > width {
- lines.push(std::mem::replace(&mut line, word.to_owned()));
- } else {
- line = next;
- }
- }
- lines.push(line);
- }
- lines
-}
-
-/// The pause menu in Horizon's style: the launcher's sidebar over the
-/// blurred world, with the game's actions as a page. Ids match
-/// `game/screens.rs`'s PauseScreen actions: 0 back to game, 1 options,
-/// 2 save and quit, 3 statistics, 4 advancements, 9 world options.
-/// Play with friends as the pause menu shows it (game/friends.rs fills it).
-#[derive(Clone, Debug, Default)]
-pub struct FriendsView {
- /// A singleplayer world (not a server): the button is offered.
- pub shown: bool,
- pub sharing: bool,
- pub code: Option,
- /// Who can join and what to do when friends on the internet can't (or,
- /// before the code, what the game is doing).
- pub status: String,
- /// Friends on the internet can reach the host.
- pub reachable: bool,
- /// Where the troubleshooting is, when they can't.
- pub help: Option,
- /// The players in the world besides the host.
- pub guests: Vec,
- pub notice: Option,
- /// The code was just copied.
- pub copied: bool,
-}
-
-pub mod pause {
- use super::*;
- fn act(a: u8) -> u64 {
- id("pause", u64::from(a))
- }
- pub fn draw(
- ui: &mut Ui,
- world: &str,
- quit_label: &str,
- opened: Instant,
- friends: &FriendsView,
- remote: bool,
- ) {
- let (w, h) = (ui.w, ui.h);
- let p = t::ease_out_quint(opened.elapsed().as_secs_f32() / t::move_());
- ui.opacity = p;
- ui.atmosphere(horizon_theme::VEIL, 1.0);
- ui.offset = (-16.0 * (1.0 - p), 0.0);
- ui.sidebar_frame("Horizon");
- ui.sidebar_list(
- id("pause.nav", 0),
- 12.0,
- 72.0,
- SIDEBAR - 24.0,
- &["Game", "Advancements", "Statistics", "Options"],
- 0,
- );
- ui.caps(
- 24.0,
- h - 12.0 - 18.0,
- color::FAINT,
- &format!("Horizon {}", horizon_core::VANILLA_VERSION),
- );
- ui.offset = (0.0, 8.0 * (1.0 - p));
- let x = SIDEBAR + 48.0;
- let cw = (w - x - 48.0).min(760.0);
- let mut y = 36.0 + 28.0;
- ui.caps(x, y, color::FAINT, "Game paused");
- y += 24.0;
- let line = (t::HERO * 1.1).round();
- let title = ui.fit(Face::Display, t::HERO, world, cw);
- ui.text_line(Face::Display, t::HERO, line, x, y, color::TEXT, &title);
- y += line + 32.0;
- let bw = ui.button_width("Back to game", true).max(120.0);
- ui.button(
- act(0),
- [x, y, bw, CONTROL_LARGE],
- "Back to game",
- Kind::Primary,
- true,
- );
- let lw = ui.button_width("World Options", true);
- ui.button(
- act(9),
- [x + bw + 8.0, y, lw, CONTROL_LARGE],
- "World Options",
- Kind::Secondary,
- true,
- );
- if friends.shown {
- let iw = ui.button_width("Invite friends", true);
- ui.button(
- act(10),
- [x + bw + lw + 16.0, y, iw, CONTROL_LARGE],
- "Invite friends",
- Kind::Secondary,
- !friends.sharing,
- );
- }
- y += CONTROL_LARGE + 32.0;
- ui.row_index = 0;
- if friends.sharing {
- y = invite(ui, x, y, cw, friends);
- }
- ui.divider(x, y, cw);
- let rh = ui.row(
- x,
- y,
- "Leave",
- if remote {
- "Disconnects from the server, then returns to the title."
- } else {
- "Saves the world, then returns to the title."
- },
- cw - t::ROW_LABEL - 220.0,
- );
- let qw = ui.button_width(quit_label, false);
- ui.button(
- act(2),
- [x + cw - qw, y + (rh - CONTROL) / 2.0, qw, CONTROL],
- quit_label,
- Kind::Danger,
- true,
- );
- y += rh;
- ui.divider(x, y, cw);
- ui.opacity = 1.0;
- ui.offset = (0.0, 0.0);
- }
- /// The invite section while sharing: the code with Copy and Stop
- /// sharing, who is here, and what changed. Returns the y below it.
- /// The code's groups packed into lines of at most `width`.
- fn code_lines(ui: &Ui, code: &str, width: f32) -> Vec {
- let mut lines: Vec = Vec::new();
- for group in code.split('-') {
- match lines.last_mut() {
- Some(l) if ui.measure(Face::Mono, BODY, &format!("{l}-{group}")) <= width => {
- l.push('-');
- l.push_str(group);
- }
- _ => lines.push(group.to_owned()),
- }
- }
- lines
- }
- fn invite(ui: &mut Ui, x: f32, mut y: f32, cw: f32, f: &FriendsView) -> f32 {
- ui.divider(x, y, cw);
- let top = y + 12.0;
- ui.text(
- Face::Regular,
- BODY,
- x,
- top + 6.0,
- color::MUTED,
- "Invite code",
- );
- let vx = x + t::ROW_LABEL + 16.0;
- let stop = "Stop sharing";
- let sw = ui.button_width(stop, false);
- ui.button(
- act(12),
- [x + cw - sw, top, sw, CONTROL],
- stop,
- Kind::Danger,
- true,
- );
- let copy = if f.copied { "Copied" } else { "Copy" };
- let copy_w = ui.button_width("Copied", false);
- let buttons = sw + 8.0 + copy_w;
- ui.button(
- act(11),
- [x + cw - buttons, top, copy_w, CONTROL],
- copy,
- Kind::Secondary,
- f.code.is_some(),
- );
- let line = (BODY * 1.45).round();
- let value_w = (cw - t::ROW_LABEL - 16.0 - buttons - 16.0).max(120.0);
- y = top + 6.0;
- match &f.code {
- Some(code) => {
- for l in code_lines(ui, code, value_w) {
- ui.text(Face::Mono, BODY, vx, y, color::TEXT, &l);
- y += line;
- }
- }
- None => {
- for l in wrap(ui, &f.status, value_w) {
- ui.text(Face::Regular, BODY, vx, y, color::MUTED, &l);
- y += line;
- }
- }
- }
- y = y.max(top + CONTROL) + 10.0;
- let small = (SMALL * 1.45).round();
- if f.code.is_some() {
- // Who can join: plain when friends anywhere can, in the text
- // colour (it asks for something) when only the LAN and VPNs can.
- let tint = if f.reachable {
- color::MUTED
- } else {
- color::TEXT
- };
- for l in wrap(ui, &f.status, cw) {
- ui.text(Face::Regular, SMALL, x, y, tint, &l);
- y += small;
- }
- if let Some(help) = &f.help {
- let l = ui.fit(Face::Regular, SMALL, &format!("Help: {help}"), cw);
- ui.text(Face::Regular, SMALL, x, y, color::FAINT, &l);
- y += small;
- }
- }
- let here = if f.guests.is_empty() {
- "No friends here yet.".to_owned()
- } else {
- format!("Here now: {}", f.guests.join(", "))
- };
- let hint =
- "Friends paste the code in Multiplayer, Join a friend, or on the launcher's Play page.";
- let lines = [
- Some((here, color::MUTED)),
- f.notice.clone().map(|n| (n, color::MUTED)),
- Some((hint.to_owned(), color::FAINT)),
- ];
- for (line, tint) in lines.into_iter().flatten() {
- let line = ui.fit(Face::Regular, SMALL, &line, cw);
- ui.text(Face::Regular, SMALL, x, y, tint, &line);
- y += small;
- }
- y + 12.0
- }
- /// The PauseScreen action under a click, if any.
- pub fn click(
- atlas: &HudAtlas,
- batch: &mut HudBatch,
- x: f32,
- y: f32,
- world: &str,
- quit_label: &str,
- friends: &FriendsView,
- remote: bool,
- ) -> Option {
- let mut ui = Ui::dry(atlas, batch, (x, y));
- draw(
- &mut ui,
- world,
- quit_label,
- Instant::now() - std::time::Duration::from_secs(5),
- friends,
- remote,
- );
- let hit = ui.hit((x, y))?;
- let nav = id("pause.nav", 0);
- match hit {
- h if h == nav => Some(0),
- h if h == nav + 1 => Some(4),
- h if h == nav + 2 => Some(3),
- h if h == nav + 3 => Some(1),
- h => [0u8, 1, 2, 3, 4, 9, 10, 11, 12]
- .into_iter()
- .find(|&a| act(a) == h),
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use horizon_world::nbt::Tag;
-
- #[test]
- fn pause_world_options_and_disconnect_are_clickable_on_servers() {
- let atlas =
- HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
- let friends = FriendsView::default();
- for remote in [false, true] {
- let quit = if remote {
- "Disconnect"
- } else {
- "Save and quit"
- };
- for action in [9u8, 2] {
- let mut batch = HudBatch::new([1280, 720]);
- let (rect, density) = {
- let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0));
- pause::draw(
- &mut ui,
- "World",
- quit,
- Instant::now() - std::time::Duration::from_secs(5),
- &friends,
- remote,
- );
- let hit = ui
- .hits
- .iter()
- .find(|h| h.id == id("pause", u64::from(action)))
- .expect("pause action available");
- (hit.rect, ui.density)
- };
- let k = density / batch.scale;
- let x = (rect[0] + rect[2]) / 2.0 * k;
- let y = (rect[1] + rect[3]) / 2.0 * k;
- assert_eq!(
- pause::click(&atlas, &mut batch, x, y, "World", quit, &friends, remote),
- Some(action)
- );
- }
- }
- }
-
- fn world(saves: &std::path::Path, folder: &str, last_played: i64) {
- crate::save::write_dat(
- &saves.join(folder).join("level.dat"),
- Tag::compound([(
- "Data",
- Tag::compound([
- ("LevelName", Tag::String(folder.into())),
- ("GameType", Tag::Int(0)),
- ("LastPlayed", Tag::Long(last_played)),
- ("WorldGenSettings", Tag::compound([("seed", Tag::Long(1))])),
- ]),
- )]),
- )
- .unwrap();
- }
- /// Clicks the middle of button `bid` as the game would; panics if the
- /// page does not show it.
- fn press(title: &mut Title, atlas: &HudAtlas, bid: u64) -> Action {
- let mut batch = HudBatch::new([1280, 720]);
- let (rect, density) = {
- let mut ui = Ui::dry(atlas, &mut batch, (0.0, 0.0));
- title.draw_horizon(&mut ui, 1.0);
- let hit = ui.hits.iter().rev().find(|h| h.id == bid);
- (hit.expect("button on the page").rect, ui.density)
- };
- let k = density / batch.scale;
- let (x, y) = ((rect[0] + rect[2]) / 2.0 * k, (rect[1] + rect[3]) / 2.0 * k);
- title.click_horizon(atlas, &mut batch, x, y)
- }
- fn shows(title: &Title, atlas: &HudAtlas, bid: u64) -> bool {
- let mut batch = HudBatch::new([1280, 720]);
- let mut ui = Ui::dry(atlas, &mut batch, (0.0, 0.0));
- title.draw_horizon(&mut ui, 1.0);
- ui.hits.iter().any(|h| h.id == bid)
- }
- fn selected(title: &Title) -> Option {
- match &title.mode {
- Mode::Select { worlds, selected } => selected.map(|i| worlds[i].folder.clone()),
- _ => panic!("not on the world list"),
- }
- }
-
- #[test]
- fn horizon_direct_connection_remembers_the_address_after_leaving() {
- let atlas =
- HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
- let saves =
- std::env::temp_dir().join(format!("horizon-front-direct-{}", std::process::id()));
- let mut title = Title::new(saves.clone(), &saves);
- title.last_server = "localhost:25566".into();
- title.mode = Mode::Multiplayer(Screen::list(&saves));
- press(&mut title, &atlas, DIRECT);
- assert_eq!(title.focused_field().unwrap().1, "localhost:25566");
- *title.focused_field().unwrap().1 = "example.org:25567".into();
- press(&mut title, &atlas, BACK);
- press(&mut title, &atlas, DIRECT);
- assert_eq!(title.focused_field().unwrap().1, "example.org:25567");
- *title.focused_field().unwrap().1 = "localhost:25568".into();
- press(&mut title, &atlas, NAV);
- press(&mut title, &atlas, NAV + 2);
- press(&mut title, &atlas, DIRECT);
- assert_eq!(title.focused_field().unwrap().1, "localhost:25568");
- }
-
- #[test]
- fn horizon_world_delete_confirms_and_keeps_the_selection_in_place() {
- let atlas =
- HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
- let root =
- std::env::temp_dir().join(format!("horizon-front-delete-{}", std::process::id()));
- let saves = root.join("saves");
- for (i, folder) in ["C", "B", "A"].iter().enumerate() {
- world(&saves, folder, 1000 * (i as i64 + 1));
- }
- let mut title = Title::new(saves.clone(), &saves);
- title.mode = Mode::Select {
- worlds: list_worlds(&saves),
- selected: None,
- };
- assert!(!shows(&title, &atlas, DELETE_WORLD));
- press(&mut title, &atlas, WORLD + 1);
- assert_eq!(selected(&title).as_deref(), Some("B"));
-
- // Cancel leaves the world and its selection.
- press(&mut title, &atlas, DELETE_WORLD);
- assert!(matches!(&title.mode, Mode::Delete { world } if world.folder == "B"));
- press(&mut title, &atlas, BACK);
- assert_eq!(selected(&title).as_deref(), Some("B"));
- assert!(saves.join("B/level.dat").is_file());
-
- // Deleting selects the world that moved up into the row.
- press(&mut title, &atlas, DELETE_WORLD);
- press(&mut title, &atlas, CONFIRM_DELETE);
- assert!(!saves.join("B").exists());
- assert_eq!(selected(&title).as_deref(), Some("C"));
-
- // A world open elsewhere is refused on a Horizon page; Back returns
- // to the question.
- let open = crate::save::SessionLock::acquire(&saves.join("C")).unwrap();
- press(&mut title, &atlas, DELETE_WORLD);
- press(&mut title, &atlas, CONFIRM_DELETE);
- assert!(matches!(title.mode, Mode::Error { .. }));
- assert!(!classic(&title.mode));
- press(&mut title, &atlas, BACK);
- assert!(matches!(title.mode, Mode::Delete { .. }));
- drop(open);
-
- // The last row: the selection moves to the new last world.
- press(&mut title, &atlas, CONFIRM_DELETE);
- assert_eq!(selected(&title).as_deref(), Some("A"));
- press(&mut title, &atlas, DELETE_WORLD);
- press(&mut title, &atlas, CONFIRM_DELETE);
- assert!(
- matches!(&title.mode, Mode::Select { worlds, selected: None } if worlds.is_empty())
- );
- let _ = std::fs::remove_dir_all(root);
- }
-}
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index f706e9348..7ec21608a 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -5,7 +5,6 @@ mod advancements_screen;
mod agent;
mod allays;
mod armor_stands;
-mod backdrop;
mod banners;
mod beacon;
mod beehives;
@@ -76,6 +75,7 @@ mod lan_pvp;
mod lan_screen;
mod lan_stations;
mod lan_trading;
+mod lan_vehicles;
mod lan_waypoints;
mod leads;
mod level_particles;
@@ -121,6 +121,7 @@ mod remote;
mod remote_objects;
mod remote_projectiles;
mod remote_stations;
+mod remote_vehicles;
mod render_control;
mod render_tick;
mod respawn_anchor;
@@ -214,6 +215,7 @@ use horizon_world::{
registry::BlockStateId,
};
use std::{
+ cell::RefCell,
collections::{HashMap, HashSet},
path::PathBuf,
sync::{
@@ -272,9 +274,10 @@ struct Options {
benchmark: Option,
/// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt.
dev_mods: Vec,
- /// Single player runs on an integrated server thread (game/integrated.rs),
- /// as vanilla's does: the default. `--no-server-thread` or
- /// `HORIZON_SERVER_THREAD=0` runs the world in the frame instead.
+ /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on an
+ /// integrated server thread (game/integrated.rs), as vanilla's does. Off by
+ /// default again until a server's players can board, ride and hit
+ /// vehicles (#1222); `--no-server-thread` keeps it off.
server_thread: bool,
/// Set on the integrated server's own options: it draws nothing, so it skips meshing.
integrated: bool,
@@ -331,7 +334,7 @@ impl Options {
dev_mods: Vec::new(),
// The command harness (HORIZON_COMMAND_SCRIPT) drives the world
// itself, without the event loop: it stays in the frame.
- server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0")
+ server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1")
&& std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(),
integrated: false,
};
@@ -341,7 +344,7 @@ impl Options {
match arg.as_str() {
"--help" | "-h" => {
println!(
- "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
+ "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --server-thread Run single player's world on its server thread (no vehicles yet)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
horizon_core::VANILLA_VERSION
);
return Ok(None);
@@ -453,6 +456,9 @@ enum Screen {
Advancements,
/// WorldOptionsScreen (game/lan_screen.rs).
WorldOptions,
+ /// Play with Friends, from the pause menu's Friends button
+ /// (`friends_screen`, game/friends.rs).
+ Friends,
/// CommandBlockEditScreen (game/command_blocks.rs).
CommandBlock,
}
@@ -1110,6 +1116,7 @@ struct Game<'a> {
/// `FogRenderer`'s evolving state.
fog: horizon_client::fog::FogState,
screen_fx: horizon_client::screen_effects::ScreenEffects,
+ weather_parameters: horizon_client::weather::ParameterCache,
panorama_rotation: horizon_client::gfx::panorama::Rotation,
world: World,
streaming: Streaming,
@@ -1312,14 +1319,12 @@ struct Game<'a> {
settings: Settings,
/// Where the options screen returns: true = title, false = pause menu.
options_from_title: bool,
- /// The live title backdrop (game/backdrop.rs).
- backdrop: backdrop::Backdrop,
- /// When the pause menu opened (Horizon style's entrance).
- pause_since: Option,
dragging: bool,
/// `ClientAvatarState`: walked distance and view bob.
avatar: horizon_client::camera::AvatarBob,
flash: u32,
+ /// Bolts that struck here and sky flashes they made, in total (`status`).
+ lightning_seen: [u32; 2],
/// The head of the bed while sleeping; the visual timer also survives waking.
sleeping: Option<[i32; 3]>,
sleep_timer: u32,
@@ -1387,7 +1392,7 @@ struct Game<'a> {
map_patches: Vec,
/// Player skin downloads, and which skin each atlas skin slot holds
/// (least recently shown first).
- skin_downloads: horizon_client::skins::Downloader,
+ skin_downloads: RefCell,
skin_slots: Vec<(String, usize)>,
cart_models: minecarts::CartModels,
/// The boat the player rides.
@@ -1417,6 +1422,8 @@ struct Game<'a> {
arrow_model: Option,
tnts: Vec,
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
+ /// Where item entities are, while the block entities tick (hoppers).
+ item_columns: Option,
creative_screen: Creative,
control: Option,
frame_stats: horizon_client::control::FrameStats,
@@ -4448,6 +4455,7 @@ impl Game<'_> {
| Screen::Stats
| Screen::Advancements
| Screen::WorldOptions
+ | Screen::Friends
| Screen::CommandBlock
) || self.book.is_some())
}
@@ -4485,10 +4493,17 @@ impl Game<'_> {
};
if capture {
self.mouse.set_ignore_first_move();
+ // macOS warps by re-associating the mouse with the pointer,
+ // which undoes a Locked grab and leaves the pointer free: warp
+ // first there. Wayland moves a pointer only while it is locked,
+ // so everywhere else warp after grabbing.
+ #[cfg(target_os = "macos")]
+ warp(window);
self.captured = window
.set_cursor_grab(CursorGrabMode::Locked)
.or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined))
.is_ok();
+ #[cfg(not(target_os = "macos"))]
if self.captured && self.focused {
warp(window);
}
@@ -4668,20 +4683,12 @@ impl Game<'_> {
}
}
if let Some(title) = &self.title {
- if horizon_client::ui_theme::horizon() {
- let fade = self.backdrop_fade();
- let mut ui =
- horizon_client::ui_theme::Ui::new(&self.gui.atlas, &mut batch, self.cursor);
- title.draw_horizon(&mut ui, fade);
- ui.finish();
- } else {
- title.draw(
- &self.gui.atlas,
- &mut batch,
- self.cursor,
- self.settings.file.bool("hideSplashTexts"),
- );
- }
+ title.draw(
+ &self.gui.atlas,
+ &mut batch,
+ self.cursor,
+ self.settings.file.bool("hideSplashTexts"),
+ );
return batch;
}
let atlas_ptr: *const HudAtlas = &self.gui.atlas;
@@ -4698,9 +4705,7 @@ impl Game<'_> {
// the sleep overlay, debug screen and open screens still draw.
let spectator = self.spectator();
let (wi, hi) = (w as i32, h as i32);
- // Horizon's pause menu sits over the blurred world alone.
- let horizon_pause = self.horizon_pause();
- let show_hud = !self.ui.hide_gui && !horizon_pause;
+ let show_hud = !self.ui.hide_gui;
if show_hud {
self.draw_spyglass(&mut batch);
// Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth /
@@ -4834,10 +4839,11 @@ impl Game<'_> {
let tw = HudBatch::text_width(atlas, text);
batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true);
}
- if !horizon_pause {
- self.draw_chat(&mut batch);
- self.draw_tab_list(&mut batch);
- }
+ self.draw_chat(&mut batch);
+ self.draw_tab_list(&mut batch);
+ // Screen.extractBlurredBackground blurs the world and HUD, while the
+ // screen's background, widgets, toasts and debug overlay stay sharp.
+ batch.blur_at = batch.vertices.len() as u32;
match self.screen {
Screen::Paused if self.pause_menu => self.draw_pause_menu(&mut batch),
// PauseScreen(false): only its title, at the top.
@@ -4858,6 +4864,7 @@ impl Game<'_> {
Screen::Stats => self.draw_stats(&mut batch),
Screen::Advancements => self.draw_advancements(&mut batch),
Screen::WorldOptions => self.draw_world_options(&mut batch),
+ Screen::Friends => self.draw_friends_screen(&mut batch),
Screen::CommandBlock => self.draw_command_block(&mut batch),
Screen::Inventory => {
self.draw_inventory(&mut batch);
@@ -8942,89 +8949,84 @@ impl Game<'_> {
}
}
/// WeatherEffectRenderer: rain and snow columns within the weather radius.
- fn weather_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) {
+ fn weather_geometry(
+ &mut self,
+ camera: glam::DVec3,
+ alpha: f64,
+ ) -> Vec {
use horizon_client::weather;
let (intensity, _) = self.world.weather.levels(alpha as f32);
if intensity <= 0.0 {
- return;
+ return Vec::new();
}
let atlas = &self.gui.atlas;
let (Some(rain_tex), Some(snow_tex)) = (
atlas.sprites.get("environment/rain").copied(),
atlas.sprites.get("environment/snow").copied(),
) else {
- return;
+ return Vec::new();
};
let (cx, cy, cz) = (
camera.x.floor() as i32,
camera.y.floor() as i32,
camera.z.floor() as i32,
);
- let radius = self.settings.weather_radius;
- let ticks = self.world.game_time;
- let partial = alpha as f32;
- let eye = [camera.x, camera.y, camera.z];
- // Vanilla draws every rain column before the snow ones.
- let mut columns = (Vec::new(), Vec::new());
- for z in cz - radius..=cz + radius {
- for x in cx - radius..=cx + radius {
+ // The 32x32 direction table supports at most a 15-block radius.
+ let radius = self.settings.weather_radius.clamp(0, 15);
+ let eye = camera.to_array();
+ let mut rain = Vec::new();
+ let mut snow_vertices = Vec::new();
+ // Saturation keeps extreme camera coordinates from overflowing the loop.
+ for z in cz.saturating_sub(radius)..=cz.saturating_add(radius) {
+ for x in cx.saturating_sub(radius)..=cx.saturating_add(radius) {
let top = self.rain_height(x, z);
- let y0 = (cy - radius).max(top);
- let y1 = (cy + radius).max(top);
+ let y0 = cy.saturating_sub(radius).max(top);
+ let y1 = cy.saturating_add(radius).max(top);
if y1 == y0 {
continue;
}
let Some(snow) = self.precipitation(x, cy, z) else {
continue;
};
- let mut random = weather::column_random(x, z);
+ let parameters = self.weather_parameters.get(x, z);
let light = self.world.light(x, top.max(cy), z);
let coords = i32::from(light & 15) << 4 | i32::from(light >> 4) << 20;
- if snow {
- columns.1.push(weather::snow_column(
- &mut random,
- ticks,
- x,
- y0,
- y1,
- z,
- coords,
- partial,
- ));
+ // Only light brightening is needed here; UV phases stay zero.
+ let lc = if snow {
+ let (block, sky) = (coords >> 4 & 15, coords >> 20 & 15);
+ ((block * 3 + 15) / 4) << 4 | ((sky * 3 + 15) / 4) << 20
} else {
- columns.0.push(weather::rain_column(
- &mut random,
- ticks,
- x,
- y0,
- y1,
- z,
- coords,
- partial,
- ));
+ coords
+ };
+ let column = weather::Column {
+ x,
+ z,
+ bottom_y: y0,
+ top_y: y1,
+ u_offset: 0.0,
+ v_offset: 0.0,
+ light_coords: lc,
+ };
+ let r = if snow { snow_tex } else { rain_tex };
+ let vertices = weather::vertices(
+ &column,
+ parameters,
+ snow,
+ eye,
+ radius,
+ intensity,
+ [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0],
+ );
+ if snow {
+ snow_vertices.extend(vertices);
+ } else {
+ rain.extend(vertices);
}
}
}
- let rain = columns.0.iter().map(|c| (c, 1.0, rain_tex));
- let snow = columns.1.iter().map(|c| (c, 0.8, snow_tex));
- for (column, max_alpha, r) in rain.chain(snow) {
- let quad = weather::column_quad(column, eye, max_alpha, radius, intensity);
- let color = quad[0].color;
- let lc = quad[0].light_coords;
- let light = ((lc >> 20 & 15) * 16) as u32 | (((lc >> 4 & 15) * 16) as u32) << 8;
- weather::tile(&quad, |pos, uvs| {
- for (p, [u, v]) in pos.into_iter().zip(uvs) {
- out.push(Vertex {
- normal: [0; 4],
- pos: p,
- uv: [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v],
- layer: 0,
- color,
- light,
- });
- }
- });
- }
+ // Vanilla draws every rain column before the snow ones.
+ rain.extend(snow_vertices);
+ rain
}
/// Player.startSleepInBed: night or thunder, no monsters within 8 blocks;
/// the bed becomes the respawn point either way.
@@ -9586,12 +9588,7 @@ impl Game<'_> {
// Camera.getCameraEntityPartialTicks: the view, the hand and the
// player's own model stay smooth while the level is frozen.
let camera_alpha = self.clock.camera_fraction();
- let live = self.backdrop_live();
- let view = if live {
- self.backdrop_view()
- } else {
- self.camera_view(camera_alpha as f32)
- };
+ let view = self.camera_view(camera_alpha as f32);
let (camera, underwater, view_yaw, view_pitch) = match view {
Some((c, yaw, pitch)) => {
let s =
@@ -9739,9 +9736,7 @@ impl Game<'_> {
// LevelLoadingScreen (Reason.OTHER) draws the title's panorama.
let title = self.title.is_some()
|| self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
- let (yaw, pitch) = if live {
- (view_yaw, view_pitch)
- } else if title {
+ let (yaw, pitch) = if title {
// PanoramaRenderer: the title cube spins at 0.1 degrees per tick, pitched 10 degrees.
(
self.panorama_rotation.update(
@@ -9753,9 +9748,7 @@ impl Game<'_> {
} else {
(view_yaw, view_pitch)
};
- let fov_degrees = if live {
- 72.0
- } else if title {
+ let fov_degrees = if title {
85.0
} else {
self.fov_degrees(camera_alpha as f32, camera.to_array())
@@ -9782,15 +9775,17 @@ impl Game<'_> {
self.entity_geometry(camera, alpha, entities)
});
}
+ let bolts = if title {
+ Vec::new()
+ } else {
+ self.bolt_instances()
+ };
let mut additive = Vec::new();
- if !title {
- self.bolt_geometry(camera, &mut additive);
- if self.dim == Dim::End {
- let mut dragon = Vec::new();
- self.dragon_geometry(camera, alpha, &mut dragon, &mut additive);
- self.dragon_fireball_geometry(camera, alpha, &mut dragon);
- entities.extend(dragon);
- }
+ if !title && self.dim == Dim::End {
+ let mut dragon = Vec::new();
+ self.dragon_geometry(camera, alpha, &mut dragon, &mut additive);
+ self.dragon_fireball_geometry(camera, alpha, &mut dragon);
+ entities.extend(dragon);
}
// A Java pack's `clouds` replaces the cloud option (`renderClouds`:
// "false", "fast", "true"), as Iris overrides `getCloudsType`.
@@ -9804,7 +9799,7 @@ impl Game<'_> {
}
.to_owned()
};
- let (celestial, stars) = if title && !live {
+ let (celestial, stars) = if title {
(Vec::new(), None)
} else if self.dim == Dim::Overworld
&& self.potions.effects.get("darkness").is_none()
@@ -9812,8 +9807,8 @@ impl Game<'_> {
{
// Camera.doesMobEffectBlockSky: no sun, moon or stars.
self.celestial_geometry(&sky)
- } else if self.dim == Dim::End {
- (self.end_sky_geometry(), None)
+ } else if self.dim == Dim::End && self.settings.horizon.sky {
+ (self.end_flash_geometry(), None)
} else {
(Vec::new(), None)
};
@@ -9830,11 +9825,11 @@ impl Game<'_> {
if !title {
self.end_geometry(camera, &mut entities);
}
- if (!title || live) && self.dim == Dim::Overworld && self.settings.horizon.weather {
- horizon_client::spans::time("weather", || {
- self.weather_geometry(camera, alpha, &mut entities)
- });
- }
+ let weather = if !title && self.dim == Dim::Overworld && self.settings.horizon.weather {
+ horizon_client::spans::time("weather", || self.weather_geometry(camera, alpha))
+ } else {
+ Vec::new()
+ };
let border = (!title)
.then(|| self.border_draw(camera.to_array(), alpha as f32))
.flatten();
@@ -9845,6 +9840,8 @@ impl Game<'_> {
self.gather_dynamic_lights(camera, alpha);
}
let frame = Frame {
+ weather: &weather,
+ weather_time: horizon_client::weather::Time::new(self.world.game_time, alpha as f32),
shader: self.shader_inputs(camera, alpha as f32),
nether_lighting: self.dim == Dim::Nether,
camera,
@@ -9857,9 +9854,15 @@ impl Game<'_> {
detail_distance: (self.streaming.radius * 16) as f32,
depth_far,
underwater,
- title: title && !live,
+ title,
skybox: self.dim == Dim::Overworld && self.settings.horizon.sky,
end_sky: self.dim == Dim::End && self.settings.horizon.sky,
+ end_sky_sprite: self
+ .gui
+ .atlas
+ .sprites
+ .get("environment/end_sky")
+ .map(|r| [r.u0, r.v0, r.u1, r.v1]),
environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)),
cave_culling,
water_fog,
@@ -9885,7 +9888,7 @@ impl Game<'_> {
debug_lines_on_top: &debug_lines_on_top,
debug_crosshair: &debug_crosshair,
hud: &hud,
- clouds: ((!title || live)
+ clouds: (!title
&& self.dim == Dim::Overworld
&& horizon_client::clouds::visible(&clouds_mode, sky.cloud_color[3]))
.then(|| self.gui.atlas.sprites.get("horizon/white"))
@@ -9902,6 +9905,13 @@ impl Game<'_> {
}),
entities: &entities,
dynamic_lights: &self.dynamic_lights,
+ lightning: horizon_client::gfx::lightning::Input {
+ bolts: &bolts,
+ uv: [
+ self.gui.atlas.font.white().u0,
+ self.gui.atlas.font.white().v0,
+ ],
+ },
additive: &additive,
see_through: &see_through,
celestial: if self.settings.horizon.sky || title {
@@ -9933,13 +9943,6 @@ impl Game<'_> {
darkness: self.darkness_lighting(alpha as f32),
night_vision: self.night_vision_intensity(),
block_flicker: self.fog.block_light_flicker,
- post: if live {
- Some(horizon_client::post::PostGrade::FROST)
- } else if self.horizon_pause() {
- Some(horizon_client::post::PostGrade::PAUSE)
- } else {
- None
- },
menu_blur: self.menu_blur(),
};
let result = match self.renderer.as_mut() {
@@ -10007,17 +10010,18 @@ impl Game<'_> {
};
level_loading::draw(batch, atlas, Some(&status), Some(self.loading_progress));
}
- /// `Screen.extractBlurredBackground` over the panorama: every classic
- /// screen of the title menus but the title itself (`TitleScreen`
- /// doesn't blur), when `menuBackgroundBlurriness` is at least 1.
+ /// `Screen.extractBlurredBackground` over the panorama or the world and
+ /// HUD, when `menuBackgroundBlurriness` is at least 1.
fn menu_blur(&self) -> Option {
let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
- let blurred = !horizon_client::ui_theme::horizon()
- && (loading
- || self.title.as_ref().is_some_and(|t| {
- self.screen == Screen::Options
- || !matches!(t.mode, horizon_client::title::Mode::Main)
- }));
+ let blurred = loading
+ || self.title.as_ref().is_some_and(|t| {
+ self.screen == Screen::Options
+ || !matches!(t.mode, horizon_client::title::Mode::Main)
+ })
+ || (self.title.is_none()
+ && self.player.is_some()
+ && self.screen.blurs_background(self.pause_menu));
let radius = self.settings.menu_blur as f32;
(blurred && radius >= 1.0).then_some(radius)
}
@@ -10096,7 +10100,7 @@ impl Game<'_> {
}
Screen::GameModeSwitcher => self.close_gamemode_switcher(false),
Screen::Dead => {}
- Screen::Stats => self.screen = Screen::Paused,
+ Screen::Stats | Screen::Friends => self.screen = Screen::Paused,
Screen::Advancements => self.close_advancements(),
Screen::WorldOptions => self.world_options_escape(),
Screen::CommandBlock => self.close_command_block(),
@@ -10570,15 +10574,6 @@ impl ApplicationHandler for Game<'_> {
) {
self.last_input = Instant::now();
}
- if let WindowEvent::MouseInput {
- state,
- button: MouseButton::Left,
- ..
- } = &event
- {
- // The press state of Horizon-style buttons.
- horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed);
- }
if (self.pending_entry.is_some() || self.world_loader.is_some())
&& matches!(&event, WindowEvent::KeyboardInput { event, .. }
if event.state == ElementState::Pressed
@@ -10678,9 +10673,7 @@ impl ApplicationHandler for Game<'_> {
if matches!(self.screen, Screen::Inventory | Screen::Creative) {
self.inventory_drag_move();
}
- if let Some(title) = &mut self.title
- && !horizon_client::ui_theme::horizon()
- {
+ if let Some(title) = &mut self.title {
title.drag(self.cursor, (b.width, b.height));
title.drag_field(&self.gui.atlas, self.cursor.0);
}
@@ -10706,9 +10699,7 @@ impl ApplicationHandler for Game<'_> {
}) * wheel_sensitivity
};
let d = scaled(raw_y) as f32;
- if let Some(title) = &mut self.title
- && !horizon_client::ui_theme::horizon()
- {
+ if let Some(title) = &mut self.title {
let size = self
.window
.as_ref()
@@ -10796,21 +10787,13 @@ impl ApplicationHandler for Game<'_> {
.as_ref()
.map(|r| [r.config.width, r.config.height])
.unwrap_or([1, 1]);
- let mut b = HudBatch::new(size);
+ let b = HudBatch::new(size);
let atlas = &self.gui.atlas;
let shift = self.has_shift_down();
let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| {
- if horizon_client::ui_theme::horizon() {
- (
- t.click_horizon(atlas, &mut b, self.cursor.0, self.cursor.1),
- false,
- )
- } else {
- let clicked =
- t.click(self.cursor.0, self.cursor.1, (b.width, b.height));
- t.press_field(atlas, self.cursor, (b.width, b.height), shift);
- clicked
- }
+ let clicked = t.click(self.cursor.0, self.cursor.1, (b.width, b.height));
+ t.press_field(atlas, self.cursor, (b.width, b.height), shift);
+ clicked
});
self.save_title_options();
if sound {
@@ -10946,6 +10929,9 @@ impl ApplicationHandler for Game<'_> {
Screen::WorldOptions if pressed && button == MouseButton::Left => {
self.world_options_click()
}
+ Screen::Friends if pressed && button == MouseButton::Left => {
+ self.friends_screen_click()
+ }
Screen::CommandBlock if pressed && button == MouseButton::Left => {
self.command_block_click()
}
@@ -11045,9 +11031,7 @@ impl ApplicationHandler for Game<'_> {
}
}
WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => {
- if event.state == ElementState::Pressed
- && self.title.as_ref().is_some_and(|t| !t.skip_opening())
- {
+ if event.state == ElementState::Pressed {
if let Some(shortcut) = self.edit_shortcut(&event) {
self.title_shortcut(shortcut);
return Ok(());
@@ -11140,11 +11124,6 @@ impl ApplicationHandler for Game<'_> {
+ (turn(KeyCode::ArrowDown) - turn(KeyCode::ArrowUp)) * 90.0 * secs)
.clamp(-90.0, 90.0);
}
- self.update_backdrop()?;
- horizon_client::ui_theme::set_backdrop(self.backdrop_fade());
- if self.screen != Screen::Paused {
- self.pause_since = None;
- }
if self.title.is_none() {
horizon_client::spans::time("update_world", || self.update_world());
horizon_client::spans::time("spawn_player", || self.spawn_player())?;
@@ -11166,8 +11145,6 @@ impl ApplicationHandler for Game<'_> {
}
self.tick_ambience();
self.tick_fov();
- } else if self.title.is_some() {
- self.tick_backdrop();
}
self.tick_music();
self.tick_sound_engine();
@@ -11438,6 +11415,7 @@ impl<'a> Game<'a> {
gui,
fog: Default::default(),
screen_fx: Default::default(),
+ weather_parameters: Default::default(),
panorama_rotation: Default::default(),
world,
streaming,
@@ -11577,11 +11555,10 @@ impl<'a> Game<'a> {
hand_strength: Default::default(),
settings,
options_from_title: false,
- backdrop: Default::default(),
- pause_since: None,
dragging: false,
avatar: Default::default(),
flash: 0,
+ lightning_seen: [0; 2],
sleeping: None,
sleep_timer: 0,
dim: Dim::Overworld,
@@ -11627,11 +11604,11 @@ impl<'a> Game<'a> {
breath_clouds: Vec::new(),
dragon_model: prepared.dragon_model,
map_patches: Vec::new(),
- skin_downloads: horizon_client::skins::Downloader::new(
+ skin_downloads: RefCell::new(horizon_client::skins::Downloader::new(
std::env::current_dir()
.unwrap_or_default()
.join("assets/skins"),
- ),
+ )),
skin_slots: Vec::new(),
cart_models: prepared.cart_models,
riding: None,
@@ -11651,6 +11628,7 @@ impl<'a> Game<'a> {
arrow_model: prepared.arrow_model,
tnts: Vec::new(),
hoppers: HashMap::new(),
+ item_columns: None,
creative_screen: prepared.creative_screen,
control: None,
frame_stats: Default::default(),
@@ -11949,13 +11927,11 @@ impl Progress {
/// Harness and dedicated runs keep the fully-synchronous startup so their
/// output stays byte-identical; only an ordinary launch shows the window first.
fn synchronous_startup(options: &Options) -> bool {
- let classic = std::env::var("HORIZON_MENU_STYLE").ok().as_deref() == Some("classic");
options.frames.is_some()
|| options.world_frames.is_some()
|| options.benchmark.is_some()
|| options.control.is_some()
|| options.dedicated.is_some()
- || classic
|| std::env::var_os("HORIZON_DISPENSE_FIXTURE").is_some()
|| std::env::var_os("HORIZON_SCULK_FIXTURE").is_some()
|| std::env::var_os("HORIZON_COMMAND_SCRIPT").is_some()
@@ -11976,7 +11952,7 @@ fn load_resources(
let requested_root = root.clone();
let threads = settings.horizon.worker_threads();
// Stage A: the menu bundle (atlas and panorama). With a loading screen it is
- // published at once so the title backdrop can appear while the world bundle
+ // published at once so the title screen can appear while the world bundle
// loads; the synchronous launch instead carries it in `Loaded`.
let mut loaded_gui = None;
let mut ui_ready = false;
@@ -12349,6 +12325,8 @@ fn loading_renderer(
/// A title-shaped frame: black clear and panorama, only the HUD is drawn.
fn loading_frame(hud: &HudBatch) -> Frame<'_> {
Frame {
+ weather: &[],
+ weather_time: horizon_client::weather::Time::new(0, 0.0),
camera: glam::DVec3::new(0.5, 100.0, 0.5),
yaw: 0.0,
pitch: 10.0,
@@ -12363,6 +12341,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
title: true,
skybox: false,
end_sky: false,
+ end_sky_sprite: None,
environment_fog: None,
water_fog: [0.0; 3],
fog: None,
@@ -12377,6 +12356,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
entities: &[],
dynamic_lights: &[],
clouds: None,
+ lightning: Default::default(),
additive: &[],
see_through: &[],
celestial: &[],
@@ -12393,7 +12373,6 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
darkness: (0.0, 0.0),
night_vision: 0.0,
block_flicker: 0.0,
- post: None,
menu_blur: None,
shader: Default::default(),
}
@@ -12420,18 +12399,8 @@ fn start_game<'a>(
let handoff = prepared.is_some();
let mut settings = match settings {
Some(settings) => settings,
- None => {
- horizon_client::ui_theme::load_preferences(&std::env::current_dir()?);
- Settings::load(&std::env::current_dir()?.join("options.txt"))
- }
+ None => Settings::load(&std::env::current_dir()?.join("options.txt")),
};
- // Scripted and frame-limited runs (the parity harnesses) see vanilla's
- // screens unless HORIZON_MENU_STYLE asks otherwise.
- if (options.frames.is_some() || options.control.is_some())
- && std::env::var_os("HORIZON_MENU_STYLE").is_none()
- {
- horizon_client::ui_theme::set_style(horizon_client::ui_theme::MenuStyle::Classic);
- }
if let Some(d) = options.distance_override {
settings.render_distance = d;
}
@@ -12537,12 +12506,6 @@ fn start_game<'a>(
&game.options.resources,
);
title.last_server = game.settings.file.string("lastServer");
- // The launcher's opening, once per session and only in Horizon's style.
- if horizon_client::ui_theme::horizon() && game.options.frames.is_none() {
- title
- .opening
- .set(Some(horizon_client::front::Opening::new()));
- }
game.title = Some(title);
}
}
@@ -12900,7 +12863,6 @@ fn run_loading(
pack_error: Option,
started: Instant,
) -> Result<()> {
- horizon_client::ui_theme::load_preferences(&std::env::current_dir()?);
let progress = Progress::new();
let (receiver, loader) =
startup_menu::spawn_loader(&options, &settings, &vanilla_root, started, &progress)?;
diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs
index 9a5cd6a58..ea686e711 100644
--- a/crates/horizon-client/src/game/agent.rs
+++ b/crates/horizon-client/src/game/agent.rs
@@ -403,6 +403,7 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
+ Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
}
}
diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs
index 52dfa7e1c..bed835663 100644
--- a/crates/horizon-client/src/game/allays.rs
+++ b/crates/horizon-client/src/game/allays.rs
@@ -9,18 +9,28 @@ impl Game<'_> {
pub(super) fn tick_allays(&mut self) {
let griefing = self.ui.rules.bool("mob_griefing");
let player = self.player.as_ref().map(|p| p.position);
+ // The playing jukeboxes, found at the first allay: no allay starts
+ // or stops one, and the block entities run into the thousands.
+ let mut jukeboxes: Option> = None;
for i in 0..self.mobs.len() {
if self.mobs[i].species() != Species::Allay || !self.mobs[i].alive() {
continue;
}
let pos = self.mobs[i].position;
// Dancing: a playing jukebox within 10 blocks.
- let dancing = self.world.block_entities.iter().any(|(k, e)| {
- matches!(e, BlockEntity::Jukebox(j) if j.playing)
- && (f64::from(k.0) + 0.5 - pos.x).powi(2)
- + (f64::from(k.1) + 0.5 - pos.y).powi(2)
- + (f64::from(k.2) + 0.5 - pos.z).powi(2)
- <= 100.0
+ let jukeboxes = jukeboxes.get_or_insert_with(|| {
+ self.world
+ .block_entities
+ .iter()
+ .filter(|(_, e)| matches!(e, BlockEntity::Jukebox(j) if j.playing))
+ .map(|(k, _)| *k)
+ .collect()
+ });
+ let dancing = jukeboxes.iter().any(|k| {
+ (f64::from(k.0) + 0.5 - pos.x).powi(2)
+ + (f64::from(k.1) + 0.5 - pos.y).powi(2)
+ + (f64::from(k.2) + 0.5 - pos.z).powi(2)
+ <= 100.0
});
self.mobs[i].extra.flag =
dancing && !horizon_client::mobs::goals::should_panic(&self.mobs[i]);
diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs
index 9f174c5ef..9fd41bb55 100644
--- a/crates/horizon-client/src/game/armor_stands.rs
+++ b/crates/horizon-client/src/game/armor_stands.rs
@@ -432,6 +432,10 @@ impl Game<'_> {
(false, false) => (0.5, 1.975),
};
let edge = (width + height + width) / 3.0 * 4.0;
+ // 26.3 compares the size with RenderSystem.DEFAULT_DEPTH_CLEAR_VALUE,
+ // which is 0.0 (reverse Z; the bytecode is `dconst_0`): an empty
+ // marker box falls back to 4, so a visible marker stand draws.
+ // Holograms stay hidden through the invisible flag instead.
let range = if edge == 0.0 { 4.0 } else { edge } * 64.0;
let dragon = a.equipment[5]
.as_ref()
@@ -700,9 +704,15 @@ impl Game<'_> {
self.dim == super::Dim::Nether,
)),
};
+ let profile = stack
+ .extra
+ .as_deref()
+ .and_then(|d| d.other.iter().find(|(k, _)| k == "minecraft:profile"))
+ .map(|(_, t)| horizon_client::scoreboard::tag_to_json(t))
+ .unwrap_or(serde_json::Value::Null);
self.pack.item_renderer.submit_special(
&special,
- &serde_json::Value::Null,
+ &profile,
false,
pose,
&self.gui.atlas.sprites,
diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs
deleted file mode 100644
index 8b32495b1..000000000
--- a/crates/horizon-client/src/game/backdrop.rs
+++ /dev/null
@@ -1,303 +0,0 @@
-//! The live title backdrop (Menu style: Horizon): a frozen landscape that
-//! Horizon generates and renders itself behind the title screens, seen
-//! through a slow orbiting camera, falling snow, an overcast sky and the cold
-//! blur and grade of `gfx::PostGrade`. Nothing is bundled: the chunks come
-//! from the vanilla generator for a fixed seed and are cached in
-//! `saves/.horizon-title/backdrop` (no level.dat, so no world list entry).
-//! The ice-spikes spot is found once with `/locate biome`'s search and kept
-//! in `spot.txt` there. The generator is built and the spot found on a
-//! worker, so the title keeps drawing its panorama until both are ready.
-use super::Game;
-use horizon_client::{
- Result,
- save::{Persistent, SaveDir},
- streaming::Streaming,
- vanillagen::VanillaTerrain,
- world::{Weather, World},
-};
-use horizon_core::biome::{BiomeZoom, obfuscate_seed};
-use std::{
- sync::{Arc, Mutex},
- time::Instant,
-};
-
-/// The world the backdrop is cut from (HORIZON_BACKDROP_SEED overrides it).
-const SEED: i64 = 2_026_031_337;
-/// The biome the camera looks for.
-const BIOME: &str = "minecraft:ice_spikes";
-/// Late morning: the snow reads clearly; the grade (`PostGrade::FROST`) makes it cold.
-const DAY_TIME: i64 = 4_000;
-
-/// The worker's result: the generator for [`SEED`], or why it failed.
-type Built = std::result::Result, String>;
-
-#[derive(Default)]
-pub(super) struct Backdrop {
- pub active: bool,
- /// The generator, once the worker has built it; taken when it is installed.
- terrain: Arc>>,
- /// The generator streams the backdrop's chunks.
- installed: bool,
- /// The search for the spot, then the spot (block x, z).
- spot: Arc>>>,
- centred: bool,
- /// Camera position once the ground under it has loaded.
- pub camera: Option,
- pub ready: Option,
- pub started: Option,
-}
-fn seed() -> i64 {
- std::env::var("HORIZON_BACKDROP_SEED")
- .ok()
- .and_then(|s| s.parse().ok())
- .unwrap_or(SEED)
-}
-impl Game<'_> {
- /// How visible the live backdrop is (0 until its first chunks are drawn).
- pub(super) fn backdrop_fade(&self) -> f32 {
- let Some(at) = self.backdrop.ready else {
- return 0.0;
- };
- let x = (at.elapsed().as_secs_f32() / 1.6).clamp(0.0, 1.0);
- x * x * (3.0 - 2.0 * x)
- }
- /// Whether the frame should draw the backdrop world instead of the panorama.
- pub(super) fn backdrop_live(&self) -> bool {
- self.title.is_some() && self.backdrop.active && self.backdrop.camera.is_some()
- }
- /// The orbiting camera: position, yaw and pitch.
- pub(super) fn backdrop_view(&self) -> Option<(glam::DVec3, f32, f32)> {
- let c = self.backdrop.camera?;
- let t = self
- .backdrop
- .started
- .map_or(0.0, |s| s.elapsed().as_secs_f32());
- // A full turn in about six minutes.
- let yaw = (200.0 + t * 1.0) % 360.0;
- let pitch = 6.0 + (t * 0.05).sin() * 2.0;
- Some((c, yaw, pitch))
- }
- /// Called every frame while the title is up.
- pub(super) fn update_backdrop(&mut self) -> Result<()> {
- let wanted = self.pending_entry.is_none()
- && self.title.is_some()
- && horizon_client::ui_theme::horizon()
- && self.world_renderer_ready
- && self.renderer.is_some()
- && self.options.frames.is_none();
- if !wanted {
- if self.backdrop.active && self.title.is_some() {
- self.stop_backdrop();
- }
- if self.title.is_none() && self.backdrop.active {
- // open_world / connect_server replaced the world and streaming.
- self.backdrop = Backdrop::default();
- }
- return Ok(());
- }
- if !self.backdrop.active {
- self.start_backdrop()?;
- }
- if !self.backdrop.installed {
- let built = self
- .backdrop
- .terrain
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .take();
- match built {
- // Still building: the panorama stays up.
- None => return Ok(()),
- Some(Ok(terrain)) => self.install_backdrop(terrain)?,
- Some(Err(e)) => {
- // The panorama stays up for good.
- log::warn!("Horizon: title backdrop: {e}");
- self.backdrop.installed = true;
- return Ok(());
- }
- }
- }
- let found = *self.backdrop.spot.lock().unwrap_or_else(|e| e.into_inner());
- let Some(Some((x, z))) = found else {
- return Ok(());
- };
- if !self.backdrop.centred {
- self.backdrop.centred = true;
- self.streaming.center = (x >> 4, z >> 4);
- self.streaming.paused = false;
- }
- self.update_world();
- if self.backdrop.camera.is_none()
- && (-2..=2)
- .all(|dz| (-2..=2).all(|dx| self.streaming.is_lit((x >> 4) + dx, (z >> 4) + dz)))
- {
- // Above the tallest block nearby, so no spike pokes through the lens.
- let mut top = 64;
- for dz in (-12..=12).step_by(3) {
- for dx in (-12..=12).step_by(3) {
- if let Some(y) = self.surface_y(x + dx, z + dz) {
- top = top.max(y);
- }
- }
- }
- let ground = self.surface_y(x, z).unwrap_or(top);
- let y = (ground + 22).max(top + 4);
- self.backdrop.camera = Some(glam::DVec3::new(
- f64::from(x) + 0.5,
- f64::from(y),
- f64::from(z) + 0.5,
- ));
- }
- if self.backdrop.camera.is_some()
- && self.backdrop.ready.is_none()
- && self
- .renderer
- .as_ref()
- .is_some_and(|r| r.section_count() > 40)
- {
- self.backdrop.ready = Some(Instant::now());
- log::info!(
- "Horizon: title backdrop ready; world rest ready: {}",
- self.res.rest.get().is_some()
- );
- }
- Ok(())
- }
- /// The world tick of the backdrop: time passes for clouds and snow only.
- pub(super) fn tick_backdrop(&mut self) {
- if self.backdrop.active {
- self.world.game_time += 1;
- // The snow's fall follows the client tick counter.
- self.ticks += 1;
- }
- }
- fn surface_y(&self, x: i32, z: i32) -> Option {
- let air = self.res.facts().air;
- (-60..320).rev().find(|&y| self.world.block(x, y, z) != air)
- }
- /// Start building the generator and finding the spot on a worker
- /// (`VanillaTerrain::new` takes seconds on a cold cache).
- fn start_backdrop(&mut self) -> Result<()> {
- log::info!(
- "Horizon: starting title backdrop after {} ms",
- self.started.elapsed().as_millis()
- );
- let seed = seed();
- let dir = self.backdrop_root()?.join(format!("{seed}"));
- std::fs::create_dir_all(&dir)?;
- // The streaming is replaced once the generator is built.
- self.streaming.paused = true;
- let mut world = World::new(self.res.facts().air, seed);
- world.day_time = DAY_TIME;
- world.game_time = 6000;
- // Light snow: the weather renders as snow in frozen biomes.
- world.weather = Weather {
- clear_time: 0,
- rain_time: i32::MAX / 2,
- thunder_time: i32::MAX / 2,
- raining: true,
- thundering: false,
- rain_level: (0.35, 0.35),
- thunder_level: (0.0, 0.0),
- };
- self.world = world;
- self.dim = super::Dim::Overworld;
- if let Some(r) = self.renderer.as_mut() {
- r.clear_sections();
- }
- self.backdrop = Backdrop {
- active: true,
- started: Some(Instant::now()),
- ..Default::default()
- };
- let (terrain, spot) = (self.backdrop.terrain.clone(), self.backdrop.spot.clone());
- let worldgen = self.options.resources.join("worldgen");
- let registry = self.pack.assets.registry;
- let biomes = self.res.biomes().clone();
- let cache = dir.join("spot.txt");
- std::thread::Builder::new()
- .name("horizon-backdrop".into())
- .spawn(move || {
- let built = Instant::now();
- let inner = match VanillaTerrain::new(&worldgen, registry, &biomes, seed) {
- Ok(t) => Arc::new(t),
- Err(e) => {
- *terrain.lock().unwrap_or_else(|e| e.into_inner()) =
- Some(Err(e.to_string()));
- return;
- }
- };
- log::info!(
- "Horizon: title backdrop generator built in {} ms",
- built.elapsed().as_millis()
- );
- *terrain.lock().unwrap_or_else(|e| e.into_inner()) = Some(Ok(inner.clone()));
- // Find (or recall) the spot.
- let known = std::fs::read_to_string(&cache).ok().and_then(|t| {
- let mut it = t.split_whitespace().map(|v| v.parse::().ok());
- Some((it.next()??, it.next()??))
- });
- let found = known.or_else(|| {
- let allowed = |name: &str| name == BIOME;
- let search = horizon_world::worldgen::generator::BiomeSearch {
- allowed: &allowed,
- origin: [0, 64, 0],
- radius: 6400,
- horizontal: 32,
- vertical: 64,
- min_y: -64,
- max_y: 320,
- };
- let found = inner.find_closest_biome(&search);
- log::info!("Horizon: title backdrop: {BIOME} at {found:?}");
- let (_, p) = found?;
- let _ = std::fs::write(&cache, format!("{} {}\n", p[0], p[2]));
- Some((p[0], p[2]))
- });
- *spot.lock().unwrap_or_else(|e| e.into_inner()) =
- Some(Some(found.unwrap_or((0, 0))));
- })?;
- Ok(())
- }
- fn backdrop_root(&self) -> Result {
- Ok(std::env::current_dir()?
- .join("saves")
- .join(".horizon-title")
- .join("backdrop"))
- }
- /// The built generator streams the backdrop's chunks.
- fn install_backdrop(&mut self, inner: Arc) -> Result<()> {
- let seed = seed();
- let save = Arc::new(SaveDir::new(self.backdrop_root()?.join(format!("{seed}"))));
- let (res, pack) = (&*self.res, &self.pack);
- let mut streaming = Streaming::new(
- Arc::new(Persistent {
- inner,
- save: save.clone(),
- registry: pack.assets.clone(),
- biomes: res.biomes().clone(),
- }),
- pack.context.clone(),
- res.threads().min(6),
- );
- streaming.radius = self.settings.render_distance.clamp(4, 10);
- streaming.biome_blend = self.settings.biome_blend;
- streaming.smooth_lighting = self.settings.smooth_lighting;
- streaming.cutout_leaves = self.settings.cutout_leaves;
- streaming.cull_leaves = self.settings.horizon.cull_leaves;
- streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed));
- streaming.paused = true;
- self.streaming = streaming;
- self.save = save;
- self.backdrop.installed = true;
- Ok(())
- }
- fn stop_backdrop(&mut self) {
- self.streaming.paused = true;
- self.world = World::new(self.res.facts().air, 0);
- if let Some(r) = self.renderer.as_mut() {
- r.clear_sections();
- }
- self.backdrop = Backdrop::default();
- }
-}
diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs
index bb1cadd15..094aed6ef 100644
--- a/crates/horizon-client/src/game/block_entity_ticks.rs
+++ b/crates/horizon-client/src/game/block_entity_ticks.rs
@@ -24,6 +24,7 @@ impl Game<'_> {
let ticking = self.block_ticking_area();
let mut spawners = Vec::new();
let mut trial_spawners = Vec::new();
+ self.item_columns = Some(Default::default());
for slot in self.world.block_entity_tickers() {
let pos = slot.0;
// Ticks before this one can remove it (`TickingBlockEntity.isRemoved`).
@@ -56,6 +57,8 @@ impl Game<'_> {
_ => {}
}
}
+ // Items move between passes: the columns hold for this one only.
+ self.item_columns = None;
self.update_song_volumes();
self.scan_for_hearts();
// The client ticks (particles, sounds, the turning mob) are for a
diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs
index 433c588d0..6b24226d9 100644
--- a/crates/horizon-client/src/game/boats.rs
+++ b/crates/horizon-client/src/game/boats.rs
@@ -57,7 +57,7 @@ pub(super) const CHEST_SLOTS: usize = 27;
const WIDTH: f64 = 1.375;
const HEIGHT: f64 = 0.5625;
/// Player.DEFAULT_VEHICLE_ATTACHMENT minus the boat's passenger attachment.
-const SEAT: f64 = 0.1875 - 0.6;
+pub(super) const SEAT: f64 = 0.1875 - 0.6;
impl Boat {
pub fn new(id: u32, wood: Arc, position: Vec3, yaw: f32) -> Self {
Self {
@@ -295,7 +295,7 @@ impl Game<'_> {
}
}
/// `AbstractBoat.tick` for one boat (`controlled` when the player rides it).
- fn tick_boat(&mut self, mut b: Boat, controlled: bool) -> Boat {
+ pub(super) fn tick_boat(&mut self, mut b: Boat, controlled: bool) -> Boat {
b.previous = b.position;
b.previous_yaw = b.yaw;
b.old_status = b.status;
@@ -448,9 +448,12 @@ impl Game<'_> {
pub(super) fn tick_boats(&mut self) {
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
+ // A server player's boat is driven by its client (lan_vehicles.rs).
+ let driven = self.guest_vehicles();
for i in 0..self.boats.len() {
let p = self.boats[i].position;
if Some(self.boats[i].id) == self.riding
+ || driven.contains(&self.boats[i].id)
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
{
continue;
@@ -659,7 +662,11 @@ impl Game<'_> {
self.right = false;
return true;
}
- if sneaking || self.boats[i].out_of_control >= 60.0 || self.riding.is_some() {
+ if sneaking
+ || self.boats[i].out_of_control >= 60.0
+ || self.riding.is_some()
+ || self.ridden_by_guest(self.boats[i].id)
+ {
return false;
}
self.riding = Some(self.boats[i].id);
diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs
index 6fc456f8d..6c5eec301 100644
--- a/crates/horizon-client/src/game/control.rs
+++ b/crates/horizon-client/src/game/control.rs
@@ -564,6 +564,8 @@ impl Game<'_> {
"graphics" => Page::Graphics,
"graphics-advanced" => Page::GraphicsAdvanced,
"extras" => Page::Extras,
+ "horizon" => Page::Horizon,
+ "shader-packs" => Page::ShaderPacks,
other => return Err(format!("unknown options page {other}").into()),
};
if self.screen == Screen::Playing && self.title.is_none() {
@@ -736,6 +738,7 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
+ Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
}
}
@@ -926,6 +929,8 @@ impl Game<'_> {
status["heard"] = json!(self.audio.heard);
// Boats, minecarts, armor stands, item frames and paintings.
status["objects"] = json!(self.objects_status());
+ status["lightning"] = json!({"bolts": self.bolts.len(), "struck": self.lightning_seen[0],
+ "flashes": self.lightning_seen[1], "flash": self.flash});
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
status["projectiles"] = json!(self.projectiles_status());
status
diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs
index d36e0adec..dd8c5335a 100644
--- a/crates/horizon-client/src/game/creatures.rs
+++ b/crates/horizon-client/src/game/creatures.rs
@@ -390,6 +390,7 @@ impl Game<'_> {
player,
others,
others_grid: None,
+ others_index: None,
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
game_time: self.world.game_time,
day_time: self.world.day_time,
@@ -402,7 +403,7 @@ impl Game<'_> {
end: self.dim == Dim::End,
world_seed: self.level.seed,
sea_level: if self.dim == Dim::Nether { 32 } else { 63 },
- teams: self.mob_teams(),
+ teams: std::sync::Arc::new(self.mob_teams()),
items: Some(self.res.items()),
difficulty: self.local_difficulty(
self.player
@@ -499,13 +500,26 @@ impl Game<'_> {
// The level random, lent to the mobs (brain behaviours draw from
// it) and taken back after their ticks.
let mut scratch = self.world.random.clone();
- let mut pushes = Vec::new();
+ let mut pushes = horizon_client::mobs::PendingPushes::default();
let mut keep = Vec::with_capacity(mobs.len());
let mut grid =
horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds));
+ // All but the snapshot is the same for every mob of the tick, so
+ // build it once: the player view and the teams scan every UUID.
+ let base = self.mob_world_base(&[]);
+ // Each mob keeps its snapshot slot all tick; the first slot of an
+ // id answers, as a scan would.
+ let mut index = horizon_client::fast_hash::FxHashMap::::default();
+ for (i, s) in snapshot.iter().enumerate() {
+ index.entry(s.id).or_insert(i as u32);
+ }
for i in 0..mobs.len() {
- let mut w = self.mob_world_base(&snapshot);
- w.others_grid = Some(&grid);
+ let mut w = MobWorld {
+ others: &snapshot,
+ others_grid: Some(&grid),
+ others_index: Some(&index),
+ ..base.clone()
+ };
let m = &mut mobs[i];
w.nearest_player = super::natural_spawning::nearest_player(
&players,
@@ -589,7 +603,11 @@ impl Game<'_> {
if let Some(host) = self.lan.as_mut()
&& !guests.is_empty()
{
- bindings.retain(|id, _| mobs.iter().any(|m| m.id == *id));
+ // A set: a scan of every mob for each binding is quadratic, and a
+ // server's loaded mobs run into the thousands.
+ let live: horizon_client::fast_hash::FxHashSet =
+ mobs.iter().map(|m| m.id).collect();
+ bindings.retain(|id, _| live.contains(id));
host.mob_players = bindings;
}
self.mobs.append(&mut mobs);
@@ -2929,6 +2947,10 @@ impl Game<'_> {
let scale = f64::from(self.settings.entity_distance);
for mob in &self.mobs {
let entity_start = out.len();
+ // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws.
+ if mob.invisible {
+ continue;
+ }
let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera;
// Entity.shouldRenderAtSqrDistance: 64 times the bounding box's
// mean edge, scaled by the entity distance option.
diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs
index a2e1b0ce6..553cd0d96 100644
--- a/crates/horizon-client/src/game/debug_keys.rs
+++ b/crates/horizon-client/src/game/debug_keys.rs
@@ -753,7 +753,7 @@ impl Game<'_> {
let lerp = |a: f64, b: f64| a + f64::from(alpha) * (b - a);
let lerpf = |a: f32, b: f32| a + alpha * (b - a);
for m in &self.mobs {
- if m.removed || m.has_effect("minecraft:invisibility") {
+ if m.removed || m.invisible || m.has_effect("minecraft:invisibility") {
continue;
}
let pos = [
diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs
index b4e358d50..61725c6ab 100644
--- a/crates/horizon-client/src/game/dispenser.rs
+++ b/crates/horizon-client/src/game/dispenser.rs
@@ -1736,7 +1736,9 @@ impl Game<'_> {
mob.head_pitch = old.head_pitch;
mob.persistent = old.persistent;
mob.custom_name = old.custom_name.clone();
+ mob.custom_name_text = old.custom_name_text.clone();
mob.name_visible = old.name_visible;
+ mob.invisible = old.invisible;
mob.no_ai = old.no_ai;
mob.silent = old.silent;
mob.no_gravity = old.no_gravity;
diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs
index a7813c767..98a595f76 100644
--- a/crates/horizon-client/src/game/end.rs
+++ b/crates/horizon-client/src/game/end.rs
@@ -138,47 +138,12 @@ impl Game<'_> {
}
}
- /// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times,
- /// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
- pub(super) fn end_sky_geometry(&self) -> Vec {
- let mut out = Vec::with_capacity(6 * 256 * 4);
- let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else {
+ /// SkyRenderer.renderEndFlash, drawn after the renderer's resident sky mesh.
+ pub(super) fn end_flash_geometry(&self) -> Vec {
+ let mut out = Vec::new();
+ // The old combined sky/flash draw also skipped the flash without a sky sprite.
+ if !self.gui.atlas.sprites.contains_key("environment/end_sky") {
return out;
- };
- use std::f32::consts::FRAC_PI_2;
- let faces = [
- glam::Mat4::IDENTITY,
- glam::Mat4::from_rotation_x(FRAC_PI_2),
- glam::Mat4::from_rotation_x(-FRAC_PI_2),
- glam::Mat4::from_rotation_x(std::f32::consts::PI),
- glam::Mat4::from_rotation_z(FRAC_PI_2),
- glam::Mat4::from_rotation_z(-FRAC_PI_2),
- ];
- let step = 200.0 / 16.0;
- for pose in faces {
- for a in 0..16 {
- for b in 0..16 {
- let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32);
- let (x1, z1) = (x0 + step, z0 + step);
- let corners = [
- (x0, z0, [r.u0, r.v0]),
- (x0, z1, [r.u0, r.v1]),
- (x1, z1, [r.u1, r.v1]),
- (x1, z0, [r.u1, r.v0]),
- ];
- for (x, z, uv) in corners {
- let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z));
- out.push(Vertex {
- normal: [0; 4],
- pos: p.to_array(),
- uv,
- layer: 2,
- color: 0xFF28_2828,
- light: 0,
- });
- }
- }
- }
}
// SkyRenderer.renderEndFlash: the end_flash sprite at height 100, scale 60.
let intensity = self.end.flash.intensity(self.clock.fraction() as f32);
diff --git a/crates/horizon-client/src/game/friends.rs b/crates/horizon-client/src/game/friends.rs
index 51dfe3fbf..f55e96392 100644
--- a/crates/horizon-client/src/game/friends.rs
+++ b/crates/horizon-client/src/game/friends.rs
@@ -1,4 +1,5 @@
-//! Play with friends, host side: "Invite friends" opens the world to LAN if
+//! Play with friends, host side: "Start Sharing" on the Play with Friends
+//! screen (`friends_screen`, the pause menu's Friends button) opens the world to LAN if
//! it isn't (with Open to LAN's defaults) and shares that port behind an
//! invite code (horizon-friends). The code holds this computer's addresses
//! and the key, so friends join with no server of ours; a relay the player
@@ -6,7 +7,12 @@
//! LAN one, unchanged: tunnelled guests are LAN guests that connect from the
//! loopback address.
use super::{Game, lan::LanSettings};
-use horizon_client::{Result, front::FriendsView, text::Text};
+use horizon_client::{
+ Result,
+ friends_screen::{self, Action, FriendsView},
+ hud::HudBatch,
+ text::Text,
+};
use horizon_friends::{Host, HostConfig, HostEvent, PathMode, host::DEFAULT_PORT, reach, stun};
use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION};
use std::time::{Duration, Instant};
@@ -52,10 +58,12 @@ impl Game<'_> {
if self.friends.is_some() {
return Ok(());
}
- if self.remote.is_some() || self.title.is_some() {
+ // Single player on its server thread shares that server, as Open to
+ // LAN publishes it; another server can't be shared.
+ if self.title.is_some() || (self.remote.is_some() && self.integrated.is_none()) {
return Err("open a singleplayer world first".into());
}
- let opened_lan = self.lan.is_none();
+ let opened_lan = self.lan_port().is_none();
if opened_lan {
// ShareToLanScreen's defaults, as the world options screen offers them.
self.lan_open(LanSettings {
@@ -153,7 +161,7 @@ impl Game<'_> {
}
if announce {
self.system_message(Text::literal(
- "Your invite code is ready in the pause menu: copy it and send it to your friends.",
+ "Your invite code is ready: Game Menu, Play with Friends. Copy it and send it to your friends.",
));
}
}
@@ -169,16 +177,55 @@ impl Game<'_> {
}
}
- /// What the pause menu shows.
+ /// Play with Friends. The world is paused under it in singleplayer, so
+ /// new codes and sessions are read while it is drawn.
+ pub(super) fn draw_friends_screen(&mut self, batch: &mut HudBatch) {
+ self.tick_friends();
+ let view = self.friends_view();
+ friends_screen::draw(batch, &self.gui.atlas, self.cursor, &view, true);
+ }
+ pub(super) fn friends_screen_click(&mut self) {
+ let view = self.friends_view();
+ let Some(action) =
+ friends_screen::click(&self.gui.atlas, self.gui_size(), self.cursor, &view)
+ else {
+ return;
+ };
+ self.audio.play_button_click();
+ match action {
+ Action::Share => {
+ if let Err(e) = self.friends_start() {
+ self.system_message(Text::literal(format!("Couldn't share the world: {e}")));
+ }
+ }
+ Action::Copy => self.friends_copy(),
+ Action::Stop => self.friends_stop(),
+ // The system browser, as the Shader Packs page opens its folder.
+ Action::Help => {
+ if let Some(url) = &view.help {
+ super::packs::open_folder(std::path::Path::new(url));
+ }
+ }
+ Action::Done => self.screen = super::Screen::Paused,
+ }
+ }
+
+ /// What Play with Friends shows.
pub(super) fn friends_view(&self) -> FriendsView {
- let guests = self
- .lan
- .as_ref()
- .map(|h| h.hub.guests.iter().map(|g| g.name.clone()).collect())
- .unwrap_or_default();
+ let guests = match &self.lan {
+ Some(h) => h.hub.guests.iter().map(|g| g.name.clone()).collect(),
+ // On the server thread: the other players the server lists.
+ None if self.integrated.is_some() => {
+ let me = self.options.player_name();
+ let mut names = self.remote_online_names().unwrap_or_default();
+ names.retain(|n| *n != me);
+ names
+ }
+ None => Vec::new(),
+ };
let Some(s) = &self.friends else {
return FriendsView {
- shown: self.remote.is_none(),
+ shown: self.remote.is_none() || self.integrated.is_some(),
..FriendsView::default()
};
};
diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs
index ef5775174..1bd3c7696 100644
--- a/crates/horizon-client/src/game/integrated.rs
+++ b/crates/horizon-client/src/game/integrated.rs
@@ -6,9 +6,10 @@
//! the world's options) with [`Integrated::call`], as vanilla's client calls
//! into its `IntegratedServer`.
//!
-//! On by default. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` runs
-//! the world in the frame instead (the escape hatch while the network
-//! player's side catches up with the in-frame one).
+//! Opt-in again (`--server-thread` or `HORIZON_SERVER_THREAD=1`): it was the
+//! default for one day, but a server's players can't board, ride or hit
+//! boats and minecarts yet (#1222), and single player's window is one of
+//! them here.
use super::{
Game, Options, PackResources, Resources, UiResources,
lan::{LanSettings, Owner},
diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs
index 8e7176a70..1d79f077d 100644
--- a/crates/horizon-client/src/game/item_draw.rs
+++ b/crates/horizon-client/src/game/item_draw.rs
@@ -9,12 +9,13 @@ use horizon_assets::item_model::{
};
use horizon_client::{
block_entity_render::{diffuse_lights, vertex_light},
- hud::HudBatch,
+ hud::{HudBatch, Rect},
item_render::{self, ItemRenderState, SpecialHost, WorldSink},
items::ItemStack,
mesher::Vertex,
};
use serde_json::Value;
+use std::{cell::RefCell, collections::HashMap};
/// The game's answers to what the resolver cannot read from the stack.
pub(super) struct Env<'a, 'g> {
@@ -126,6 +127,8 @@ pub(super) fn local_time(pattern: &str) -> String {
/// Banner and shield pattern textures from the banner pattern registry.
pub(super) struct Host<'a> {
banners: &'a horizon_client::banner::Banners,
+ sprites: &'a HashMap,
+ skins: &'a RefCell,
}
impl SpecialHost for Host<'_> {
fn banner_texture(&self, pattern: &str) -> Option {
@@ -138,6 +141,18 @@ impl SpecialHost for Host<'_> {
.pattern(pattern)
.map(|_| self.banners.shield_texture(pattern))
}
+ fn player_skin(&self, profile: &Value) -> Option {
+ // SkullBlockRenderer.getPlayerSkin: SkinManager.getInsecureSkinInformation
+ // accepts a texture property without a signature, unlike the tab list.
+ let url = horizon_client::skins::profile_skin_url(profile)?;
+ let location =
+ horizon_client::skins::skin_location(&horizon_client::skins::texture_hash(&url)?);
+ let _ = self
+ .skins
+ .borrow_mut()
+ .state(horizon_client::skins::Kind::Skin, &url);
+ self.sprites.contains_key(&location).then_some(location)
+ }
}
/// `ItemOwner` of an entity holding or showing an item.
@@ -177,6 +192,8 @@ impl Game<'_> {
pub(super) fn item_host(&self) -> Host<'_> {
Host {
banners: &self.res.stations().banners,
+ sprites: &self.gui.atlas.sprites,
+ skins: &self.skin_downloads,
}
}
/// The client level as item models read it.
diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs
index 548a69e3f..17e1e09a3 100644
--- a/crates/horizon-client/src/game/lan.rs
+++ b/crates/horizon-client/src/game/lan.rs
@@ -807,7 +807,13 @@ impl Game<'_> {
if has_guests {
let host_entity = state.as_ref().map(|s| s.entity_id);
self.lan_assign_ids();
- self.lan_riding(host_entity, &mut host.hub.riding);
+ let guests: Vec<(u32, i32)> = host
+ .hub
+ .guests
+ .iter()
+ .filter_map(|g| Some((g.vehicle?, g.entity_id)))
+ .collect();
+ self.lan_riding(host_entity, &guests, &mut host.hub.riding);
self.lan_entities(host_entity, &mut host.hub, &mut states);
} else {
states.clear();
diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs
index bc224da9e..eccbd7f0b 100644
--- a/crates/horizon-client/src/game/lan_actions.rs
+++ b/crates/horizon-client/src/game/lan_actions.rs
@@ -292,7 +292,8 @@ impl Game<'_> {
let (left, right) = (self.left, self.right);
self.left = play.digging.is_some();
self.right = play.using.is_some() || self.using.is_some();
- let riding = self.riding.take();
+ // The guest's vehicle (Entity.vehicle) for its turn.
+ let riding = std::mem::replace(&mut self.riding, g.vehicle);
let host_station = self.station.take();
// The guest's bed, sleep counter and respawn point; the host's
// respawn point, anchor and action bar stay theirs.
@@ -467,7 +468,7 @@ impl Game<'_> {
(self.respawn_config, self.level.spawn) = respawn;
// ServerPlayer.displayClientMessage(_, true): the guest's action bar.
let guest_message = std::mem::replace(&mut self.message, message);
- self.riding = riding;
+ let guest_vehicle = std::mem::replace(&mut self.riding, riding);
self.left = left;
self.right = right;
play.mining = std::mem::replace(&mut self.mining, mining);
@@ -491,6 +492,11 @@ impl Game<'_> {
self.mount_menu = host_mount_menu;
self.keys = host_keys;
let g = &mut host.hub.guests[i];
+ let left_vehicle = g.vehicle.filter(|_| guest_vehicle.is_none());
+ if guest_vehicle.is_none() {
+ g.vehicle_good = None;
+ }
+ g.vehicle = guest_vehicle;
let fell_asleep = bed.is_some() && g.bed.is_none();
(g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn);
g.sleeping = g.bed.is_some();
@@ -549,7 +555,24 @@ impl Game<'_> {
let teleported = std::mem::take(&mut m.teleported);
let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum();
g.motion = Some(Box::new(m));
- if moved > 0.0001 || turned || teleported {
+ // Entity.teleportTo takes a rider out of its vehicle.
+ let left_vehicle = match g.vehicle.filter(|_| teleported) {
+ Some(v) => {
+ (g.vehicle, g.vehicle_good) = (None, None);
+ Some(v)
+ }
+ None => left_vehicle,
+ };
+ // ServerPlayer.dismountTo: the client hears it is out of the
+ // vehicle before the teleport beside it. A rider sits where its
+ // vehicle puts it (lan_vehicles.rs), with no teleport.
+ if let Some(vehicle) = left_vehicle {
+ g.send(&C::SetPassengers(play::SetPassengers {
+ vehicle: vehicle as i32,
+ passengers: Vec::new(),
+ }));
+ }
+ if g.vehicle.is_none() && (moved > 0.0001 || turned || teleported) {
host.hub.teleport(i, Some(at));
}
}
@@ -900,16 +923,22 @@ impl Game<'_> {
}
S::Attack(p) => self.guest_attack(host, conn, p.id),
S::Interact(p) => {
- if let Some((position, eye)) = self.look_at_entity(host, gi, p.id) {
- let _ = (position, eye);
+ let before = host.hub.guests[gi].vehicle;
+ if self
+ .look_at_entity(host, gi, p.id, Some(p.location))
+ .is_some()
+ {
let swung = self.as_guest(host, conn, |g| {
let swings = g.swings_started;
let _ = g.use_item();
g.swings_started != swings
});
self.lan_swing_back(host, conn, swung);
+ self.guest_boarded(host, conn, before);
}
}
+ S::MoveVehicle(p) => self.guest_move_vehicle(host, conn, &p),
+ S::PaddleBoat(p) => self.guest_paddle_boat(host, conn, [p.left, p.right]),
S::SetCreativeModeSlot(p) => {
let g = &mut host.hub.guests[gi];
if !g.creative() || !(0..46).contains(&p.slot) {
@@ -1147,19 +1176,39 @@ impl Game<'_> {
}
}
- /// Aim the swapped-in player at an entity; returns its centre and the eye.
+ /// Aim the swapped-in player at an entity; returns where it aims and the
+ /// eye. A boat, minecart, armor stand, item frame or painting is aimed at
+ /// the point the client hit (the interact packet's location) when that
+ /// is on it, else at its centre.
fn look_at_entity(
&mut self,
host: &mut LanHost,
gi: usize,
id: i32,
+ location: Option<[f64; 3]>,
) -> Option<([f64; 3], [f64; 3])> {
+ let object = || {
+ let (lo, hi, origin) = self.object_target(id)?;
+ let middle = [0, 1, 2].map(|k| (lo[k] + hi[k]) / 2.0);
+ let Some(l) = location else {
+ return Some(middle);
+ };
+ let point = [0, 1, 2].map(|k| origin[k] + l[k]);
+ // A little inside the box, so the ray from the eye meets it.
+ let inside = [0, 1, 2].map(|k| {
+ let margin = ((hi[k] - lo[k]) / 2.0).min(0.01);
+ point[k].clamp(lo[k] + margin, hi[k] - margin)
+ });
+ let on = (0..3).all(|k| (point[k] - inside[k]).abs() < 0.1);
+ Some(if on { inside } else { middle })
+ };
let centre = match self.mobs.iter().find(|m| m.id as i32 == id) {
Some(m) => [
m.position.x,
m.position.y + m.kind.height * 0.5,
m.position.z,
],
+ None if self.object_target(id).is_some() => object()?,
// A dragon part or an end crystal (game/dragon.rs).
None => {
let b = self.tracked_special_box(id)?;
@@ -1210,7 +1259,7 @@ impl Game<'_> {
return;
}
let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch);
- if self.look_at_entity(host, gi, id).is_none() {
+ if self.look_at_entity(host, gi, id, None).is_none() {
return;
}
self.as_guest(host, conn, |g| {
@@ -1676,6 +1725,7 @@ impl Game<'_> {
/// regeneration and the food tick (ServerPlayer.doTick). Their hurt
/// sounds are heard at the guest.
fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) {
+ self.guest_vehicle_tick(host, conn);
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
@@ -1730,6 +1780,13 @@ impl Game<'_> {
break;
}
}
+ // A ServerPlayer travels on the server too
+ // (MoveSimulationType.AUTHORITATIVE_SIDE_AND_SERVER), so every tick
+ // on a ladder or vine LivingEntity.handleOnClimbable resets its fall
+ // distance: climbing down doesn't hurt where it lands (#1255).
+ if w.climbable().unwrap_or(false) {
+ w.player.fall_distance = 0.0;
+ }
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs
index 404d00c46..5f46f7c21 100644
--- a/crates/horizon-client/src/game/lan_entities.rs
+++ b/crates/horizon-client/src/game/lan_entities.rs
@@ -89,8 +89,17 @@ fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> {
impl Game<'_> {
/// Who rides what (`Entity.getPassengers`): mobs on mobs, and the
/// host in its boat or minecart.
- pub(super) fn lan_riding(&self, host_entity: Option, riding: &mut Riding) {
+ pub(super) fn lan_riding(
+ &self,
+ host_entity: Option,
+ guests: &[(u32, i32)],
+ riding: &mut Riding,
+ ) {
riding.clear();
+ // The server's players in their boats and minecarts.
+ for &(vehicle, guest) in guests {
+ riding.add(vehicle as i32, guest);
+ }
for m in self.mobs.iter().filter(|m| !m.removed) {
if let Some(vehicle) = m.extra.mount {
riding.add(vehicle as i32, m.id as i32);
@@ -264,6 +273,7 @@ impl Game<'_> {
self.tridents.iter_mut().for_each(|t| give(&mut t.id));
self.rockets.iter_mut().for_each(|r| give(&mut r.id));
self.crystals.iter_mut().for_each(|c| give(&mut c.id));
+ self.bolts.iter_mut().for_each(|b| give(&mut b.id));
}
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
@@ -275,6 +285,10 @@ impl Game<'_> {
None => 0,
};
let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z];
+ // LightningBolt: each client draws and flashes its own.
+ for b in self.bolts.iter().filter(|b| b.id != 0) {
+ out.push(state(b.id, "minecraft:lightning_bolt", b.at, 0.0, false));
+ }
for t in self.tnts.iter().filter(|t| t.id != 0) {
let mut e = state(t.id, "minecraft:tnt", at(t.position), 0.0, t.on_ground);
e.velocity = at(t.velocity);
diff --git a/crates/horizon-client/src/game/lan_vehicles.rs b/crates/horizon-client/src/game/lan_vehicles.rs
new file mode 100644
index 000000000..01195e49e
--- /dev/null
+++ b/crates/horizon-client/src/game/lan_vehicles.rs
@@ -0,0 +1,288 @@
+//! Boats and minecarts for a server's players: LAN guests, players on a
+//! dedicated server, and single player's window on its server thread.
+//!
+//! A player aims at a vehicle, item frame, armor stand or painting as at a
+//! mob (`ServerGamePacketListenerImpl.handleInteract`), and the game's own
+//! code for it runs as that player (`AbstractBoat.interact` seats it,
+//! `VehicleEntity.hurtServer` breaks the vehicle). A boat is driven by its
+//! rider's client (`handleMoveVehicle`, `handlePaddleBoat`); a minecart moves
+//! here with the rider's input (`ServerPlayer.getLastClientMoveIntent`).
+//! Sneaking gets out (`Player.rideTick`: `wantsToStopRiding`), and the client
+//! is teleported where the player lands (`ServerPlayer.dismountTo`).
+use super::{Game, Keys, boats::SEAT, lan::LanHost};
+use horizon_client::collisions::SceneCollisions;
+use horizon_core::geometry::{Aabb, Vec3};
+use horizon_protocol::{
+ packets::play::{self, Clientbound as C},
+ text::translatable,
+};
+
+/// `PlayerInput` flags, as the server player's client last sent them.
+pub(super) fn input_keys(flags: u8) -> Keys {
+ Keys {
+ forward: flags & 1 != 0,
+ backward: flags & 2 != 0,
+ left: flags & 4 != 0,
+ right: flags & 8 != 0,
+ jump: flags & 16 != 0,
+ shift: flags & 32 != 0,
+ ..Keys::default()
+ }
+}
+
+fn corners(b: Aabb) -> ([f64; 3], [f64; 3]) {
+ let (lo, hi) = (b.min_position(), b.max_position());
+ ([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z])
+}
+
+impl Game<'_> {
+ /// The box of a boat, minecart, armor stand, item frame or painting, and
+ /// the point an interact packet's location is measured from (the
+ /// client's `remote_object_hit` uses the same points).
+ pub(super) fn object_target(&self, id: i32) -> Option<([f64; 3], [f64; 3], [f64; 3])> {
+ let id = u32::try_from(id).ok()?;
+ let at = |v: Vec3| [v.x, v.y, v.z];
+ let centre = |p: [i32; 3]| p.map(|v| f64::from(v) + 0.5);
+ if let Some(b) = self.boats.iter().find(|b| b.id == id) {
+ let (lo, hi) = corners(b.bounds());
+ return Some((lo, hi, at(b.position)));
+ }
+ if let Some(c) = self.carts.iter().find(|c| c.id == id) {
+ let (lo, hi) = corners(c.bounds());
+ return Some((lo, hi, at(c.position)));
+ }
+ if let Some(a) = self.armor_stands.iter().find(|a| a.id == id) {
+ let (lo, hi) = corners(a.bounds());
+ return Some((lo, hi, at(a.position)));
+ }
+ if let Some(f) = self.item_frames.iter().find(|f| f.id == id) {
+ let (lo, hi) = f.bounds();
+ return Some((lo, hi, centre(f.pos)));
+ }
+ let p = self.paintings.iter().find(|p| p.id == id)?;
+ let (lo, hi) = p.bounds();
+ Some((lo, hi, centre(p.pos)))
+ }
+
+ /// The vehicles the server's players ride: they move with their riders,
+ /// not in `tick_boats` and `tick_carts`.
+ pub(super) fn guest_vehicles(&self) -> Vec {
+ self.lan.as_ref().map_or_else(Vec::new, |h| {
+ h.hub.guests.iter().filter_map(|g| g.vehicle).collect()
+ })
+ }
+
+ /// Whether a server player other than the one acting rides `vehicle`
+ /// (`Entity.canAddPassenger`: a boat or minecart seats one player here).
+ pub(super) fn ridden_by_guest(&self, vehicle: u32) -> bool {
+ self.lan.as_ref().is_some_and(|h| {
+ h.hub
+ .guests
+ .iter()
+ .any(|g| Some(g.conn) != self.lan_acting && g.vehicle == Some(vehicle))
+ })
+ }
+
+ /// `Player.rideTick` for a server player, before its moves this tick:
+ /// it stays in its seat, steers its minecart, or gets out.
+ pub(super) fn guest_vehicle_tick(&mut self, host: &mut LanHost, conn: u32) {
+ let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
+ return;
+ };
+ let g = &host.hub.guests[gi];
+ let Some(vehicle) = g.vehicle else {
+ return;
+ };
+ let (keys, dead) = (input_keys(g.input), g.dead || g.health <= 0.0);
+ let boat = self.boats.iter().position(|b| b.id == vehicle);
+ let cart = self.carts.iter().any(|c| c.id == vehicle);
+ // The vehicle is gone (broken, in another level) or the rider died:
+ // its client drops it with the entity or the death screen.
+ if dead || (boat.is_none() && !cart) {
+ let g = &mut host.hub.guests[gi];
+ (g.vehicle, g.vehicle_good) = (None, None);
+ return;
+ }
+ if let Some(i) = boat {
+ // AbstractBoat.tick on the server for a boat its rider drives:
+ // only the hurt animation and the damage wear off here.
+ let b = &mut self.boats[i];
+ b.hurt_time = (b.hurt_time - 1).max(0);
+ b.damage = (b.damage - 1.0).max(0.0);
+ }
+ // Getting out goes through leave_guest, which tells the client and
+ // teleports it (ServerPlayer.dismountTo).
+ let seat = self.as_guest(host, conn, |game| {
+ if let Some(i) = game.boats.iter().position(|b| Some(b.id) == game.riding) {
+ if keys.shift {
+ game.dismount(i);
+ return None;
+ }
+ let p = game.boats[i].position;
+ return Some([p.x, p.y + SEAT, p.z]);
+ }
+ // The minecart moves with the rider's input, and lets it out when
+ // it sneaks or the cart breaks.
+ game.tick_cart_riding(keys);
+ game.riding?;
+ let p = game.player.as_ref()?.position;
+ Some([p.x, p.y, p.z])
+ });
+ if let Some(Some(at)) = seat {
+ let g = &mut host.hub.guests[gi];
+ g.previous_position = g.position;
+ g.position = at;
+ }
+ }
+
+ /// After an interaction: a player that got into a vehicle sits in it,
+ /// and its last good vehicle position is where the vehicle is.
+ pub(super) fn guest_boarded(&mut self, host: &mut LanHost, conn: u32, before: Option) {
+ let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
+ return;
+ };
+ let Some(vehicle) = host.hub.guests[gi].vehicle else {
+ return;
+ };
+ if before == Some(vehicle) {
+ return;
+ }
+ // The host in the window rides it already.
+ if self.riding == Some(vehicle) {
+ host.hub.guests[gi].vehicle = before;
+ return;
+ }
+ let at = self
+ .boats
+ .iter()
+ .find(|b| b.id == vehicle)
+ .map(|b| b.position)
+ .or_else(|| {
+ self.carts
+ .iter()
+ .find(|c| c.id == vehicle)
+ .map(|c| c.position)
+ });
+ let g = &mut host.hub.guests[gi];
+ if let Some(p) = at {
+ g.vehicle_good = Some([p.x, p.y, p.z]);
+ g.previous_position = g.position;
+ g.position = [p.x, p.y + SEAT, p.z];
+ g.on_ground = false;
+ }
+ }
+
+ /// `ServerGamePacketListenerImpl.handleMoveVehicle`: the boat its rider
+ /// drives goes where the client says, unless it moved too quickly or
+ /// wrongly; then it stays, and the client is told where it is.
+ pub(super) fn guest_move_vehicle(
+ &mut self,
+ host: &mut LanHost,
+ conn: u32,
+ p: &play::MoveVehicleRequest,
+ ) {
+ let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
+ return;
+ };
+ let [x, y, z] = p.position;
+ if !(x.is_finite() && y.is_finite() && z.is_finite())
+ || !p.yaw.is_finite()
+ || !p.pitch.is_finite()
+ {
+ host.hub.kick(
+ conn,
+ translatable("multiplayer.disconnect.invalid_vehicle_movement", &[]),
+ );
+ return;
+ }
+ let g = &host.hub.guests[gi];
+ if g.awaiting_teleport.is_some() || !g.loaded {
+ return;
+ }
+ let owner = host.hub.singleplayer_owner == Some(g.uuid);
+ let (vehicle, good) = (g.vehicle, g.vehicle_good);
+ let back = |host: &mut LanHost, position: Vec3, yaw: f32| {
+ let packet = play::MoveVehicle {
+ position: [position.x, position.y, position.z],
+ yaw,
+ pitch: 0.0,
+ };
+ host.hub.send_to(conn, &C::MoveVehicle(packet));
+ };
+ // Only a boat is driven by its rider (getControllingPassenger); a
+ // minecart that is elsewhere on the client is put back.
+ let Some(i) = vehicle.and_then(|v| self.boats.iter().position(|b| b.id == v)) else {
+ if let Some(c) = vehicle.and_then(|v| self.carts.iter().find(|c| c.id == v))
+ && c.position.distance_squared(Vec3::new(x, y, z)) > 1.0
+ {
+ back(host, c.position, c.yaw);
+ }
+ return;
+ };
+ let b = &self.boats[i];
+ let old = b.position;
+ let good = good.map_or(old, |g| Vec3::new(g[0], g[1], g[2]));
+ let target = Vec3::new(
+ x.clamp(-3.0E7, 3.0E7),
+ y.clamp(-2.0E7, 2.0E7),
+ z.clamp(-3.0E7, 3.0E7),
+ );
+ // Moved too quickly: more than 10 blocks past its own motion.
+ let moved = target.distance_squared(old) - b.velocity.length_squared();
+ if moved > 100.0 && !owner {
+ log::warn!("boat {} moved too quickly! {moved}", b.id);
+ back(host, old, b.yaw);
+ return;
+ }
+ // vehicle.move(PLAYER, target - lastGood) with the boat's collisions:
+ // where it can't follow the client (a quarter block off, the height
+ // aside), it moved wrongly.
+ let bounds = b.bounds();
+ let mut scene = SceneCollisions {
+ world: &self.world,
+ binding: self.collision,
+ subject: None,
+ };
+ let wanted = target.subtract(good);
+ let resolved = scene
+ .resolve(bounds, wanted, 0.0, b.on_ground)
+ .unwrap_or(wanted);
+ let reached = old.add_vector(resolved);
+ let wrongly = (target.x - reached.x).powi(2) + (target.z - reached.z).powi(2) > 0.0625;
+ let free_before = scene.unobstructed(bounds).unwrap_or(true);
+ // isEntityCollidingWithAnythingNew: a box that was free is not there.
+ let moved_box = bounds.move_by(target.subtract(old));
+ let free_after = scene
+ .unobstructed(moved_box.deflate(Vec3::new(1.0E-5, 1.0E-5, 1.0E-5)))
+ .unwrap_or(true);
+ if free_before && (wrongly || !free_after) {
+ log::warn!("boat {} moved wrongly", b.id);
+ back(host, old, b.yaw);
+ return;
+ }
+ let b = &mut self.boats[i];
+ b.previous = old;
+ b.velocity = target.subtract(old);
+ b.position = target;
+ b.previous_yaw = b.yaw;
+ b.yaw = p.yaw;
+ b.on_ground = p.on_ground;
+ let g = &mut host.hub.guests[gi];
+ g.vehicle_good = Some([target.x, target.y, target.z]);
+ g.previous_position = g.position;
+ g.position = [target.x, target.y + SEAT, target.z];
+ }
+
+ /// `handlePaddleBoat`: the paddles of the boat the player drives.
+ pub(super) fn guest_paddle_boat(&mut self, host: &LanHost, conn: u32, paddles: [bool; 2]) {
+ let vehicle = host
+ .hub
+ .guests
+ .iter()
+ .find(|g| g.conn == conn)
+ .and_then(|g| g.vehicle);
+ if let Some(b) = self.boats.iter_mut().find(|b| Some(b.id) == vehicle) {
+ b.paddling = paddles;
+ }
+ }
+}
diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs
index 6c4dd933f..476cb5aa4 100644
--- a/crates/horizon-client/src/game/lightning.rs
+++ b/crates/horizon-client/src/game/lightning.rs
@@ -5,17 +5,13 @@
//! witches, mooshroom colours, turtles, burnt items), lightning rods, the sky
//! flash, the sounds and the branching additive bolt.
use super::Game;
-use horizon_client::{
- mesher::Vertex,
- mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species},
-};
-use horizon_core::{
- position::BlockPos,
- random::{LegacyRandom, RandomSource},
-};
+use horizon_client::mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species};
+use horizon_core::{position::BlockPos, random::RandomSource};
pub(super) struct Bolt {
- at: [f64; 3],
+ /// The entity id a server's players know it by (0 until it has one).
+ pub id: u32,
+ pub at: [f64; 3],
life: i32,
flashes: i32,
seed: i64,
@@ -137,7 +133,9 @@ impl Game<'_> {
let r = &mut self.world.random;
let seed = r.next_long();
let flashes = r.next_int_bound(3).unwrap_or(0) + 1;
+ self.lightning_seen[0] += 1;
self.bolts.push(Bolt {
+ id: 0,
at,
life: 2,
flashes,
@@ -146,6 +144,24 @@ impl Game<'_> {
converted: Vec::new(),
});
}
+ /// `ClientLevel.addEntity` for a server's lightning bolt: on a client it
+ /// only flashes, sounds and draws (`LightningBolt.tick` off the server).
+ pub(super) fn spawn_remote_bolt(&mut self, id: u32, at: [f64; 3]) {
+ self.bolts.retain(|b| b.id != id);
+ let r = &mut self.world.random;
+ let seed = r.next_long();
+ let flashes = r.next_int_bound(3).unwrap_or(0) + 1;
+ self.lightning_seen[0] += 1;
+ self.bolts.push(Bolt {
+ id,
+ at,
+ life: 2,
+ flashes,
+ seed,
+ visual_only: true,
+ converted: Vec::new(),
+ });
+ }
/// `spawnFire`: fire at the strike point and `extra` random neighbours.
fn bolt_fire(&mut self, at: [f64; 3], extra: i32) {
if self.ui.difficulty < 2 {
@@ -222,6 +238,9 @@ impl Game<'_> {
}
}
if b.life >= 0 {
+ if self.flash == 0 {
+ self.lightning_seen[1] += 1;
+ }
self.flash = 2;
if !b.visual_only {
self.thunder_hit(b);
@@ -349,71 +368,14 @@ impl Game<'_> {
|| e.stack.item.contains("netherite")
});
}
- /// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8
- /// segments of 16 blocks, from the bolt's seed.
- pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec) {
- let white = self.gui.atlas.font.white();
- let uv = [white.u0, white.v0];
- // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
- let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
- for b in &self.bolts {
- let o = (glam::DVec3::from_array(b.at) - camera).as_vec3();
- let mut random = LegacyRandom::new(b.seed);
- let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
- let (mut x_off, mut z_off) = (0f32, 0f32);
- for i in (0..8).rev() {
- xs[i] = x_off;
- zs[i] = z_off;
- x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
- z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
- }
- for layer in 0..4 {
- let mut random = LegacyRandom::new(b.seed);
- for branch in 0..3 {
- let trunk = branch == 0;
- let start = 7 - branch;
- let end = if trunk { 0 } else { start - 3 + 1 };
- let mut sx = xs[start] - x_off;
- let mut sz = zs[start] - z_off;
- for segment in (end..=start).rev() {
- let (ex, ez) = (sx, sz);
- let spread = if trunk { 11 } else { 31 };
- sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
- sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
- let mut top = 0.1 + layer as f32 * 0.2;
- let mut bottom = top;
- if trunk {
- top *= segment as f32 * 0.1 + 1.0;
- bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
- }
- for (rx, rz, lx, lz) in [
- (false, false, true, false),
- (true, false, true, true),
- (true, true, false, true),
- (false, true, false, false),
- ] {
- let s = |p: bool, r: f32| if p { r } else { -r };
- let y0 = segment as f32 * 16.0;
- let corners = [
- [sx + s(rx, bottom), y0, sz + s(rz, bottom)],
- [ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
- [ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
- [sx + s(lx, bottom), y0, sz + s(lz, bottom)],
- ];
- for c in corners {
- out.push(Vertex {
- normal: [0; 4],
- pos: (o + glam::Vec3::from_array(c)).to_array(),
- uv,
- layer: 2,
- color,
- light: 240 | 240 << 8,
- });
- }
- }
- }
- }
- }
- }
+ /// Simulation-order render inputs; seeded geometry lives in the renderer.
+ pub(super) fn bolt_instances(&self) -> Vec {
+ self.bolts
+ .iter()
+ .map(|b| horizon_client::gfx::lightning::Bolt {
+ at: b.at,
+ seed: b.seed,
+ })
+ .collect()
}
}
diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs
index c05c7295f..8ce1940c9 100644
--- a/crates/horizon-client/src/game/machines.rs
+++ b/crates/horizon-client/src/game/machines.rs
@@ -327,6 +327,46 @@ impl Containers<'_> {
}
}
+/// The block columns any item entity's box reaches, so that a hopper with
+/// no item over it skips the scan of every item. Kept for one block-entity
+/// pass, in which items do not move: removing one leaves a superset, still
+/// right, and adding one (always pushed at the end, under a new id) or
+/// removing the last rebuilds the columns.
+#[derive(Default)]
+pub(super) struct ItemColumns {
+ /// The item count and last item id when last asked, if built.
+ seen: Option<(usize, Option)>,
+ cells: horizon_client::fast_hash::FxHashSet<(i32, i32)>,
+}
+impl ItemColumns {
+ /// Whether an item's box may reach into column (x, z).
+ fn may_reach(
+ &mut self,
+ items: &[horizon_client::entities::ItemEntity],
+ x: i32,
+ z: i32,
+ ) -> bool {
+ let (len, last) = (items.len(), items.last().map(|i| i.id));
+ let stale = self
+ .seen
+ .is_none_or(|(seen_len, seen_last)| len > seen_len || last != seen_last);
+ self.seen = Some((len, last));
+ if stale {
+ self.cells.clear();
+ for item in items {
+ let b = item.bounds();
+ let (lo, hi) = (b.min_position(), b.max_position());
+ for cx in lo.x.floor() as i32..=hi.x.floor() as i32 {
+ for cz in lo.z.floor() as i32..=hi.z.floor() as i32 {
+ self.cells.insert((cx, cz));
+ }
+ }
+ }
+ }
+ self.cells.contains(&(x, z))
+ }
+}
+
fn bone_meal() -> ItemStack {
ItemStack {
item: "minecraft:bone_meal".into(),
@@ -648,6 +688,11 @@ impl Game<'_> {
f64::from(pos.2) + 1.0,
],
);
+ if let Some(columns) = self.item_columns.as_mut()
+ && !columns.may_reach(&self.dropped, pos.0, pos.2)
+ {
+ return false;
+ }
let mut i = 0;
while i < self.dropped.len() {
let b = self.dropped[i].bounds();
@@ -880,3 +925,122 @@ impl Game<'_> {
true
}
}
+
+#[cfg(test)]
+mod item_column_tests {
+ use super::ItemColumns;
+ use horizon_client::{entities::ItemEntity, items::ItemStack};
+ use horizon_core::geometry::Vec3;
+
+ fn item(id: u32, x: f64, y: f64, z: f64) -> ItemEntity {
+ let at = Vec3::new(x, y, z);
+ ItemEntity {
+ health: 5,
+ fire_ticks: 0,
+ id,
+ stack: ItemStack::new("minecraft:stone", 1),
+ thrower: None,
+ position: at,
+ previous: at,
+ velocity: Vec3::ZERO,
+ on_ground: true,
+ age: 0,
+ pickup_delay: 0,
+ bob_offset: 0.0,
+ ticks: 0,
+ }
+ }
+ /// `hopper_suck`'s test: some item box meets the hopper's SUCK_AABB.
+ fn scan(items: &[ItemEntity], (x, y, z): (i32, i32, i32)) -> bool {
+ let (min, max) = (
+ Vec3::new(f64::from(x), f64::from(y) + 11.0 / 16.0, f64::from(z)),
+ Vec3::new(f64::from(x) + 1.0, f64::from(y) + 2.0, f64::from(z) + 1.0),
+ );
+ items.iter().any(|i| {
+ let b = i.bounds();
+ let (lo, hi) = (b.min_position(), b.max_position());
+ lo.x < max.x
+ && hi.x > min.x
+ && lo.y < max.y
+ && hi.y > min.y
+ && lo.z < max.z
+ && hi.z > min.z
+ })
+ }
+
+ /// One tick of empty hoppers looking for items: each scans every item
+ /// (before) or asks the columns first (after, build included).
+ #[test]
+ #[ignore]
+ fn hopper_suck_cost() {
+ for (hoppers, count) in [(500i32, 200u32), (2000, 500), (2000, 2000)] {
+ let mut seed = 99u64;
+ let mut next = |range: f64| {
+ seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
+ (seed >> 11) as f64 / (1u64 << 53) as f64 * range
+ };
+ let items: Vec = (0..count)
+ .map(|id| item(id, next(160.0), 64.0, next(160.0)))
+ .collect();
+ let at: Vec<(i32, i32, i32)> = (0..hoppers)
+ .map(|_| (next(160.0) as i32, 63, next(160.0) as i32))
+ .collect();
+ let t = std::time::Instant::now();
+ let a: Vec = at.iter().map(|&h| scan(&items, h)).collect();
+ let before = t.elapsed().as_secs_f64() * 1e3;
+ let t = std::time::Instant::now();
+ let mut columns = ItemColumns::default();
+ let b: Vec = at
+ .iter()
+ .map(|&h| columns.may_reach(&items, h.0, h.2) && scan(&items, h))
+ .collect();
+ let after = t.elapsed().as_secs_f64() * 1e3;
+ assert_eq!(a, b);
+ println!("{hoppers} hoppers, {count} items: {before:.3} ms -> {after:.3} ms");
+ }
+ }
+
+ #[test]
+ fn no_hopper_with_an_item_over_it_is_skipped() {
+ let mut seed = 0x1234_5678_9abc_def1u64;
+ let mut next = |range: f64| {
+ seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
+ (seed >> 11) as f64 / (1u64 << 53) as f64 * range
+ };
+ let mut items: Vec = Vec::new();
+ let mut columns = ItemColumns::default();
+ let mut next_id = 0;
+ let mut skipped = 0;
+ for round in 0..3000 {
+ // Items come and go as hoppers take them and crafters drop them.
+ match round % 5 {
+ 0 | 1 => {
+ next_id += 1;
+ // On edges too: a quarter of them sit on a block line.
+ let snap = |v: f64, edge: bool| if edge { v.floor() + 0.125 } else { v };
+ let edge = round % 4 == 0;
+ items.push(item(
+ next_id,
+ snap(next(24.0) - 12.0, edge),
+ 64.0,
+ snap(next(24.0) - 12.0, edge),
+ ));
+ }
+ 2 if !items.is_empty() => {
+ let i = next(items.len() as f64) as usize;
+ items.remove(i);
+ }
+ _ => {}
+ }
+ let hopper = (next(26.0) as i32 - 13, 63, next(26.0) as i32 - 13);
+ let reach = columns.may_reach(&items, hopper.0, hopper.2);
+ let found = scan(&items, hopper);
+ assert!(
+ reach || !found,
+ "round {round}: skipped a hopper with an item over it"
+ );
+ skipped += usize::from(!reach);
+ }
+ assert!(skipped > 1000, "skipped only {skipped}");
+ }
+}
diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs
index 855ef941a..bc2534659 100644
--- a/crates/horizon-client/src/game/maps.rs
+++ b/crates/horizon-client/src/game/maps.rs
@@ -275,6 +275,37 @@ impl Game<'_> {
}
self.maps.data.get_mut(&id)
}
+ /// `ClientboundMapItemDataPacket.handle`: the server's colours for a map
+ /// this client does not own (lobby map art, a framed map on a wall).
+ pub(super) fn remote_map_item_data(
+ &mut self,
+ p: &horizon_protocol::packets::play::MapItemData,
+ ) {
+ let dimension = self.dimension_id();
+ let map = self
+ .maps
+ .data
+ .entry(p.map_id)
+ .or_insert_with(|| MapData::fresh(0.0, 0.0, p.scale.max(0) as u8, dimension));
+ map.locked = p.locked;
+ let Some(patch) = &p.patch else {
+ map.dirty = false;
+ return;
+ };
+ for x in 0..patch.width {
+ for y in 0..patch.height {
+ let Some(&color) = patch.colors.get((x + y * patch.width) as usize) else {
+ continue;
+ };
+ let (px, py) = (patch.start_x + x, patch.start_y + y);
+ if (0..128).contains(&px) && (0..128).contains(&py) {
+ map.update_color(px, py, color);
+ }
+ }
+ }
+ // The server owns a remote map: only the texture has to change.
+ map.dirty = false;
+ }
fn next_map_id(&mut self) -> i32 {
let last = *self.maps.last_id.get_or_insert_with(|| {
horizon_client::save::read_dat(&self.world_root.join("data/minecraft/maps/last_id.dat"))
diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs
index 367dc6aaf..756202530 100644
--- a/crates/horizon-client/src/game/minecarts.rs
+++ b/crates/horizon-client/src/game/minecarts.rs
@@ -775,10 +775,13 @@ impl Game<'_> {
self.push_carts();
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
+ // A server player's minecart moves with its rider (lan_vehicles.rs).
+ let ridden = self.guest_vehicles();
let mut i = 0;
while i < self.carts.len() {
let p = self.carts[i].position;
if Some(self.carts[i].id) == self.riding
+ || ridden.contains(&self.carts[i].id)
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
{
i += 1;
@@ -986,7 +989,7 @@ impl Game<'_> {
let held = self.held().cloned();
match self.carts[i].kind {
CartKind::Rideable => {
- if sneaking || self.riding.is_some() {
+ if sneaking || self.riding.is_some() || self.ridden_by_guest(self.carts[i].id) {
return false;
}
self.riding = Some(self.carts[i].id);
diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs
index 707b9df96..be829f1bb 100644
--- a/crates/horizon-client/src/game/names.rs
+++ b/crates/horizon-client/src/game/names.rs
@@ -124,7 +124,7 @@ impl Game<'_> {
team,
viewer,
self.spectator(),
- m.has_effect("minecraft:invisibility"),
+ m.invisible || m.has_effect("minecraft:invisibility"),
);
// Entity.isDiscrete: a crouching player.
let discrete = player && m.extra.crouching;
@@ -144,9 +144,16 @@ impl Game<'_> {
continue;
}
// getDisplayName: the name in the team's prefix, suffix and colour.
+ let member = if player {
+ Text::literal(&name)
+ } else {
+ m.custom_name_text
+ .clone()
+ .unwrap_or_else(|| Text::literal(&name))
+ };
let shown = match team {
- Some(t) => t.formatted_name(Text::literal(&name)),
- None => Text::literal(&name),
+ Some(t) => t.formatted_name(member),
+ None => member,
};
let mut lines = Vec::new();
// EntityRenderer.extractNameTags: the score shows within the
@@ -171,6 +178,64 @@ impl Game<'_> {
discrete,
});
}
+ // Armor stands name themselves: an invisible one with a visible name
+ // is a hologram (its model is skipped, its name tag is not).
+ for a in &self.armor_stands {
+ let Some(name) = &a.custom_name else {
+ continue;
+ };
+ if !a.name_visible {
+ continue;
+ }
+ let height = match (a.marker, a.small) {
+ (true, _) => 0.0,
+ (false, true) => 0.9875,
+ (false, false) => 1.975,
+ };
+ let distance_sqr =
+ glam::DVec3::new(a.position.x, a.position.y, a.position.z).distance_squared(camera);
+ if distance_sqr >= 64.0 * 64.0 {
+ continue;
+ }
+ let team = self.mob_team(a.id);
+ let invisible = sb::invisible_to(team, viewer, self.spectator(), false);
+ let view = sb::NameView {
+ discrete: false,
+ distance_sqr,
+ invisible_to_viewer: invisible,
+ hud_hidden: self.ui.hide_gui,
+ is_camera: false,
+ is_vehicle: false,
+ };
+ if !sb::name_shown(team, viewer, view) {
+ continue;
+ }
+ let shown = match team {
+ Some(t) => t.formatted_name(name.clone()),
+ None => name.clone(),
+ };
+ let mut lines = Vec::new();
+ let mut lift = 0.0;
+ let holder = self.persist.uuids.get(&a.id).map(|u| uuid_text(*u));
+ if distance_sqr < 10.0 * 10.0
+ && let Some(score) = holder.and_then(|h| self.below_name_text(&h))
+ {
+ lines.push((score, 0.0));
+ lift = f64::from(9.0f32 * 1.15 * 0.025);
+ }
+ lines.push((shown, lift));
+ let l = self.world.light(
+ a.position.x.floor() as i32,
+ (a.position.y + height).floor() as i32,
+ a.position.z.floor() as i32,
+ );
+ tags.push(NameTag {
+ at: glam::DVec3::new(a.position.x, a.position.y + height + 0.5, a.position.z),
+ lines,
+ light: l,
+ discrete: false,
+ });
+ }
tags
}
/// `SubmitNodeCollection.submitNameTag`: a discrete name is drawn once,
diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs
index 68aabbbc6..6dda8e0ac 100644
--- a/crates/horizon-client/src/game/natural_spawning.rs
+++ b/crates/horizon-client/src/game/natural_spawning.rs
@@ -9,6 +9,7 @@ use horizon_client::{
mobs::{
Mob, MobWorld, Species,
data::{self, MobData},
+ seen_grid::SeenGrid,
spawn_rules::{Dimension, SpawnLevel},
spawn_selection::{
self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest,
@@ -75,8 +76,72 @@ pub(super) struct GameLevel<'g, 'a> {
pub(super) pending: std::cell::RefCell>,
/// The types and boxes of what a spawner created this tick.
pub(super) pending_ids: std::cell::RefCell>,
+ /// The game's mobs by box, built once a pass has asked more than
+ /// [`SCANNED_QUERIES`] box queries (the mobs do not change while it
+ /// holds the game); the first ones scan, as the build costs a few scans.
+ pub(super) boxes: std::cell::OnceCell,
+ pub(super) box_queries: std::cell::Cell,
+}
+const SCANNED_QUERIES: u32 = 8;
+/// A mob not removed: its index in `Game::mobs`, box, alive, and whether
+/// it is a living shulker.
+type MobBox = (usize, Aabb, bool, bool);
+fn mob_box(i: usize, m: &Mob) -> MobBox {
+ let alive = m.alive();
+ (
+ i,
+ m.bounds(),
+ alive,
+ alive && m.species() == Species::Shulker,
+ )
+}
+/// The boxes of the game's mobs not removed, and a grid over them.
+pub(super) struct MobBoxes {
+ entries: Vec,
+ grid: SeenGrid,
+}
+impl MobBoxes {
+ fn new(mobs: &[Mob]) -> Self {
+ let entries: Vec<_> = mobs
+ .iter()
+ .enumerate()
+ .filter(|(_, m)| !m.removed)
+ .map(|(i, m)| mob_box(i, m))
+ .collect();
+ let grid = SeenGrid::new(entries.iter().map(|e| e.1));
+ Self { entries, grid }
+ }
+ /// The entries whose boxes meet `area` (and possibly a few more).
+ fn near(&self, area: Aabb) -> impl Iterator- + '_ {
+ let mut near = Vec::new();
+ let indexed = self.grid.candidates(area, &mut near);
+ let all = (!indexed).then(|| self.entries.iter());
+ near.into_iter()
+ .map(|i| self.entries[i as usize])
+ .chain(all.into_iter().flatten().copied())
+ }
}
impl GameLevel<'_, '_> {
+ /// The mobs not removed whose boxes may meet `area` (callers test them).
+ fn mobs_near(&self, area: Aabb) -> Box
+ '_> {
+ let asked = self.box_queries.get() + 1;
+ self.box_queries.set(asked);
+ if asked <= SCANNED_QUERIES && self.boxes.get().is_none() {
+ return Box::new(
+ self.game
+ .mobs
+ .iter()
+ .enumerate()
+ .filter(|(_, m)| !m.removed)
+ .map(|(i, m)| mob_box(i, m)),
+ );
+ }
+ Box::new(
+ self.boxes
+ .get_or_init(|| MobBoxes::new(&self.game.mobs))
+ .near(area),
+ )
+ }
fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> {
let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?;
Some(self.game.res.biomes().get(chunk.biome(x, y, z)))
@@ -224,12 +289,9 @@ impl NaturalLevel for GameLevel<'_, '_> {
// 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
+ .mobs_near(grown)
+ .any(|(_, b, _, shulker)| shulker && b.intersects(grown))
&& !self
.pending_ids
.borrow()
@@ -244,10 +306,8 @@ impl NaturalLevel for GameLevel<'_, '_> {
!player
&& !self.pending.borrow().iter().any(|b| b.intersects(bounds))
&& !self
- .game
- .mobs
- .iter()
- .any(|m| m.alive() && !m.removed && m.bounds().intersects(bounds))
+ .mobs_near(bounds)
+ .any(|(_, b, alive, _)| alive && b.intersects(bounds))
}
fn spawn_mobs(&self) -> bool {
self.game.ui.rules.bool("spawn_mobs")
@@ -289,10 +349,8 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> {
}
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))
+ .mobs_near(bounds)
+ .filter(|&(i, b, ..)| self.game.mobs[i].kind.id == id && b.intersects(bounds))
.count();
let pending = self
.pending_ids
@@ -311,6 +369,8 @@ impl<'a> Game<'a> {
players: self.level_players(),
pending: Default::default(),
pending_ids: Default::default(),
+ boxes: Default::default(),
+ box_queries: Default::default(),
}
}
/// Creates a mob the spawner accepted, finalized the game's way; the
diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs
index 257586572..32acdd256 100644
--- a/crates/horizon-client/src/game/pad_menu.rs
+++ b/crates/horizon-client/src/game/pad_menu.rs
@@ -113,7 +113,7 @@ impl Game<'_> {
}
/// Where focus can land: buttons drawn last frame, every registered
- /// target (sliders, fields, rows, Horizon-style widgets), and the slots
+ /// target (sliders, fields, rows, keyboard keys), and the slots
/// and tabs of inventories (GUI pixels), on screen.
fn pad_targets(&self) -> Vec {
let mut targets = self.pad_all_targets();
@@ -137,7 +137,7 @@ impl Game<'_> {
})
.collect();
for t in widgets::last_targets() {
- // A Horizon button is both a labelled button and a target.
+ // A button can be both a labelled button and a target.
if let Some(same) = targets.iter_mut().find(|o| o.rect == t.rect) {
same.kind = t.kind;
} else {
@@ -1026,45 +1026,13 @@ impl Game<'_> {
}
}
- /// The focus highlight. Classic screens look as vanilla's keyboard focus
- /// does: buttons, sliders and slots already draw their highlighted
- /// sprite under the (hidden) pointer, and list rows and fields get
- /// vanilla's white one-pixel outline (`AbstractSelectionList`'s focused
- /// selection, `EditBox`'s highlighted border). Horizon-style screens get
- /// the design system's focus colour: a two-dp accent ring.
+ /// The focus highlight, as vanilla's keyboard focus looks: buttons,
+ /// sliders and slots already draw their highlighted sprite under the
+ /// (hidden) pointer, and list rows and fields get vanilla's white
+ /// one-pixel outline (`AbstractSelectionList`'s focused selection,
+ /// `EditBox`'s highlighted border).
fn draw_pad_focus(&self, batch: &mut HudBatch, focus: Target) {
let [x, y, w, h] = focus.rect;
- // The options' sub-pages keep the classic layout under either style.
- let horizon = horizon_client::ui_theme::horizon()
- && if self.screen == Screen::Options {
- self.ui.options.page() == Page::Main
- } else {
- self.title.is_some() || self.screen == Screen::Paused
- };
- if horizon {
- use horizon_client::ui_theme::{self as theme, Ui, color};
- let mut ui = Ui::new(&self.gui.atlas, batch, self.cursor);
- let k = ui.batch.scale / ui.density;
- let (x, y, w, h) = (x * k, y * k, w * k, h * k);
- let radius = match focus.kind {
- Kind::Button | Kind::Tab(_) | Kind::Slider { .. } => (h + 6.0) / 2.0,
- Kind::Field => theme::RADIUS + 3.0,
- _ => theme::RADIUS_PLATE + 3.0,
- };
- for inset in [0.0, 1.0] {
- let o = 3.0 - inset;
- ui.border(
- x - o,
- y - o,
- w + 2.0 * o,
- h + 2.0 * o,
- radius - inset,
- color::ACCENT,
- );
- }
- ui.finish();
- return;
- }
if matches!(focus.kind, Kind::Row | Kind::Field) {
let atlas = &self.gui.atlas;
let white = rgba(255, 255, 255, 255);
diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs
index 6280959d8..bcf9e6ab5 100644
--- a/crates/horizon-client/src/game/piglins.rs
+++ b/crates/horizon-client/src/game/piglins.rs
@@ -34,6 +34,9 @@ impl Game<'_> {
if !self.ui.rules.bool("mob_griefing") {
return;
}
+ // Whether each item is piglin-loved, kept until an item is added or
+ // removed (added ones are pushed at the end under a new id).
+ let mut loved: (Option<(usize, Option)>, Vec) = (None, Vec::new());
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Piglin
@@ -46,11 +49,20 @@ impl Game<'_> {
continue;
}
let pos = m.position;
+ let key = (self.dropped.len(), self.dropped.last().map(|e| e.id));
+ if loved.0 != Some(key) {
+ loved.0 = Some(key);
+ loved.1 = self
+ .dropped
+ .iter()
+ .map(|e| self.piglin_loved(&e.stack.item))
+ .collect();
+ }
let best = self
.dropped
.iter()
.enumerate()
- .filter(|(_, e)| self.piglin_loved(&e.stack.item))
+ .filter(|&(j, _)| loved.1[j])
.map(|(j, e)| (j, e.position.distance_squared(pos)))
.filter(|(_, d)| *d <= 81.0)
.min_by(|a, b| a.1.total_cmp(&b.1));
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index 7c96e7bad..c482d9728 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -7,7 +7,7 @@
//! client predicts its own movement; the server stays authoritative for
//! everything else.
use super::{Dim, Game, Mining, Screen};
-use horizon_client::first_person::Hand;
+use horizon_client::first_person::{Hand, SwingAnimation};
use horizon_client::{
Result,
chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy},
@@ -93,7 +93,7 @@ pub(super) struct Remote {
pub(super) registries: Arc,
joined: bool,
status: String,
- entity_id: i32,
+ pub(super) entity_id: i32,
dimension: DimensionType,
biome_map: Vec,
biome_bits: u8,
@@ -140,6 +140,8 @@ pub(super) struct Remote {
tab_players: HashMap,
/// Each listed profile's unpacked `textures` property.
skin_textures: HashMap,
+ /// The skin texture each profile's players show, once its download is ready.
+ skins: HashMap,
listed: std::collections::HashSet,
/// `ClientboundLoginPacket.onlineMode`: the player list shows heads.
online_mode: bool,
@@ -194,6 +196,30 @@ fn face_direction(face: [i32; 3]) -> u8 {
}
}
+/// A `minecraft:profile` component as the item data JSON the model reads.
+fn profile_tag(p: &horizon_protocol::item::Profile) -> Tag {
+ let properties = p
+ .properties
+ .iter()
+ .map(|(name, value, signature)| {
+ let mut entries: Vec<(&'static str, Tag)> = vec![
+ ("name", Tag::String(name.as_str().into())),
+ ("value", Tag::String(value.as_str().into())),
+ ];
+ if let Some(signature) = signature {
+ entries.push(("signature", Tag::String(signature.as_str().into())));
+ }
+ Tag::compound(entries)
+ })
+ .collect::>();
+ let mut entries: Vec<(&'static str, Tag)> = Vec::new();
+ if let Some(name) = &p.name {
+ entries.push(("name", Tag::String(name.as_str().into())));
+ }
+ entries.push(("properties", Tag::List(properties)));
+ Tag::compound(entries)
+}
+
/// A protocol number format as the scoreboard's.
fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFormat {
use horizon_client::scoreboard::{NumberFormat, tag_to_json};
@@ -306,6 +332,11 @@ impl Game<'_> {
progress: 0.0,
total: 0,
};
+ // The connected client never opens a server world (single player also
+ // joins here), so load the registries its argument parsers and local
+ // suggestions need before receiving the server's command tree.
+ self.ui.registries = Default::default();
+ self.build_registries();
self.ui.registries.permission = 0;
self.ui.chat.clear();
self.screen = Screen::Playing;
@@ -355,6 +386,7 @@ impl Game<'_> {
players: HashMap::new(),
tab_players: HashMap::new(),
skin_textures: HashMap::new(),
+ skins: HashMap::new(),
listed: Default::default(),
online_mode: false,
level_players: HashMap::new(),
@@ -515,66 +547,118 @@ impl Game<'_> {
let mut out = ItemStack {
item: self.item_name(s.item),
count: s.count.max(0) as u32,
- damage: s.damage().max(0) as u32,
+ damage: 0,
extra: None,
};
- use horizon_protocol::item::{Component, component};
- if let Some(Component::Int(rgb)) = s.component(component::DYED_COLOR) {
- out.data_mut().dyed_color = Some(*rgb);
- }
- if let Some(Component::Int(id)) = s.component(component::MAP_ID) {
- out.data_mut().map_id = Some(*id);
- }
- if let Some(Component::Int(cost)) = s.component(component::REPAIR_COST) {
- out.data_mut().repair_cost = (*cost).max(0) as u32;
- }
- if let Some(Component::Int(mode)) = s.component(component::MAP_POST_PROCESSING) {
- out.data_mut().map_post_processing = Some((*mode).clamp(0, 1) as u8);
- }
- if let Some(Component::WritableBook(pages)) = s.component(component::WRITABLE_BOOK_CONTENT)
- {
- out.data_mut().writable_pages = pages.clone();
- }
- if let Some(Component::WrittenBook(b)) = s.component(component::WRITTEN_BOOK_CONTENT) {
- let lang = self
- .remote
- .as_ref()
- .map(|r| r.lang.clone())
- .unwrap_or_default();
- out.data_mut().written = Some(horizon_client::item_data::WrittenBook {
- title: b.title.clone(),
- author: b.author.clone(),
- generation: b.generation.clamp(0, 3) as u8,
- pages: b.pages.iter().map(|p| plain(p, &lang)).collect(),
- });
- }
- if let Some(Component::Text(name)) = s.component(component::CUSTOM_NAME) {
- let lang = self
- .remote
- .as_ref()
- .map(|r| r.lang.clone())
- .unwrap_or_default();
- out.data_mut().custom_name = Some(plain(name, &lang));
- }
- // The enchantments by the server's registry ids.
- let levels = |list: &[(i32, i32)]| -> Vec<(Arc, u32)> {
- let names = self.remote.as_ref().map(|r| &r.registries);
- list.iter()
- .filter_map(|(id, level)| {
- let name = names?.name("minecraft:enchantment", *id)?;
- Some((Arc::from(name), (*level).max(0) as u32))
- })
- .collect()
- };
- if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) {
- out.data_mut().enchantments = levels(list);
- }
- if let Some(Component::Enchantments(list)) = s.component(component::STORED_ENCHANTMENTS) {
- out.data_mut().stored_enchantments = levels(list);
+ // A vanilla `components` compound, then the same decoder the saved
+ // and command item NBT use, so tooltips and models see every field.
+ let components = self.protocol_components(s);
+ let (damage, data) = horizon_client::item_data::decode_components(components.as_ref());
+ out.damage = damage;
+ if let Some(data) = data {
+ *out.data_mut() = *data;
}
out.tidy();
Some(out)
}
+ /// The item's patched components as vanilla's `components` compound.
+ fn protocol_components(&self, s: &Stack) -> Option {
+ use horizon_protocol::item::{Component, component};
+ let r = self.remote.as_ref()?;
+ let name = |id: i32| r.builtin.get("minecraft:data_component_type")?.name(id);
+ let mut entries: Vec<(&str, Tag)> = Vec::new();
+ for (kind, c) in &s.added {
+ let Some(key) = name(*kind) else {
+ continue;
+ };
+ let value = match c {
+ Component::Int(v) if *kind == component::RARITY => {
+ let rarity = ["common", "uncommon", "rare", "epic"];
+ Tag::String(rarity.get(*v as usize).copied().unwrap_or("common").into())
+ }
+ Component::Int(v) => Tag::Int(*v),
+ Component::Unit => Tag::Compound(Default::default()),
+ Component::Bool(v) => Tag::Byte(i8::from(*v)),
+ Component::Text(t) | Component::Nbt(t) => t.clone(),
+ Component::Ident(v) => Tag::String(v.as_str().into()),
+ Component::Lore(lines) => Tag::List(lines.clone()),
+ Component::WritableBook(pages) => Tag::compound([(
+ "pages",
+ Tag::List(
+ pages
+ .iter()
+ .map(|p| Tag::String(p.as_str().into()))
+ .collect(),
+ ),
+ )]),
+ Component::WrittenBook(b) => Tag::compound([
+ ("title", Tag::String(b.title.as_str().into())),
+ ("author", Tag::String(b.author.as_str().into())),
+ ("generation", Tag::Int(b.generation)),
+ ("pages", Tag::List(b.pages.clone())),
+ ("resolved", Tag::Byte(i8::from(b.resolved))),
+ ]),
+ Component::Enchantments(list) => {
+ // Enchantments are a synced (data-driven) registry: the
+ // ids index the server's RegistryData, not the builtin
+ // report, so a datapack enchantment names correctly.
+ let levels = list.iter().filter_map(|(id, level)| {
+ let name = r.registries.name("minecraft:enchantment", *id)?;
+ Some((name, Tag::Int(*level)))
+ });
+ Tag::compound(levels)
+ }
+ Component::AttackRange(v) => Tag::compound([
+ ("min_reach", Tag::Float(v[0].to_bits())),
+ ("max_reach", Tag::Float(v[1].to_bits())),
+ ("min_attack_momentum", Tag::Float(v[2].to_bits())),
+ ("max_attack_momentum", Tag::Float(v[3].to_bits())),
+ ("hitbox_margin", Tag::Float(v[4].to_bits())),
+ ("mob_factor", Tag::Float(v[5].to_bits())),
+ ]),
+ Component::Profile(p) => profile_tag(p),
+ Component::CustomModelData {
+ floats,
+ flags,
+ strings,
+ colors,
+ } => Tag::compound([
+ (
+ "floats",
+ Tag::List(floats.iter().map(|f| Tag::Float(f.to_bits())).collect()),
+ ),
+ (
+ "flags",
+ Tag::List(flags.iter().map(|b| Tag::Byte(i8::from(*b))).collect()),
+ ),
+ (
+ "strings",
+ Tag::List(
+ strings
+ .iter()
+ .map(|s| Tag::String(s.as_str().into()))
+ .collect(),
+ ),
+ ),
+ (
+ "colors",
+ Tag::List(colors.iter().map(|c| Tag::Int(*c)).collect()),
+ ),
+ ]),
+ Component::TooltipDisplay { hide, hidden } => {
+ let hidden = hidden
+ .iter()
+ .filter_map(|id| Some(Tag::String(name(*id)?.into())));
+ Tag::compound([
+ ("hide_tooltip", Tag::Byte(i8::from(*hide))),
+ ("hidden_components", Tag::List(hidden.collect())),
+ ])
+ }
+ };
+ entries.push((key, value));
+ }
+ Some(Tag::compound(entries))
+ }
fn to_network(&self, s: &Option) -> Option {
let s = s.as_ref()?;
let mut stack = Stack::new(self.item_id(&s.item), s.count as i32);
@@ -1283,6 +1367,10 @@ impl Game<'_> {
self.turn_remote_projectile(id, rotation);
}
fn remove_entity(&mut self, id: i32) {
+ // The vehicle the player rode is gone (Entity.removeVehicle).
+ if self.riding == Some(id as u32) {
+ self.riding = None;
+ }
self.mobs.retain(|m| m.id != id as u32);
self.orbs.retain(|o| o.id != id as u32);
self.dropped.retain(|d| d.id != id as u32);
@@ -1669,6 +1757,8 @@ impl Game<'_> {
];
self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground);
}
+ C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers),
+ C::MoveVehicle(p) => self.remote_move_vehicle(p.position, p.yaw),
// ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3).
C::RotateHead(p) => {
if let Some(r) = self.remote.as_mut() {
@@ -1677,6 +1767,29 @@ impl Game<'_> {
}
}
C::SetEntityData(p) => {
+ // Entity.DATA_SHARED_FLAGS_ID, DATA_CUSTOM_NAME and
+ // DATA_CUSTOM_NAME_VISIBLE: server NPCs and holograms rely on
+ // these instead of saved NBT.
+ if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
+ for (index, _, value) in &p.values {
+ match (index, value) {
+ (0, Value::Byte(flags)) => m.invisible = flags & 0x20 != 0,
+ (2, Value::OptText(name)) => {
+ let text = name.as_ref().map(horizon_client::entity_nbt::name_text);
+ m.custom_name =
+ text.as_ref().map(horizon_client::text::Text::plain);
+ m.custom_name_text = text;
+ }
+ (2, Value::Text(name)) => {
+ let text = horizon_client::entity_nbt::name_text(name);
+ m.custom_name = Some(text.plain());
+ m.custom_name_text = Some(text);
+ }
+ (3, Value::Bool(visible)) => m.name_visible = *visible,
+ _ => {}
+ }
+ }
+ }
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Rabbit
{
@@ -2314,6 +2427,7 @@ impl Game<'_> {
.then(|| Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5));
}
C::ServerData(p) => self.remote_server_data(p.icon.as_deref()),
+ C::MapItemData(p) => self.remote_map_item_data(&p),
// handleTickingState / handleTickingStep: the level's TickRateManager.
C::TickingState(p) => {
self.clock.set_rate(p.rate);
@@ -2459,33 +2573,20 @@ impl Game<'_> {
pub(super) fn remote_tab_players(
&mut self,
) -> Option<(Vec, bool, Vec)> {
- let r = self.remote.as_ref()?;
- let mut players: Vec<_> = r
- .listed
- .iter()
- .filter_map(|u| r.tab_players.get(u).cloned())
- .collect();
+ self.update_remote_skins();
+ let mut players: Vec<_> = {
+ let r = self.remote.as_ref()?;
+ r.listed
+ .iter()
+ .filter_map(|u| r.tab_players.get(u).cloned())
+ .collect()
+ };
for p in &mut players {
- let Some(textures) = r.skin_textures.get(&p.uuid) else {
- continue;
- };
- // PlayerInfo.createSkinLookup: only the local player's own skin
- // may be unsigned.
- let downloads = &mut self.skin_downloads;
- let skin = horizon_client::skins::lookup(textures, p.uuid != r.profile, |kind, url| {
- downloads.state(kind, url)
- });
- if let Some(skin) = skin {
- p.skin = skin;
- }
- }
- for (location, rgba) in self.skin_downloads.take_ready() {
- self.store_skin(location, rgba);
- }
- for p in &mut players {
- if p.skin.starts_with("skins/") && !self.show_skin(&p.skin) {
- p.skin = horizon_client::tab_list::default_skin(p.uuid).to_owned();
- }
+ p.skin = self
+ .remote
+ .as_ref()
+ .and_then(|r| r.skins.get(&p.uuid).cloned())
+ .unwrap_or_else(|| horizon_client::tab_list::default_skin(p.uuid).to_owned());
}
let r = self.remote.as_ref()?;
let upside_down = players
@@ -2498,9 +2599,68 @@ impl Game<'_> {
.collect();
Some((players, r.online_mode, upside_down))
}
+ /// `PlayerInfo.getSkin` for every player entity, including NPCs that are
+ /// never in the tab list: resolve each profile's textures and give the
+ /// level's player models their skin.
+ fn update_remote_skins(&mut self) {
+ let Some(r) = self.remote.as_ref() else {
+ return;
+ };
+ let local = r.profile;
+ let entries: Vec<(u128, horizon_client::skins::Textures)> = r
+ .skin_textures
+ .iter()
+ .map(|(uuid, textures)| (*uuid, textures.clone()))
+ .collect();
+ let mut resolved: Vec<(u128, String)> = Vec::new();
+ for (uuid, textures) in entries {
+ // PlayerInfo.createSkinLookup: only the local player's own skin
+ // may be unsigned.
+ let skin = {
+ let mut downloads = self.skin_downloads.borrow_mut();
+ horizon_client::skins::lookup(&textures, uuid != local, |kind, url| {
+ downloads.state(kind, url)
+ })
+ };
+ if let Some(skin) = skin {
+ resolved.push((uuid, skin));
+ }
+ }
+ resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.show_skin(skin));
+ let Some((level, skins, own)) = self.remote.as_mut().map(|r| {
+ r.skins = resolved.into_iter().collect();
+ (
+ r.level_players
+ .iter()
+ .map(|(id, uuid)| (*id as u32, *uuid))
+ .collect::>(),
+ r.skins.clone(),
+ r.skins.get(&r.profile).cloned(),
+ )
+ }) else {
+ return;
+ };
+ for (id, uuid) in level {
+ let Some(skin) = skins.get(&uuid) else {
+ continue;
+ };
+ if let Some(mob) = self
+ .mobs
+ .iter_mut()
+ .find(|m| m.id == id && &*m.kind.id == "minecraft:player")
+ {
+ mob.skin = Some(skin.clone());
+ }
+ }
+ if let Some(skin) = own
+ && let Some(mob) = self.player_model.as_mut()
+ {
+ mob.skin = Some(skin);
+ }
+ }
/// Puts a downloaded skin in an atlas skin slot: a free one, else the
/// least recently shown.
- fn store_skin(&mut self, location: String, rgba: Vec) {
+ pub(super) fn store_skin(&mut self, location: String, rgba: Vec) {
use horizon_client::hud::SKIN_SLOTS;
let slot = if self.skin_slots.len() < SKIN_SLOTS {
self.skin_slots.len()
@@ -2778,9 +2938,9 @@ impl Game<'_> {
self.capture_loaded_world();
}
let stick = self.pad_move();
- let Some(player) = self.player.as_mut() else {
+ if self.player.is_none() {
return Ok(());
- };
+ }
let playing = self.screen == Screen::Playing;
let held = |k| playing && self.keys.contains(&k);
let keys = Keys {
@@ -2801,7 +2961,14 @@ impl Game<'_> {
| u8::from(keys.jump) << 4
| u8::from(keys.shift) << 5
| u8::from(keys.sprint) << 6;
- self.previous_position = player.position;
+ // A passenger moves with its vehicle (Entity.rideTick), not by itself.
+ let riding = self.screen != Screen::Dead && self.remote_ride(keys);
+ let Some(player) = self.player.as_mut() else {
+ return Ok(());
+ };
+ if !riding {
+ self.previous_position = player.position;
+ }
let before = (
player.ground.on_ground,
[player.velocity.x, player.velocity.y, player.velocity.z],
@@ -2818,7 +2985,7 @@ impl Game<'_> {
f64::from(head[2]) + 0.5,
);
player.velocity = Vec3::ZERO;
- } else if !dead {
+ } else if !dead && !riding {
player.velocity = player.velocity.add_vector(pushed);
MotionWorld {
entities: &ghast_collisions,
@@ -3104,6 +3271,9 @@ impl Game<'_> {
};
self.tick_remote_objects(&mut step);
self.tick_remote_projectiles(&mut step);
+ // LightningBolt.tick on a client, and the sky flash fading.
+ self.flash = self.flash.saturating_sub(1);
+ self.tick_bolts();
}
lerps.retain(|_, l| l.steps > 0);
if let Some(r) = self.remote.as_mut() {
@@ -3165,6 +3335,8 @@ impl Game<'_> {
p.sprinting,
);
let (yaw, pitch, selected) = (self.yaw, self.pitch, self.selected);
+ let riding = self.riding.is_some();
+ let vehicle = self.remote_vehicle_packets();
let Some(r) = self.remote.as_mut() else {
return;
};
@@ -3187,9 +3359,18 @@ impl Game<'_> {
data: 0,
}));
}
- if let Some(packet) = r
- .position_sender
- .update(pos, (yaw, pitch), on_ground, collision)
+ if riding {
+ // LocalPlayer.tick: a passenger sends its look, then the vehicle
+ // it controls.
+ out.push(S::MovePlayerRot(play::MovePlayerRot {
+ yaw,
+ pitch,
+ flags: u8::from(on_ground) | u8::from(collision) << 1,
+ }));
+ out.extend(vehicle);
+ } else if let Some(packet) =
+ r.position_sender
+ .update(pos, (yaw, pitch), on_ground, collision)
{
out.push(packet);
}
@@ -3309,10 +3490,8 @@ impl Game<'_> {
sequence: seq,
}));
if progress >= 1.0 {
+ // startDestroyBlock: instant survival breaks have no destroy delay.
self.predict_break(hit.pos, state, seq);
- if let Some(r) = self.remote.as_mut() {
- r.destroy_delay = 5;
- }
return;
}
if let Some(r) = self.remote.as_mut() {
@@ -3422,6 +3601,21 @@ impl Game<'_> {
fn remote_use_entity(&mut self) -> bool {
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
+ // A boat, minecart, item frame, armor stand or painting nearer than
+ // any mob: the server uses it (AbstractBoat.interact boards it).
+ if let Some(hit) = self.remote_object_hit()
+ && self.mob_hit().is_none_or(|(_, d)| hit.distance < d)
+ && self.before_block(hit.distance)
+ {
+ self.send(S::Interact(play::Interact {
+ id: hit.id,
+ hand: 0,
+ location: hit.location,
+ secondary: sneaking,
+ }));
+ self.swing_arm();
+ return true;
+ }
if let Some((i, distance)) = self.mob_hit()
&& self.before_block(distance)
{
@@ -3489,7 +3683,15 @@ impl Game<'_> {
self.predict_use(&changes, seq);
}
if held_block {
- self.with_hand(hand, Game::swing_arm);
+ if reacts
+ || held
+ .as_ref()
+ .is_some_and(|stack| self.remote_can_place(&hit, stack))
+ {
+ self.with_hand(hand, Game::swing_arm);
+ }
+ // BlockItem.place returns FAIL when placement is rejected:
+ // stop this click without trying the item or the other hand.
return true;
}
return reacts;
@@ -3547,7 +3749,11 @@ impl Game<'_> {
/// container, and the blocks it changed. Vanilla's client runs it on its
/// own level first; this runs it on a copy, and `predict_use` keeps the
/// changes it predicts.
- fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) {
+ fn remote_block_reacts(
+ &mut self,
+ hit: &super::Hit,
+ held: Option<&ItemStack>,
+ ) -> (bool, DryUse) {
// Player.isSecondaryUseActive with something in either hand.
let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some();
if self.keys.contains(&KeyCode::ShiftLeft) && hands_full {
@@ -3562,26 +3768,53 @@ impl Game<'_> {
[-1, 0, 0] => Direction::West,
_ => Direction::East,
};
- let mut level = DryLevel {
- world: &self.world,
- changed: HashMap::new(),
- random: horizon_core::random::LegacyRandom::new(0),
- sounds: Vec::new(),
+ let player = self.use_context();
+ self.with_level(|b, level, _| {
+ let mut level = DryLevel::new(level);
+ let reacts = b
+ .use_item_on(
+ &mut level,
+ &mut horizon_world::level::Ticks::default(),
+ horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
+ face,
+ horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
+ player,
+ held.map(|s| &*s.item),
+ )
+ .consumes_action();
+ (reacts, (level.changed.into_iter().collect(), level.sounds))
+ })
+ }
+
+ /// Run BlockItem.place on a disposable level before predicting its swing.
+ /// The real level supplies collision shapes and building-blocking entities;
+ /// block writes, random draws, scheduled ticks and events stay in the preview.
+ fn remote_can_place(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool {
+ if !self.may_build() {
+ return false;
+ }
+ let ctx = horizon_world::level::PlaceContext {
+ clicked_pos: horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
+ face: horizon_core::geometry::Direction::ALL[face_direction(hit.face) as usize],
+ hit: Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
+ inside: hit.face == [0; 3],
+ yaw: self.yaw,
+ pitch: self.pitch,
+ sneaking: self.keys.contains(&KeyCode::ShiftLeft),
+ item: stack.item.to_string(),
+ can_use_game_master_blocks: self.can_use_game_master_blocks(),
};
- let reacts = self
- .res
- .behaviours()
- .use_item_on(
- &mut level,
- &mut horizon_world::level::Ticks::default(),
- horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
- face,
- horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
- self.use_context(),
- held.map(|s| &*s.item),
+ self.with_level(|b, level, _| {
+ let mut level = DryLevel::new(level);
+ matches!(
+ b.place_block(
+ &mut level,
+ &mut horizon_world::level::Ticks::default(),
+ &ctx
+ ),
+ horizon_world::level::PlaceOutcome::Placed { .. }
)
- .consumes_action();
- (reacts, (level.changed.into_iter().collect(), level.sounds))
+ })
}
/// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether
@@ -3762,6 +3995,14 @@ impl Game<'_> {
id: self.creatures.projectiles[i].id as i32,
}));
self.reset_attack_strength();
+ } else if let Some(hit) = self.remote_object_hit()
+ && self.mob_hit().is_none_or(|(_, d)| hit.distance < d)
+ && self.before_block(hit.distance)
+ {
+ // VehicleEntity.hurtServer, ItemFrame and ArmorStand hurtServer,
+ // a painting broken: the server decides.
+ self.send(S::Attack(play::Attack { id: hit.id }));
+ self.reset_attack_strength();
} else if let Some((i, distance)) = self.mob_hit()
&& self.before_block(distance)
{
@@ -3836,23 +4077,26 @@ impl Game<'_> {
Ok(true)
}
KeyCode::KeyQ => {
+ if self.spectator() {
+ return Ok(true);
+ }
let all = self.keys.contains(&KeyCode::ControlLeft);
+ // MultiPlayerGameMode.dropItem: predict removal before sending
+ // the action, then swing only if a nonempty stack was removed.
+ let dropped = horizon_client::items::take_held_drop(
+ &mut self.inventory[self.selected],
+ all,
+ false,
+ );
self.send(S::PlayerAction(play::PlayerAction {
action: if all { 4 } else { 5 },
pos: [0; 3],
direction: 0,
sequence: 0,
}));
- // Inventory.removeFromSelected (prediction).
- let slot = &mut self.inventory[self.selected];
- if let Some(s) = slot {
- if all || s.count <= 1 {
- *slot = None;
- } else {
- s.count -= 1;
- }
+ if dropped.is_some() {
+ self.swing_hand(Hand::Main, SwingAnimation::DEFAULT);
}
- self.swing_arm();
Ok(true)
}
KeyCode::KeyE => {
@@ -4529,7 +4773,7 @@ pub(super) fn input_ordinal(input: Input) -> i32 {
/// The client's world for a guess at what a click does: reads go to the
/// world, writes stay here and are dropped.
struct DryLevel<'w> {
- world: &'w horizon_client::world::World,
+ base: &'w dyn horizon_world::level::LevelAccess,
changed: HashMap,
random: horizon_core::random::LegacyRandom,
/// The sounds the use plays (a door's creak).
@@ -4559,6 +4803,17 @@ pub(super) fn hand_operated(name: &str) -> bool {
|| name == "lever"
}
+impl<'w> DryLevel<'w> {
+ fn new(base: &'w dyn horizon_world::level::LevelAccess) -> Self {
+ Self {
+ base,
+ changed: HashMap::new(),
+ random: horizon_core::random::LegacyRandom::new(0),
+ sounds: Vec::new(),
+ }
+ }
+}
+
impl horizon_world::level::LevelAccess for DryLevel<'_> {
fn emit(&mut self, event: horizon_world::level::LevelEvent) {
if let horizon_world::level::LevelEvent::Sound {
@@ -4575,7 +4830,7 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> {
self.changed
.get(&pos)
.copied()
- .unwrap_or_else(|| self.world.block(pos.x, pos.y, pos.z))
+ .unwrap_or_else(|| self.base.block_state(pos))
}
fn set_raw(
&mut self,
@@ -4587,13 +4842,31 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> {
Some(previous)
}
fn is_loaded(&self, pos: horizon_core::position::BlockPos) -> bool {
- self.world.loaded(pos.x, pos.z)
+ self.base.is_loaded(pos)
+ }
+ fn min_y(&self) -> i32 {
+ self.base.min_y()
+ }
+ fn max_y(&self) -> i32 {
+ self.base.max_y()
+ }
+ fn block_light(&self, pos: horizon_core::position::BlockPos) -> i32 {
+ self.base.block_light(pos)
+ }
+ fn sky_light(&self, pos: horizon_core::position::BlockPos) -> i32 {
+ self.base.sky_light(pos)
+ }
+ fn sky_darken(&self) -> i32 {
+ self.base.sky_darken()
+ }
+ fn is_unobstructed(&self, pos: horizon_core::position::BlockPos, state: BlockStateId) -> bool {
+ self.base.is_unobstructed(pos, state)
}
fn random(&mut self) -> &mut horizon_core::random::LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
- self.world.game_time
+ self.base.game_time()
}
}
@@ -4709,6 +4982,110 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_
mod tests {
use super::Game;
+ #[test]
+ fn placement_preview_checks_obstruction_without_changing_the_level() {
+ use super::DryLevel;
+ use horizon_core::{position::BlockPos, random::LegacyRandom};
+ use horizon_world::{
+ level::{
+ Behaviours, LevelAccess, PlaceContext, PlaceOutcome, Ticks, data::load_registry,
+ },
+ registry::BlockStateId,
+ };
+
+ struct Level {
+ air: BlockStateId,
+ stone: BlockStateId,
+ obstructed: bool,
+ loaded: bool,
+ ceiling: i32,
+ }
+ impl LevelAccess for Level {
+ fn block_state(&self, pos: BlockPos) -> BlockStateId {
+ if pos == BlockPos::new(0, 0, 0) {
+ self.stone
+ } else {
+ self.air
+ }
+ }
+ fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option {
+ panic!("preview must not write to the live level");
+ }
+ fn is_loaded(&self, _: BlockPos) -> bool {
+ self.loaded
+ }
+ fn max_y(&self) -> i32 {
+ self.ceiling
+ }
+ fn is_unobstructed(&self, pos: BlockPos, _: BlockStateId) -> bool {
+ assert_eq!(pos, BlockPos::new(0, 1, 0));
+ !self.obstructed
+ }
+ fn random(&mut self) -> &mut LegacyRandom {
+ panic!("preview must not advance the live level's random source");
+ }
+ fn game_time(&self) -> i64 {
+ 0
+ }
+ }
+
+ // As with the LAN tests, prepared game resources are optional locally.
+ let resources = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../.local/horizon-client")
+ .join(horizon_core::VANILLA_VERSION);
+ if !resources.join("block-behaviours.json").exists() {
+ return;
+ }
+ let registry = load_registry(&resources).unwrap();
+ let behaviours = Behaviours::load(®istry, &resources).unwrap();
+ let mut base = Level {
+ air: registry.default_state("minecraft:air").unwrap(),
+ stone: registry.default_state("minecraft:stone").unwrap(),
+ obstructed: false,
+ loaded: true,
+ ceiling: 320,
+ };
+ for item in [
+ "minecraft:stone",
+ "minecraft:oak_slab",
+ "minecraft:oak_door",
+ // GrowingPlantHeadBlock.getStateForPlacement draws a random age.
+ "minecraft:twisting_vines",
+ ] {
+ let ctx = PlaceContext {
+ clicked_pos: BlockPos::new(0, 0, 0),
+ face: horizon_core::geometry::Direction::Up,
+ hit: horizon_core::geometry::Vec3::new(0.5, 1.0, 0.5),
+ inside: false,
+ yaw: 0.0,
+ pitch: 45.0,
+ sneaking: false,
+ item: item.into(),
+ can_use_game_master_blocks: false,
+ };
+ for (obstructed, loaded, ceiling) in [
+ (false, true, 320),
+ (true, true, 320),
+ (false, false, 320),
+ (false, true, 1),
+ ] {
+ base.obstructed = obstructed;
+ base.loaded = loaded;
+ base.ceiling = ceiling;
+ let valid = !obstructed && loaded && ceiling > 1;
+ let mut preview = DryLevel::new(&base);
+ let outcome = behaviours.place_block(&mut preview, &mut Ticks::default(), &ctx);
+ assert_eq!(
+ matches!(outcome, PlaceOutcome::Placed { .. }),
+ valid,
+ "{item}, obstructed={obstructed}, loaded={loaded}, ceiling={ceiling}"
+ );
+ assert_eq!(preview.changed.is_empty(), !valid);
+ assert_eq!(base.block_state(BlockPos::new(0, 1, 0)), base.air);
+ }
+ }
+ }
+
#[test]
fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() {
// InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand.
diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs
index 12a15bc34..4bba24946 100644
--- a/crates/horizon-client/src/game/remote_objects.rs
+++ b/crates/horizon-client/src/game/remote_objects.rs
@@ -52,6 +52,8 @@ impl Game<'_> {
invisible: false,
check_interval: 0,
});
+ } else if kind == "minecraft:lightning_bolt" {
+ self.spawn_remote_bolt(id, position);
} else if kind == "minecraft:painting" {
// The variant comes with the entity data; until then the
// registry's first one (VariantUtils.getAny).
@@ -123,6 +125,14 @@ impl Game<'_> {
} else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) {
match (index, value) {
(0, Value::Byte(flags)) => a.invisible = flags & 0x20 != 0,
+ // Entity.DATA_CUSTOM_NAME and DATA_CUSTOM_NAME_VISIBLE.
+ (2, Value::OptText(name)) => {
+ a.custom_name = name.as_ref().map(horizon_client::entity_nbt::name_text);
+ }
+ (2, Value::Text(name)) => {
+ a.custom_name = Some(horizon_client::entity_nbt::name_text(name));
+ }
+ (3, Value::Bool(visible)) => a.name_visible = *visible,
(9, Value::Float(health)) => a.health = *health,
// ArmorStand.DATA_CLIENT_FLAGS.
(15, Value::Byte(flags)) => {
@@ -180,7 +190,12 @@ impl Game<'_> {
/// A move's rotation and ground state for an object.
pub(super) fn turn_remote_object(&mut self, id: i32, yaw: Option, on_ground: bool) {
let id = id as u32;
+ // The boat the player drives turns here (isLocalInstanceAuthoritative).
+ let driven = self.riding;
if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
+ if Some(id) == driven {
+ return;
+ }
if let Some(yaw) = yaw {
b.yaw = yaw;
}
@@ -205,7 +220,12 @@ impl Game<'_> {
c.previous_yaw = c.yaw;
c.position = step(c.id, c.position);
}
+ // The boat the player drives moves here, not where the server says.
+ let driven = self.riding;
for b in &mut self.boats {
+ if Some(b.id) == driven {
+ continue;
+ }
b.previous = b.position;
b.previous_yaw = b.yaw;
b.position = step(b.id, b.position);
@@ -266,5 +286,6 @@ impl Game<'_> {
self.armor_stands.retain(|a| a.id != id);
self.item_frames.retain(|f| f.id != id);
self.paintings.retain(|p| p.id != id);
+ self.bolts.retain(|b| b.id != id);
}
}
diff --git a/crates/horizon-client/src/game/remote_vehicles.rs b/crates/horizon-client/src/game/remote_vehicles.rs
new file mode 100644
index 000000000..dc3b2b686
--- /dev/null
+++ b/crates/horizon-client/src/game/remote_vehicles.rs
@@ -0,0 +1,181 @@
+//! Boats, minecarts, item frames, armor stands and paintings for a server's
+//! client: single player on its server thread, a LAN guest, a player on a
+//! dedicated server.
+//!
+//! The client aims at them like at mobs (`Minecraft.hitResult`, then
+//! `ServerboundInteractPacket`), and rides the vehicle the server seats it in
+//! (`ClientPacketListener.handleSetEntityPassengersPacket`). A boat is
+//! controlled by its rider's client: it ticks here and its moves go to the
+//! server (`LocalPlayer.tick`: `ServerboundMoveVehiclePacket`,
+//! `AbstractBoat.tick`: `ServerboundPaddleBoatPacket`). A minecart moves on
+//! the server with the rider's input, and the rider sits in it.
+use super::{Game, Keys, view_vector};
+use horizon_core::geometry::Vec3;
+use horizon_protocol::packets::play::{self, Serverbound as S};
+
+/// An object under the crosshair: its entity id, how far along the view it
+/// was hit, and where (`EntityHitResult.getLocation` minus the entity's
+/// position, the interact packet's location).
+pub(super) struct ObjectHit {
+ pub id: i32,
+ pub distance: f64,
+ pub location: [f64; 3],
+}
+
+impl Game<'_> {
+ /// The nearest boat, minecart, item frame, armor stand or painting the
+ /// view hits within reach.
+ pub(super) fn remote_object_hit(&self) -> Option {
+ let eye = self.eye_position()?;
+ let dir = view_vector(self.yaw, self.pitch);
+ let at = |d: f64| {
+ [
+ eye[0] + dir[0] * d,
+ eye[1] + dir[1] * d,
+ eye[2] + dir[2] * d,
+ ]
+ };
+ let block_centre = |p: [i32; 3]| {
+ [
+ f64::from(p[0]) + 0.5,
+ f64::from(p[1]) + 0.5,
+ f64::from(p[2]) + 0.5,
+ ]
+ };
+ let mut hits: Vec<(i32, f64, [f64; 3])> = Vec::new();
+ if let Some((i, d)) = self.painting_hit() {
+ let p = &self.paintings[i];
+ hits.push((p.id as i32, d, block_centre(p.pos)));
+ }
+ if let Some((i, d)) = self.frame_hit() {
+ let f = &self.item_frames[i];
+ hits.push((f.id as i32, d, block_centre(f.pos)));
+ }
+ if let Some((i, d, _)) = self.armor_stand_hit() {
+ let a = &self.armor_stands[i];
+ let p = a.position;
+ hits.push((a.id as i32, d, [p.x, p.y, p.z]));
+ }
+ if let Some((i, d)) = self.boat_hit() {
+ let p = self.boats[i].position;
+ hits.push((self.boats[i].id as i32, d, [p.x, p.y, p.z]));
+ }
+ if let Some((i, d)) = self.cart_hit() {
+ let p = self.carts[i].position;
+ hits.push((self.carts[i].id as i32, d, [p.x, p.y, p.z]));
+ }
+ let (id, distance, origin) = hits.into_iter().min_by(|a, b| a.1.total_cmp(&b.1))?;
+ let point = at(distance);
+ Some(ObjectHit {
+ id,
+ distance,
+ location: [
+ point[0] - origin[0],
+ point[1] - origin[1],
+ point[2] - origin[2],
+ ],
+ })
+ }
+
+ /// `ClientPacketListener.handleSetEntityPassengersPacket`: who rides
+ /// `vehicle` now. The local player gets in or out; mobs and other
+ /// players sit where the server keeps them.
+ pub(super) fn remote_set_passengers(&mut self, vehicle: i32, passengers: &[i32]) {
+ let Some(me) = self.remote.as_ref().map(|r| r.entity_id) else {
+ return;
+ };
+ let vehicle_id = vehicle as u32;
+ for m in &mut self.mobs {
+ if m.extra.mount == Some(vehicle_id) && !passengers.contains(&(m.id as i32)) {
+ m.extra.mount = None;
+ } else if passengers.contains(&(m.id as i32)) {
+ m.extra.mount = Some(vehicle_id);
+ }
+ }
+ if passengers.contains(&me) {
+ if self.riding != Some(vehicle_id) {
+ self.riding = Some(vehicle_id);
+ if let Some(p) = self.player.as_mut() {
+ p.velocity = Vec3::ZERO;
+ p.fall_distance = 0.0;
+ }
+ }
+ } else if self.riding == Some(vehicle_id) {
+ // The server takes the player out, then teleports it.
+ self.riding = None;
+ }
+ }
+
+ /// The local player's tick in its vehicle, in place of its own movement:
+ /// false when it rides nothing.
+ pub(super) fn remote_ride(&mut self, keys: Keys) -> bool {
+ let Some(id) = self.riding else {
+ return false;
+ };
+ let seat = if let Some(i) = self.boats.iter().position(|b| b.id == id) {
+ // AbstractBoat.tick on the controlling client: steer and move.
+ let mut b = self.boats[i].clone();
+ b.input = [keys.left, keys.right, keys.forward, keys.backward];
+ let b = self.tick_boat(b, true);
+ // positionRider: the seat turns with the boat; clampRotation.
+ self.yaw += b.delta_rotation;
+ let delta = (self.yaw - b.yaw + 180.0).rem_euclid(360.0) - 180.0;
+ self.yaw += delta.clamp(-105.0, 105.0) - delta;
+ let seat = b.position;
+ self.boats[i] = b;
+ Some(seat)
+ } else {
+ // A minecart: the server moves it, the rider sits in it.
+ self.carts.iter().find(|c| c.id == id).map(|c| c.position)
+ };
+ if let Some(p) = self.player.as_mut() {
+ self.previous_position = p.position;
+ if let Some(v) = seat {
+ p.position = Vec3::new(v.x, v.y + super::boats::SEAT, v.z);
+ }
+ p.velocity = Vec3::ZERO;
+ p.fall_distance = 0.0;
+ }
+ true
+ }
+
+ /// `LocalPlayer.tick` for a passenger: the boat it controls goes to the
+ /// server every tick with its paddles (the rider's own position does not).
+ pub(super) fn remote_vehicle_packets(&self) -> Vec {
+ let Some(b) = self
+ .riding
+ .and_then(|id| self.boats.iter().find(|b| b.id == id))
+ else {
+ return Vec::new();
+ };
+ vec![
+ S::MoveVehicle(play::MoveVehicleRequest {
+ position: [b.position.x, b.position.y, b.position.z],
+ yaw: b.yaw,
+ pitch: 0.0,
+ on_ground: b.on_ground,
+ }),
+ S::PaddleBoat(play::PaddleBoat {
+ left: b.paddling[0],
+ right: b.paddling[1],
+ }),
+ ]
+ }
+
+ /// `ClientPacketListener.handleMoveVehicle`: the server put the boat the
+ /// player drives back.
+ pub(super) fn remote_move_vehicle(&mut self, position: [f64; 3], yaw: f32) {
+ let Some(b) = self
+ .riding
+ .and_then(|id| self.boats.iter_mut().find(|b| b.id == id))
+ else {
+ return;
+ };
+ let at = Vec3::new(position[0], position[1], position[2]);
+ b.previous = at;
+ b.position = at;
+ b.yaw = yaw;
+ b.previous_yaw = yaw;
+ b.velocity = Vec3::ZERO;
+ }
+}
diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs
index 99dae39a5..4d60c2df7 100644
--- a/crates/horizon-client/src/game/scoreboard.rs
+++ b/crates/horizon-client/src/game/scoreboard.rs
@@ -431,20 +431,18 @@ impl Game<'_> {
self.score.board.players_team(self.acting_player_name())
}
/// The teams of the player and of the mobs on one (empty without teams).
- pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams {
+ pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams<'_> {
let board = &self.score.board;
if board.teams.is_empty() {
return Default::default();
}
horizon_client::mobs::Teams {
- player: self.player_team().cloned(),
+ player: self.player_team(),
mobs: self
.persist
.uuids
.iter()
- .filter_map(|(id, uuid)| {
- Some((*id, board.players_team(&uuid_text(*uuid))?.clone()))
- })
+ .filter_map(|(id, uuid)| Some((*id, board.players_team(&uuid_text(*uuid))?)))
.collect(),
}
}
@@ -599,6 +597,11 @@ impl Game<'_> {
/// objective.
pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) {
use horizon_client::tab_list::{self, TabInputs};
+ // Player heads and the player list both draw from the same skin slots.
+ let ready: Vec<_> = self.skin_downloads.borrow_mut().take_ready();
+ for (location, rgba) in ready {
+ self.store_skin(location, rgba);
+ }
let key = self.screen == super::Screen::Playing
&& self.keys.contains(&winit::keyboard::KeyCode::Tab);
let (players, online_mode, upside_down) = match self.remote_tab_players() {
diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs
index cecd8d46f..ae36b44df 100644
--- a/crates/horizon-client/src/game/screens.rs
+++ b/crates/horizon-client/src/game/screens.rs
@@ -7,6 +7,28 @@ use horizon_client::{
ui,
};
+impl Screen {
+ /// Screen.extractBackground for non-isInGameUi screens, and
+ /// PauseScreen.extractBackground only when showPauseMenu is true.
+ pub(super) fn blurs_background(self, pause_menu: bool) -> bool {
+ match self {
+ Self::Paused => pause_menu,
+ Self::Options
+ | Self::Stats
+ | Self::Advancements
+ | Self::WorldOptions
+ | Self::Friends => true,
+ Self::Playing
+ | Self::GameModeSwitcher
+ | Self::Chat
+ | Self::Creative
+ | Self::Inventory
+ | Self::Dead
+ | Self::CommandBlock => false,
+ }
+ }
+}
+
/// PauseScreen buttons: (x, y, width, label key, action id, active).
/// https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/PauseScreen
fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static str, u8, bool)> {
@@ -43,6 +65,9 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s
}
/// The icon row: report bugs, feedback, friends, player reporting.
+/// `FRIENDS_ICON` (vanilla's `CommonButtons.friends`) opens Horizon's
+/// Play with Friends; the others stay inactive.
+const FRIENDS_ICON: usize = 2;
fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] {
let x0 = ((w - 212.0) * 0.5).floor() + 60.0;
let y = ((h - 166.0) * 0.25).floor() + 98.0;
@@ -69,41 +94,8 @@ impl Game<'_> {
pub(super) fn external_server(&self) -> bool {
self.remote.is_some() && self.integrated.is_none()
}
- /// Whether the pause menu is drawn in Horizon's style (over a blurred world).
- pub(super) fn horizon_pause(&self) -> bool {
- self.screen == Screen::Paused
- && self.pause_menu
- && self.title.is_none()
- && horizon_client::ui_theme::horizon()
- }
- fn pause_labels(&self) -> (String, &'static str) {
- if let Some(server) = &self.integrated {
- return (server.world_name.clone(), "Save and quit");
- }
- if self.external_server() {
- ("Multiplayer".to_owned(), "Disconnect")
- } else {
- (self.level.name.clone(), "Save and quit")
- }
- }
pub(super) fn draw_pause_menu(&mut self, batch: &mut HudBatch) {
- if horizon_client::ui_theme::horizon() {
- let opened = *self.pause_since.get_or_insert_with(std::time::Instant::now);
- let (world, quit) = self.pause_labels();
- self.tick_friends();
- let friends = self.friends_view();
- let mut ui = horizon_client::ui_theme::Ui::new(&self.gui.atlas, batch, self.cursor);
- horizon_client::front::pause::draw(
- &mut ui,
- &world,
- quit,
- opened,
- &friends,
- self.external_server(),
- );
- ui.finish();
- return;
- }
+ let friends = self.friends_view().shown;
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
@@ -131,12 +123,41 @@ impl Game<'_> {
hover,
);
}
- for (x, y, sprite) in pause_icons(w, h) {
- ui::button(batch, atlas, x, y, 20.0, 20.0, &Text::empty(), false, false);
+ let mut tooltip = None;
+ for (i, (x, y, sprite)) in pause_icons(w, h).into_iter().enumerate() {
+ let active = i == FRIENDS_ICON && friends;
+ let hover = ui::hovered(self.cursor, x, y, 20.0, 20.0);
+ // The icon has no label: name it for controller focus and the
+ // control socket's widget tree.
+ if i == FRIENDS_ICON {
+ horizon_client::widgets::record(
+ horizon_client::friends_screen::TITLE,
+ [x, y, 20.0, 20.0],
+ active,
+ );
+ }
+ ui::button(
+ batch,
+ atlas,
+ x,
+ y,
+ 20.0,
+ 20.0,
+ &Text::empty(),
+ active,
+ active && hover,
+ );
// SpriteIconButton.CenteredIcon: the 15x15 sprite at
// x + width / 2 - 15 / 2 in integer pixels, untinted even
// when the button is inactive.
batch.sprite_scaled(atlas, sprite, x + 3.0, y + 3.0, 15.0, 15.0, u32::MAX);
+ if i == FRIENDS_ICON && hover {
+ tooltip = Some(Text::literal(horizon_client::friends_screen::TITLE));
+ }
+ }
+ // SpriteIconButton.withTootip: the label as a tooltip.
+ if let Some(tip) = tooltip {
+ ui::tooltip(batch, atlas, &[tip], self.cursor);
}
}
pub(super) fn pause_click(&mut self) -> Result<()> {
@@ -148,29 +169,16 @@ impl Game<'_> {
let b = HudBatch::new(size);
(b.width, b.height)
};
- let hit = if horizon_client::ui_theme::horizon() {
- let size = self
- .renderer
- .as_ref()
- .map_or([1, 1], |r| [r.config.width, r.config.height]);
- let mut b = HudBatch::new(size);
- let (world, quit) = self.pause_labels();
- horizon_client::front::pause::click(
- &self.gui.atlas,
- &mut b,
- self.cursor.0,
- self.cursor.1,
- &world,
- quit,
- &self.friends_view(),
- self.external_server(),
- )
- } else {
- pause_buttons(w, h, self.external_server())
- .into_iter()
- .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
- .map(|b| b.4)
- };
+ let friends = pause_icons(w, h)[FRIENDS_ICON];
+ let hit = pause_buttons(w, h, self.external_server())
+ .into_iter()
+ .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
+ .map(|b| b.4)
+ .or_else(|| {
+ (self.friends_view().shown
+ && ui::hovered(self.cursor, friends.0, friends.1, 20.0, 20.0))
+ .then_some(10)
+ });
match hit {
Some(0) => {
self.screen = Screen::Playing;
@@ -180,17 +188,11 @@ impl Game<'_> {
Some(3) => self.open_stats(),
Some(4) => self.open_advancements(true),
Some(9) => self.open_world_options(),
- Some(10) => {
- if let Err(e) = self.friends_start() {
- self.system_message(Text::literal(format!("Couldn't share the world: {e}")));
- }
- }
- Some(11) => self.friends_copy(),
- Some(12) => self.friends_stop(),
+ Some(10) => self.screen = Screen::Friends,
Some(2) => self.close_world()?,
_ => {}
}
- if hit.is_some() && !horizon_client::ui_theme::horizon() {
+ if hit.is_some() {
self.audio.play_button_click();
}
Ok(())
@@ -334,7 +336,34 @@ impl Game<'_> {
#[cfg(test)]
mod tests {
- use super::pause_buttons;
+ use super::{Screen, pause_buttons};
+
+ #[test]
+ fn menu_blur_matches_vanilla_screen_backgrounds() {
+ for screen in [
+ Screen::Options,
+ Screen::Stats,
+ Screen::Advancements,
+ Screen::WorldOptions,
+ ] {
+ assert!(screen.blurs_background(false));
+ assert!(screen.blurs_background(true));
+ }
+ assert!(Screen::Paused.blurs_background(true));
+ assert!(!Screen::Paused.blurs_background(false));
+ for screen in [
+ Screen::Playing,
+ Screen::GameModeSwitcher,
+ Screen::Chat,
+ Screen::Creative,
+ Screen::Inventory,
+ Screen::Dead,
+ Screen::CommandBlock,
+ ] {
+ assert!(!screen.blurs_background(true));
+ assert!(!screen.blurs_background(false));
+ }
+ }
#[test]
fn pause_menu_uses_disconnect_for_servers_and_keeps_world_options() {
diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs
index 096562608..8667f305f 100644
--- a/crates/horizon-client/src/game/sculk.rs
+++ b/crates/horizon-client/src/game/sculk.rs
@@ -71,6 +71,8 @@ pub(super) struct SculkState {
/// The sculk block entities in the order they were added.
index: Index,
pub known: HashSet<(i32, i32)>,
+ /// The chunk map's membership revision `known` was taken at.
+ pub known_revision: Option,
// Keyed by mob ids the server gives out: the fast hasher is safe.
steps: FxHashMap,
damaged: FxHashMap,
@@ -336,7 +338,10 @@ impl Game<'_> {
/// the block writes recorded since the last tick.
pub(super) fn sculk_sync_index(&mut self) {
// Chunks that arrived or left (every half second is plenty).
- if self.sculk.ticks.is_multiple_of(10) {
+ // Nothing to do while no chunk came or went.
+ let revision = self.world.chunks.membership_revision();
+ if self.sculk.ticks.is_multiple_of(10) && self.sculk.known_revision != Some(revision) {
+ self.sculk.known_revision = Some(revision);
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
let arrived: Vec<(i32, i32)> = loaded.difference(&self.sculk.known).copied().collect();
for key in arrived {
diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs
index d71cd5431..b02dfe998 100644
--- a/crates/horizon-client/src/game/sculk_fixture.rs
+++ b/crates/horizon-client/src/game/sculk_fixture.rs
@@ -433,6 +433,7 @@ impl Game<'_> {
});
self.level_events.clear();
self.sculk.known = self.world.chunks.keys().copied().collect();
+ self.sculk.known_revision = Some(self.world.chunks.membership_revision());
self.sculk_sync_index();
let mut names: HashMap = HashMap::new();
let mut sources: Vec = Vec::new();
diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs
index ffbbe7193..0c8376397 100644
--- a/crates/horizon-client/src/game/startup_menu.rs
+++ b/crates/horizon-client/src/game/startup_menu.rs
@@ -73,11 +73,6 @@ impl StartupMenu {
&self.root,
);
title.last_server = settings.file.string("lastServer");
- if horizon_client::ui_theme::horizon() {
- title
- .opening
- .set(Some(horizon_client::front::Opening::new()));
- }
self.title = Some(title);
}
}
@@ -152,9 +147,6 @@ impl StartupMenu {
fn title_key(&mut self, event: &KeyEvent) {
let shortcut = self.shortcut(event);
let Some(title) = &mut self.title else { return };
- if title.skip_opening() {
- return;
- }
if let Some(shortcut) = shortcut {
if title.has_caret_field() {
title.field_shortcut(shortcut, &mut self.clipboard);
@@ -422,14 +414,6 @@ impl Loading {
event_loop: &ActiveEventLoop,
event: WindowEvent,
) -> Result<()> {
- if let WindowEvent::MouseInput {
- state,
- button: MouseButton::Left,
- ..
- } = &event
- {
- horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed);
- }
if let WindowEvent::KeyboardInput { event, .. } = &event
&& let PhysicalKey::Code(key) = event.physical_key
{
@@ -455,7 +439,6 @@ impl Loading {
WindowEvent::Focused(false) => {
self.menu.modifiers = ModifiersState::empty();
self.menu.physical_keys.clear();
- horizon_client::ui_theme::set_pressed(false);
self.menu.dragging = false;
if let Some(title) = &mut self.menu.title {
title.release();
@@ -508,41 +491,23 @@ impl Loading {
button: MouseButton::Left,
..
} => {
- let mut batch = HudBatch::new(self.menu_size());
+ let batch = HudBatch::new(self.menu_size());
if let (Some(title), Some(gui)) = (&mut self.menu.title, &self.gui) {
if state == ElementState::Released {
title.release();
title.release_field();
} else {
- let action = if horizon_client::ui_theme::horizon() {
- let action = title.click_horizon(
- &gui.atlas,
- &mut batch,
- self.menu.cursor.0,
- self.menu.cursor.1,
- );
- // Horizon's deeper world-management pages use classic fields.
- title.press_field(
- &gui.atlas,
- self.menu.cursor,
- (batch.width, batch.height),
- self.menu.modifiers.shift_key(),
- );
- action
- } else {
- let (action, _) = title.click(
- self.menu.cursor.0,
- self.menu.cursor.1,
- (batch.width, batch.height),
- );
- title.press_field(
- &gui.atlas,
- self.menu.cursor,
- (batch.width, batch.height),
- self.menu.modifiers.shift_key(),
- );
- action
- };
+ let (action, _) = title.click(
+ self.menu.cursor.0,
+ self.menu.cursor.1,
+ (batch.width, batch.height),
+ );
+ title.press_field(
+ &gui.atlas,
+ self.menu.cursor,
+ (batch.width, batch.height),
+ self.menu.modifiers.shift_key(),
+ );
self.menu_action(event_loop, action);
}
}
@@ -617,18 +582,12 @@ impl Loading {
} else if let Some(title) = &mut self.menu.title {
title.poll_backup();
let _ = title.update_toast(self.settings.notification_display_time);
- if horizon_client::ui_theme::horizon() {
- let mut ui = horizon_client::ui_theme::Ui::new(&gui.atlas, batch, self.menu.cursor);
- title.draw_horizon(&mut ui, 0.0);
- ui.finish();
- } else {
- title.draw(
- &gui.atlas,
- batch,
- self.menu.cursor,
- self.settings.file.bool("hideSplashTexts"),
- );
- }
+ title.draw(
+ &gui.atlas,
+ batch,
+ self.menu.cursor,
+ self.settings.file.bool("hideSplashTexts"),
+ );
}
}
@@ -730,7 +689,6 @@ mod tests {
// Navigate and enter a world name without a registry, biomes, pack
// tables or a Game. Replacing fallback artwork preserves this state.
let title = loading.menu.title.as_mut().unwrap();
- title.opening.set(None);
title.mode = horizon_client::title::Mode::Create {
name: String::new(),
seed: "42".into(),
diff --git a/crates/horizon-client/src/game/zombie_villagers.rs b/crates/horizon-client/src/game/zombie_villagers.rs
index c68c0f1c1..b47e2460c 100644
--- a/crates/horizon-client/src/game/zombie_villagers.rs
+++ b/crates/horizon-client/src/game/zombie_villagers.rs
@@ -194,7 +194,9 @@ fn carry_over(from: &Mob, to: &mut Mob) {
to.fire_ticks = from.fire_ticks;
to.persistent = from.persistent;
to.custom_name = from.custom_name.clone();
+ to.custom_name_text = from.custom_name_text.clone();
to.name_visible = from.name_visible;
+ to.invisible = from.invisible;
to.extra.pick_up_loot = from.extra.pick_up_loot;
to.extra.main_hand = from.extra.main_hand.clone();
to.extra.off_hand = from.extra.off_hand.clone();
diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs
index 14c040c5c..9250940da 100644
--- a/crates/horizon-client/src/gfx.rs
+++ b/crates/horizon-client/src/gfx.rs
@@ -33,6 +33,7 @@ fn entity_shader() -> String {
}
mod entity_batch;
+mod weather;
use entity_batch::EntityBatch;
pub use entity_batch::WATER_MASK_OVERLAY;
@@ -61,8 +62,10 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6]
mod arena;
mod cull;
+mod end_sky;
mod flat;
mod java_stages;
+pub mod lightning;
mod lod;
mod occlusion;
mod pack_stages;
@@ -163,8 +166,10 @@ pub struct Frame<'a> {
pub title: bool,
/// Dimensions without a skybox (the Nether) clear to the fog colour.
pub skybox: bool,
- /// The End: clear to black and draw `celestial` (the End sky box) behind the world.
+ /// The End: clear to black and draw the resident sky box behind the world.
pub end_sky: bool,
+ /// End sky atlas bounds (u0, v0, u1, v1); absent when the sprite is missing.
+ pub end_sky_sprite: Option<[f32; 4]>,
/// Environmental fog start/end (Nether 10..96), if any.
pub environment_fog: Option<(f32, f32)>,
pub water_fog: [f32; 3],
@@ -189,16 +194,20 @@ pub struct Frame<'a> {
pub nether_lighting: bool,
/// Camera-relative entity geometry textured from the shared atlas.
pub entities: &'a [Vertex],
+ pub weather: &'a [crate::weather::Vertex],
+ pub weather_time: crate::weather::Time,
/// Horizon Extras' dynamic lights, nearest first (`dynamic_light::select`); empty when off.
pub dynamic_lights: &'a [[f32; 4]],
/// Cloud mesh inputs; geometry and GPU storage are retained by the renderer.
pub clouds: Option>,
- /// Additive translucent geometry after the entities (lightning, dragon rays).
+ /// Retained lightning bolts, drawn before the other additive entities.
+ pub lightning: lightning::Input<'a>,
+ /// Additive translucent geometry after lightning (dragon rays).
pub additive: &'a [Vertex],
/// Name tags over everything, without depth (`TEXT_SEE_THROUGH`).
pub see_through: &'a [Vertex],
- /// Camera-relative sun and moon, or the End sky box (drawn behind
- /// everything, additive).
+ /// Camera-relative sun and moon, or the animated End flash (additive,
+ /// behind everything and after the resident End sky box).
pub celestial: &'a [Vertex],
/// The stars, drawn from their static buffer after the sun and moon:
/// the sky's rotation (camera-relative world from star space) and the
@@ -230,8 +239,6 @@ pub struct Frame<'a> {
pub night_vision: f32,
/// Torch flicker added to the block light factor of 1.4.
pub block_flicker: f32,
- /// Blur and grade the frame under a Horizon-style menu (`post`).
- pub post: Option,
/// `Screen.extractBlurredBackground`: blur the frame by this radius
/// (`menuBackgroundBlurriness`) before the screen is drawn over it.
pub menu_blur: Option,
@@ -324,6 +331,7 @@ pub struct Renderer {
crosshair_group: wgpu::BindGroup,
crosshair_globals: wgpu::Buffer,
entity_pipeline: wgpu::RenderPipeline,
+ weather: weather::Weather,
crumbling_pipeline: wgpu::RenderPipeline,
/// `RenderPipelines.WATER_MASK`: depth writes only, no colour.
water_mask_pipeline: wgpu::RenderPipeline,
@@ -334,9 +342,12 @@ pub struct Renderer {
cloud_uniform: wgpu::Buffer,
cloud_group: wgpu::BindGroup,
additive_pipeline: wgpu::RenderPipeline,
+ lightning_pipeline: wgpu::RenderPipeline,
+ lightning: lightning::Renderer,
see_through_pipeline: wgpu::RenderPipeline,
celestial_pipeline: wgpu::RenderPipeline,
celestial_buffer: wgpu::Buffer,
+ end_sky: end_sky::EndSky,
stars: stars::Stars,
panorama: panorama::Panorama,
/// `RenderPipelines.WORLD_BORDER` and its buffers.
@@ -437,8 +448,6 @@ pub struct Renderer {
/// The selected shader pack's stages (Horizon setting; none by default).
pack: Option,
pub hud: HudRenderer,
- /// The menus' backdrop blur, made on first use.
- post: Option,
/// Vanilla's menu background blur, made on first use.
menu_blur: Option,
pub info: wgpu::AdapterInfo,
@@ -1445,6 +1454,12 @@ impl Renderer {
),
],
});
+ let weather = weather::Weather::new(
+ &device,
+ config.format.remove_srgb_suffix(),
+ &entity_bindings,
+ &entity_shader,
+ );
let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Atlas"),
..Default::default()
@@ -1664,8 +1679,17 @@ impl Renderer {
alpha_blend,
false,
);
+ let lightning_attributes = wgpu::vertex_attr_array![6=>Float32x3];
+ let lightning_vertex = [
+ entity_vertex[0].clone(),
+ Some(wgpu::VertexBufferLayout {
+ array_stride: std::mem::size_of::<[f32; 3]>() as u64,
+ step_mode: wgpu::VertexStepMode::Instance,
+ attributes: &lightning_attributes,
+ }),
+ ];
// BlendFunction.LIGHTNING: src alpha, one; no depth writes.
- let additive_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ let additive_descriptor = wgpu::RenderPipelineDescriptor {
label: Some("Additive entities"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
@@ -1709,6 +1733,16 @@ impl Renderer {
}),
multiview_mask: None,
cache: None,
+ };
+ let additive_pipeline = device.create_render_pipeline(&additive_descriptor);
+ let lightning_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Lightning"),
+ vertex: wgpu::VertexState {
+ entry_point: Some("vs_lightning"),
+ buffers: &lightning_vertex,
+ ..additive_descriptor.vertex.clone()
+ },
+ ..additive_descriptor
});
let celestial_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Celestial bodies"),
@@ -2101,6 +2135,7 @@ impl Renderer {
crosshair_group,
crosshair_globals,
entity_pipeline,
+ weather,
crumbling_pipeline,
water_mask_pipeline,
cloud_pipeline,
@@ -2110,9 +2145,12 @@ impl Renderer {
cloud_uniform,
cloud_group,
additive_pipeline,
+ lightning_pipeline,
+ lightning: lightning::Renderer::new(),
see_through_pipeline,
celestial_pipeline,
celestial_buffer,
+ end_sky: end_sky::EndSky::default(),
stars,
panorama,
border_pipeline,
@@ -2181,7 +2219,6 @@ impl Renderer {
world_post,
pack: None,
hud,
- post: None,
menu_blur: None,
info,
suspended: size.width == 0 || size.height == 0,
@@ -3229,6 +3266,13 @@ impl Renderer {
bytemuck::cast_slice(&all),
);
}
+ self.weather.prepare(
+ &self.device,
+ &mut encoder,
+ &mut self.uploads,
+ frame.weather,
+ frame.weather_time,
+ );
let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize);
if outline_edges > 0 {
let lines = outline_vertices(&frame.outline[..outline_edges], camera);
@@ -3246,6 +3290,7 @@ impl Renderer {
frame.hand,
frame.see_through,
);
+ let weather_quads = frame.weather.len() as u32 / 4;
let world_quads =
entity_quads + crumbling_quads + translucent_crumbling_quads + water_mask_quads;
let cloud_quads = if let Some(input) = &frame.clouds {
@@ -3279,6 +3324,13 @@ impl Renderer {
} else {
0
};
+ self.lightning.prepare(
+ &self.device,
+ &mut self.uploads,
+ &mut encoder,
+ &frame.lightning,
+ camera,
+ );
let all_entities = &self.entity_batch.combined;
let hand_quads = (frame.hand.len() / 4) as u32;
let additive_quads = (frame.additive.len() / 4) as u32;
@@ -3310,6 +3362,9 @@ impl Renderer {
);
}
let celestial_vertices = frame.celestial.len().min(2048 * 4);
+ if frame.end_sky && !frame.title {
+ self.end_sky.prepare(&self.device, frame.end_sky_sprite);
+ }
if celestial_vertices > 0 {
self.uploads.buffer(
&mut encoder,
@@ -3318,8 +3373,14 @@ impl Renderer {
bytemuck::cast_slice(&frame.celestial[..celestial_vertices]),
);
}
- let max_quads =
- (world_quads + additive_quads + hand_quads + see_through_quads).max(cloud_quads);
+ let max_quads = (world_quads + additive_quads + hand_quads + see_through_quads)
+ .max(cloud_quads)
+ .max(if frame.lightning.bolts.is_empty() {
+ 0
+ } else {
+ lightning::QUADS
+ })
+ .max(weather_quads);
if max_quads > self.index_quads {
self.index_quads = max_quads.next_power_of_two();
self.indices = Self::quad_indices(&self.device, self.index_quads);
@@ -3510,12 +3571,17 @@ impl Renderer {
if frame.title {
self.panorama.draw(&mut pass);
pass.set_bind_group(0, &self.group, &[]);
- } else if celestial_vertices > 0 {
+ } else if celestial_vertices > 0 || frame.end_sky {
pass.set_pipeline(&self.celestial_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
- pass.set_vertex_buffer(0, self.celestial_buffer.slice(..));
- pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1);
+ if frame.end_sky {
+ self.end_sky.draw(&mut pass);
+ }
+ if celestial_vertices > 0 {
+ pass.set_vertex_buffer(0, self.celestial_buffer.slice(..));
+ pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1);
+ }
pass.set_bind_group(0, &self.group, &[]);
}
if !frame.title && frame.stars.is_some() {
@@ -3602,6 +3668,8 @@ impl Renderer {
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
+ self.weather.draw(&mut pass, &self.entity_group);
+ pass.set_bind_group(0, &self.group, &[]);
if crumbling_quads > 0 {
pass.set_pipeline(&self.crumbling_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
@@ -3622,6 +3690,12 @@ impl Renderer {
);
pass.set_bind_group(0, &self.group, &[]);
}
+ if !frame.lightning.bolts.is_empty() {
+ pass.set_pipeline(&self.lightning_pipeline);
+ pass.set_bind_group(0, &self.entity_group, &[]);
+ self.lightning.draw(&mut pass, &frame.lightning);
+ pass.set_bind_group(0, &self.group, &[]);
+ }
if additive_quads > 0 {
pass.set_pipeline(&self.additive_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
@@ -3841,9 +3915,19 @@ impl Renderer {
let first = debug_depth + debug_top;
pass.draw(0..4, first..first + crosshair);
}
- if let Some(radius) = frame.menu_blur
- && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
- {
+ let menu_blur = frame
+ .menu_blur
+ .filter(|_| self.config.usage.contains(wgpu::TextureUsages::COPY_SRC));
+ let blur_at = menu_blur.map_or(0, |_| frame.hud.blur_at);
+ self.hud.draw_range(
+ &mut encoder,
+ &view_target,
+ &self.depth,
+ frame.hud,
+ [self.config.width, self.config.height],
+ 0..blur_at,
+ );
+ if let Some(radius) = menu_blur {
let format = self.config.format;
let device = &self.device;
self.menu_blur
@@ -3858,29 +3942,13 @@ impl Renderer {
radius,
);
}
- if let Some(grade) = &frame.post
- && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
- {
- let format = self.config.format;
- let device = &self.device;
- self.post
- .get_or_insert_with(|| crate::post::Post::new(device, format))
- .apply(
- &self.device,
- &self.queue,
- &mut encoder,
- &target_texture,
- &view_target,
- [self.config.width, self.config.height],
- grade,
- );
- }
- self.hud.draw(
+ self.hud.draw_range(
&mut encoder,
&view_target,
&self.depth,
frame.hud,
[self.config.width, self.config.height],
+ blur_at..frame.hud.vertices.len() as u32,
);
if culling && let Some(cull) = &mut self.cull {
cull.end(&self.device, &mut encoder);
diff --git a/crates/horizon-client/src/gfx/end_sky.rs b/crates/horizon-client/src/gfx/end_sky.rs
new file mode 100644
index 000000000..15e9001fc
--- /dev/null
+++ b/crates/horizon-client/src/gfx/end_sky.rs
@@ -0,0 +1,84 @@
+//! The End sky's six tiled faces, retained for the lifetime of the renderer's atlas.
+use crate::mesher::Vertex;
+use wgpu::util::DeviceExt;
+
+const VERTICES: u32 = 6 * 16 * 16 * 4;
+
+#[derive(Default)]
+pub(super) struct EndSky {
+ mesh: Option<([f32; 4], wgpu::Buffer)>,
+}
+
+impl EndSky {
+ /// Called only when the End sky is enabled. Rebuild on atlas UV changes;
+ /// resource reload and device recreation also replace the owning renderer.
+ pub(super) fn prepare(&mut self, device: &wgpu::Device, uv: Option<[f32; 4]>) {
+ let Some(uv) = uv else {
+ self.mesh = None;
+ return;
+ };
+ if self.mesh.as_ref().is_some_and(|(old, _)| *old == uv) {
+ return;
+ }
+ let vertices = vertices(uv);
+ let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("End sky vertices"),
+ contents: bytemuck::cast_slice(&vertices),
+ usage: wgpu::BufferUsages::VERTEX,
+ });
+ self.mesh = Some((uv, buffer));
+ }
+
+ /// The celestial pipeline, atlas bind group and quad indices are already bound.
+ pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {
+ if let Some((_, buffer)) = &self.mesh {
+ pass.set_vertex_buffer(0, buffer.slice(..));
+ pass.draw_indexed(0..VERTICES / 4 * 6, 0, 0..1);
+ }
+ }
+}
+
+/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times,
+/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
+fn vertices(uv: [f32; 4]) -> Vec {
+ let mut out = Vec::with_capacity(VERTICES as usize);
+ use std::f32::consts::FRAC_PI_2;
+ let faces = [
+ glam::Mat4::IDENTITY,
+ glam::Mat4::from_rotation_x(FRAC_PI_2),
+ glam::Mat4::from_rotation_x(-FRAC_PI_2),
+ glam::Mat4::from_rotation_x(std::f32::consts::PI),
+ glam::Mat4::from_rotation_z(FRAC_PI_2),
+ glam::Mat4::from_rotation_z(-FRAC_PI_2),
+ ];
+ let step = 200.0 / 16.0;
+ for pose in faces {
+ for a in 0..16 {
+ for b in 0..16 {
+ let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32);
+ let (x1, z1) = (x0 + step, z0 + step);
+ let corners = [
+ (x0, z0, [uv[0], uv[1]]),
+ (x0, z1, [uv[0], uv[3]]),
+ (x1, z1, [uv[2], uv[3]]),
+ (x1, z0, [uv[2], uv[1]]),
+ ];
+ for (x, z, uv) in corners {
+ let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z));
+ out.push(Vertex {
+ normal: [0; 4],
+ pos: p.to_array(),
+ uv,
+ layer: 2,
+ color: 0xFF28_2828,
+ light: 0,
+ });
+ }
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/horizon-client/src/gfx/end_sky/tests.rs b/crates/horizon-client/src/gfx/end_sky/tests.rs
new file mode 100644
index 000000000..61266003d
--- /dev/null
+++ b/crates/horizon-client/src/gfx/end_sky/tests.rs
@@ -0,0 +1,330 @@
+use super::*;
+use crate::gfx::{Globals, Renderer};
+use bytemuck::Zeroable;
+use glam::Mat4;
+
+#[test]
+fn geometry_matches_pre_residency_vertex_snapshots() {
+ use sha2::{Digest, Sha256};
+ // Captured from game/end.rs at 34c3c1cf for full, tiled and non-binary UVs.
+ // Quantize positions only, avoiding platform sin/cos rounding differences;
+ // quad order, UVs, tint, material and light retain their exact byte values.
+ for (uv, expected) in [
+ (
+ [0.0, 0.0, 1.0, 1.0],
+ "f7ee23457fc557b33ecf09c9afaf858f3d8907e108abf06055f627523f733536",
+ ),
+ (
+ [0.125, 0.25, 0.375, 0.5],
+ "f74c4b8d23ec2b7c11b5752821d0733851bf11358f1b26f9448226ff62a6a318",
+ ),
+ (
+ [0.13, 0.27, 0.41, 0.59],
+ "f0aaa39c5b22168bdc7c6c329acb4d3598a2feb61ff7b6f2850b644682749b39",
+ ),
+ ] {
+ let mut mesh = vertices(uv);
+ assert_eq!(mesh.len(), VERTICES as usize);
+ for vertex in &mut mesh {
+ vertex.pos = vertex.pos.map(|x| {
+ let n = (x * 1024.0).round() / 1024.0;
+ if n == 0.0 { 0.0 } else { n }
+ });
+ }
+ assert_eq!(
+ format!("{:x}", Sha256::digest(bytemuck::cast_slice(&mesh))),
+ expected
+ );
+ }
+}
+
+fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
+ let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
+ eprintln!("End sky test adapter: {:?}", adapter.get_info());
+ pollster::block_on(adapter.request_device(&Default::default())).ok()
+}
+
+#[test]
+fn resident_buffer_survives_frames_and_refreshes_with_the_atlas() {
+ let Some((device, _)) = device() else {
+ eprintln!("no GPU adapter: skipped");
+ return;
+ };
+ let mut sky = EndSky::default();
+ let uv = [0.125, 0.25, 0.375, 0.5];
+ sky.prepare(&device, Some(uv));
+ let first = sky.mesh.as_ref().unwrap().1.clone();
+ assert_eq!(
+ first.size(),
+ u64::from(VERTICES) * size_of::() as u64
+ );
+ // Immutable: steady-state frames cannot upload into this buffer.
+ assert_eq!(first.usage(), wgpu::BufferUsages::VERTEX);
+ for _ in 0..600 {
+ sky.prepare(&device, Some(uv));
+ assert_eq!(sky.mesh.as_ref().unwrap().1, first);
+ }
+ let moved = [0.5, 0.5, 0.75, 0.75];
+ sky.prepare(&device, Some(moved));
+ assert_ne!(sky.mesh.as_ref().unwrap().1, first);
+ assert_eq!(sky.mesh.as_ref().unwrap().0, moved);
+ sky.prepare(&device, None);
+ assert!(sky.mesh.is_none());
+ sky.prepare(&device, Some(uv));
+ assert_ne!(sky.mesh.as_ref().unwrap().1, first);
+ // A resource reload/device recreation starts a new renderer-owned cache,
+ // even if the replacement atlas happens to use exactly the same UVs.
+ let mut replacement = EndSky::default();
+ replacement.prepare(&device, Some(uv));
+ assert_ne!(
+ replacement.mesh.as_ref().unwrap().1,
+ sky.mesh.as_ref().unwrap().1
+ );
+}
+
+/// The actual entity shader and celestial blend, comparing the old combined
+/// vertex stream with a resident sky draw followed by a separate flash draw.
+#[test]
+fn separate_draws_match_combined_celestial_pixels() {
+ let Some((device, queue)) = device() else {
+ eprintln!("no GPU adapter: skipped");
+ return;
+ };
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("End sky differential shader"),
+ source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()),
+ });
+ let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4];
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("End sky differential pipeline"),
+ layout: None,
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_entity"),
+ compilation_options: Default::default(),
+ buffers: &[Some(wgpu::VertexBufferLayout {
+ array_stride: size_of::() as u64,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &attributes,
+ })],
+ },
+ primitive: wgpu::PrimitiveState {
+ cull_mode: None,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: Default::default(),
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_celestial"),
+ compilation_options: Default::default(),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: Some(wgpu::BlendState {
+ color: wgpu::BlendComponent {
+ src_factor: wgpu::BlendFactor::SrcAlpha,
+ dst_factor: wgpu::BlendFactor::One,
+ operation: wgpu::BlendOperation::Add,
+ },
+ alpha: wgpu::BlendComponent::OVER,
+ }),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ }),
+ multiview_mask: None,
+ cache: None,
+ });
+ let texture = |pixels: &[u8], width, height| {
+ device.create_texture_with_data(
+ &queue,
+ &wgpu::TextureDescriptor {
+ label: None,
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ },
+ wgpu::util::TextureDataOrder::LayerMajor,
+ pixels,
+ )
+ };
+ // Asymmetric, translucent texels expose UV/winding and blend-order errors.
+ let pixels: Vec = (0..16 * 16)
+ .flat_map(|i| {
+ [
+ (i * 17) as u8,
+ (i * 31) as u8,
+ (i * 7) as u8,
+ (80 + i % 176) as u8,
+ ]
+ })
+ .collect();
+ let atlas = texture(&pixels, 16, 16).create_view(&Default::default());
+ let lightmap = texture(&[255; 4], 1, 1).create_view(&Default::default());
+ let sampler = device.create_sampler(&Default::default());
+ let uniform = device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size: size_of::() as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &pipeline.get_bind_group_layout(0),
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&atlas),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(&lightmap),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
+ });
+ let indices = Renderer::quad_indices(&device, VERTICES / 4 + 1);
+ let mut resident = EndSky::default();
+ let uv = [0.125, 0.25, 0.375, 0.5];
+ resident.prepare(&device, Some(uv));
+ let first = resident.mesh.as_ref().unwrap().1.clone();
+ let render = |sky: &EndSky, flash: &[Vertex], combined: bool| {
+ let target = device.create_texture(&wgpu::TextureDescriptor {
+ label: None,
+ size: wgpu::Extent3d {
+ width: 64,
+ height: 64,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ });
+ let view = target.create_view(&Default::default());
+ let mut vertices = if combined { vertices(uv) } else { Vec::new() };
+ vertices.extend_from_slice(flash);
+ let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: bytemuck::cast_slice(&vertices),
+ usage: wgpu::BufferUsages::VERTEX,
+ });
+ let readback = device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size: 64 * 64 * 4,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ ..Default::default()
+ });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &group, &[]);
+ pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
+ if !combined {
+ sky.draw(&mut pass);
+ }
+ if !vertices.is_empty() {
+ pass.set_vertex_buffer(0, buffer.slice(..));
+ pass.draw_indexed(0..vertices.len() as u32 / 4 * 6, 0, 0..1);
+ }
+ }
+ encoder.copy_texture_to_buffer(
+ target.as_image_copy(),
+ wgpu::TexelCopyBufferInfo {
+ buffer: &readback,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(256),
+ rows_per_image: Some(64),
+ },
+ },
+ target.size(),
+ );
+ queue.submit([encoder.finish()]);
+ readback
+ .slice(..)
+ .map_async(wgpu::MapMode::Read, |r| r.unwrap());
+ device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ readback.slice(..).get_mapped_range().unwrap().to_vec()
+ };
+ let mut cases = 0;
+ let mut visible_flash_cases = 0;
+ for yaw in [0.0_f32, 45.0, 90.0, 180.0, 270.0] {
+ for pitch in [-85.0_f32, -30.0, 0.0, 45.0, 85.0] {
+ let mut globals = Globals::zeroed();
+ globals.view_proj = (Mat4::perspective_rh(90_f32.to_radians(), 1.0, 0.05, 1024.0)
+ * Mat4::from_rotation_x(pitch.to_radians())
+ * Mat4::from_rotation_y(yaw.to_radians()))
+ .to_cols_array_2d();
+ queue.write_buffer(&uniform, 0, bytemuck::bytes_of(&globals));
+ let no_flash = render(&resident, &[], true);
+ for level in [0_u32, 1, 127, 255] {
+ let flash: Vec<_> = if level == 0 {
+ Vec::new()
+ } else {
+ // Same flash size/height, with an arbitrary EndFlashState pose.
+ let pose = Mat4::from_rotation_y(1.3) * Mat4::from_rotation_x(-1.6);
+ [(-60.0, -60.0), (60.0, -60.0), (60.0, 60.0), (-60.0, 60.0)]
+ .map(|(x, z)| Vertex {
+ pos: pose.transform_point3(glam::vec3(x, 100.0, z)).to_array(),
+ uv: [0.75 + x / 480.0, 0.75 + z / 480.0],
+ layer: 2,
+ color: level * 0x01010101,
+ light: 0,
+ normal: [0; 4],
+ })
+ .to_vec()
+ };
+ resident.prepare(&device, Some(uv));
+ let expected = render(&resident, &flash, true);
+ let actual = render(&resident, &flash, false);
+ visible_flash_cases += usize::from(expected != no_flash);
+ assert_eq!(actual, expected, "yaw={yaw} pitch={pitch} flash={level}");
+ assert!(
+ actual.as_chunks::<4>().0.iter().any(|p| p[..3] != [0; 3]),
+ "empty frame"
+ );
+ assert_eq!(resident.mesh.as_ref().unwrap().1, first);
+ cases += 1;
+ }
+ }
+ }
+ assert!(
+ visible_flash_cases > 0,
+ "the flash must affect the comparison"
+ );
+ eprintln!("{cases} combined/resident framebuffer cases matched exactly");
+}
diff --git a/crates/horizon-client/src/gfx/lightning.rs b/crates/horizon-client/src/gfx/lightning.rs
new file mode 100644
index 000000000..251dbf00e
--- /dev/null
+++ b/crates/horizon-client/src/gfx/lightning.rs
@@ -0,0 +1,211 @@
+//! Seeded, bolt-local lightning meshes retained until their last active bolt disappears.
+use crate::{gfx::upload::Uploads, mesher::Vertex};
+use glam::DVec3;
+use horizon_core::random::{LegacyRandom, RandomSource};
+use std::collections::HashMap;
+use wgpu::util::DeviceExt;
+
+/// A bolt's render state. Simulation lifetime and flashes stay in the game.
+#[derive(Clone, Copy)]
+pub struct Bolt {
+ pub at: [f64; 3],
+ pub seed: i64,
+}
+
+#[derive(Default)]
+pub struct Input<'a> {
+ pub bolts: &'a [Bolt],
+ /// Current atlas white texel; a changed rect invalidates retained vertices.
+ pub uv: [f32; 2],
+}
+
+// Four layers, fourteen segments (eight trunk, two branches of three), four quads.
+pub(super) const QUADS: u32 = 4 * 14 * 4;
+
+/// `LightningBoltRenderer.submit`: keep random draws, layers and quad order unchanged.
+fn geometry(seed: i64, uv: [f32; 2]) -> Vec {
+ let mut out = Vec::with_capacity(QUADS as usize * 4);
+ // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
+ let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
+ let mut random = LegacyRandom::new(seed);
+ let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
+ let (mut x_off, mut z_off) = (0f32, 0f32);
+ for i in (0..8).rev() {
+ xs[i] = x_off;
+ zs[i] = z_off;
+ x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
+ z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
+ }
+ for layer in 0..4 {
+ let mut random = LegacyRandom::new(seed);
+ for branch in 0..3 {
+ let trunk = branch == 0;
+ let start = 7 - branch;
+ let end = if trunk { 0 } else { start - 3 + 1 };
+ let mut sx = xs[start] - x_off;
+ let mut sz = zs[start] - z_off;
+ for segment in (end..=start).rev() {
+ let (ex, ez) = (sx, sz);
+ let spread = if trunk { 11 } else { 31 };
+ sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
+ sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
+ let mut top = 0.1 + layer as f32 * 0.2;
+ let mut bottom = top;
+ if trunk {
+ top *= segment as f32 * 0.1 + 1.0;
+ bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
+ }
+ for (rx, rz, lx, lz) in [
+ (false, false, true, false),
+ (true, false, true, true),
+ (true, true, false, true),
+ (false, true, false, false),
+ ] {
+ let s = |p: bool, r: f32| if p { r } else { -r };
+ let y0 = segment as f32 * 16.0;
+ let corners = [
+ [sx + s(rx, bottom), y0, sz + s(rz, bottom)],
+ [ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
+ [ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
+ [sx + s(lx, bottom), y0, sz + s(lz, bottom)],
+ ];
+ for c in corners {
+ out.push(Vertex {
+ normal: [0; 4],
+ pos: c,
+ uv,
+ layer: 2,
+ color,
+ light: 240 | 240 << 8,
+ });
+ }
+ }
+ }
+ }
+ }
+ out
+}
+
+struct Cached {
+ mesh: T,
+ used: bool,
+}
+
+/// Shared seeds use the same mesh; storage is bounded by active unique seeds,
+/// including after seed changes, removals, dimension switches and disconnects.
+struct Cache {
+ uv: Option<[f32; 2]>,
+ meshes: HashMap>,
+}
+impl Cache {
+ fn new() -> Self {
+ Self {
+ uv: None,
+ meshes: HashMap::new(),
+ }
+ }
+
+ fn prepare(&mut self, input: &Input<'_>, mut build: impl FnMut(i64, [f32; 2]) -> T) {
+ if self.uv != Some(input.uv) {
+ self.meshes.clear();
+ self.uv = Some(input.uv);
+ }
+ for cached in self.meshes.values_mut() {
+ cached.used = false;
+ }
+ for bolt in input.bolts {
+ self.meshes
+ .entry(bolt.seed)
+ .or_insert_with(|| Cached {
+ mesh: build(bolt.seed, input.uv),
+ used: true,
+ })
+ .used = true;
+ }
+ self.meshes.retain(|_, cached| cached.used);
+ // HashMap::retain keeps its allocation. Release historical peak capacity
+ // as well as meshes once the storm (or connection) is gone.
+ if self.meshes.is_empty() {
+ self.meshes = HashMap::new();
+ } else if self.meshes.capacity() > self.meshes.len() * 4 {
+ self.meshes.shrink_to_fit();
+ }
+ }
+}
+
+fn offset(bolt: &Bolt, camera: DVec3) -> [f32; 3] {
+ (DVec3::from_array(bolt.at) - camera).as_vec3().to_array()
+}
+
+pub(super) struct Renderer {
+ cache: Cache,
+ instances: Option,
+ capacity: usize,
+}
+impl Renderer {
+ pub(super) fn new() -> Self {
+ Self {
+ cache: Cache::new(),
+ instances: None,
+ capacity: 0,
+ }
+ }
+
+ pub(super) fn prepare(
+ &mut self,
+ device: &wgpu::Device,
+ uploads: &mut Uploads,
+ encoder: &mut wgpu::CommandEncoder,
+ input: &Input<'_>,
+ camera: DVec3,
+ ) {
+ self.cache.prepare(input, |seed, uv| {
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Lightning vertices"),
+ contents: bytemuck::cast_slice(&geometry(seed, uv)),
+ usage: wgpu::BufferUsages::VERTEX,
+ })
+ });
+ if input.bolts.is_empty() {
+ self.instances = None;
+ self.capacity = 0;
+ return;
+ }
+ if input.bolts.len() > self.capacity || input.bolts.len() < self.capacity / 4 {
+ self.capacity = input.bolts.len().next_power_of_two();
+ self.instances = Some(device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("Lightning offsets"),
+ size: (self.capacity * std::mem::size_of::<[f32; 3]>()) as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ }));
+ }
+ let offsets: Vec<_> = input
+ .bolts
+ .iter()
+ .map(|bolt| offset(bolt, camera))
+ .collect();
+ uploads.buffer(
+ encoder,
+ self.instances.as_ref().unwrap(),
+ 0,
+ bytemuck::cast_slice(&offsets),
+ );
+ }
+
+ pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, input: &Input<'_>) {
+ let Some(instances) = &self.instances else {
+ return;
+ };
+ pass.set_vertex_buffer(1, instances.slice(..));
+ // Follow simulation order, including repeated seeds; HashMap order must
+ // never change additive accumulation or the order before dragon rays.
+ for (i, bolt) in input.bolts.iter().enumerate() {
+ pass.set_vertex_buffer(0, self.cache.meshes[&bolt.seed].mesh.slice(..));
+ pass.draw_indexed(0..QUADS * 6, 0, i as u32..i as u32 + 1);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/horizon-client/src/gfx/lightning/tests/mod.rs b/crates/horizon-client/src/gfx/lightning/tests/mod.rs
new file mode 100644
index 000000000..f89f402de
--- /dev/null
+++ b/crates/horizon-client/src/gfx/lightning/tests/mod.rs
@@ -0,0 +1,495 @@
+use super::*;
+use std::cell::Cell;
+
+// Frozen pre-cache generator: compare every Vertex byte, including primitive
+// order and the original camera-relative rounding, without game resources.
+fn reference(seed: i64, at: [f64; 3], camera: DVec3, uv: [f32; 2]) -> Vec {
+ let mut out = Vec::new();
+ // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
+ let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
+ let b = Bolt { seed, at };
+ {
+ let o = (glam::DVec3::from_array(b.at) - camera).as_vec3();
+ let mut random = LegacyRandom::new(b.seed);
+ let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
+ let (mut x_off, mut z_off) = (0f32, 0f32);
+ for i in (0..8).rev() {
+ xs[i] = x_off;
+ zs[i] = z_off;
+ x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
+ z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
+ }
+ for layer in 0..4 {
+ let mut random = LegacyRandom::new(b.seed);
+ for branch in 0..3 {
+ let trunk = branch == 0;
+ let start = 7 - branch;
+ let end = if trunk { 0 } else { start - 3 + 1 };
+ let mut sx = xs[start] - x_off;
+ let mut sz = zs[start] - z_off;
+ for segment in (end..=start).rev() {
+ let (ex, ez) = (sx, sz);
+ let spread = if trunk { 11 } else { 31 };
+ sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
+ sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
+ let mut top = 0.1 + layer as f32 * 0.2;
+ let mut bottom = top;
+ if trunk {
+ top *= segment as f32 * 0.1 + 1.0;
+ bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
+ }
+ for (rx, rz, lx, lz) in [
+ (false, false, true, false),
+ (true, false, true, true),
+ (true, true, false, true),
+ (false, true, false, false),
+ ] {
+ let s = |p: bool, r: f32| if p { r } else { -r };
+ let y0 = segment as f32 * 16.0;
+ let corners = [
+ [sx + s(rx, bottom), y0, sz + s(rz, bottom)],
+ [ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
+ [ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
+ [sx + s(lx, bottom), y0, sz + s(lz, bottom)],
+ ];
+ for c in corners {
+ out.push(Vertex {
+ normal: [0; 4],
+ pos: (o + glam::Vec3::from_array(c)).to_array(),
+ uv,
+ layer: 2,
+ color,
+ light: 240 | 240 << 8,
+ });
+ }
+ }
+ }
+ }
+ }
+ }
+ out
+}
+
+fn seeds() -> Vec {
+ let mut seeds = vec![0, 1, -1, i64::MIN, i64::MAX, 0x123456789abcdef];
+ let mut random = LegacyRandom::new(42);
+ seeds.extend((0..256).map(|_| random.next_long()));
+ seeds
+}
+
+/// Pinned 26.3 LightningBoltRenderer.lambda$submit$0, captured with an
+/// identity PoseStack and a VertexConsumer recording big-endian xyz floats.
+#[test]
+fn geometry_matches_pinned_vanilla_vertex_digest() {
+ use sha2::{Digest, Sha256};
+ let mut digest = Sha256::new();
+ for seed in seeds() {
+ for vertex in geometry(seed, [0.0; 2]) {
+ for value in vertex.pos {
+ digest.update(value.to_be_bytes());
+ }
+ }
+ }
+ assert_eq!(
+ format!("{:x}", digest.finalize()),
+ "a9ed25caa50b9aa340faa4bb417b3d533b061f0dce66514e4bb212931444dee6"
+ );
+}
+
+#[test]
+fn retained_geometry_matches_original_generator() {
+ let uv = [0.8125, 0.03125];
+ for seed in seeds() {
+ let local = geometry(seed, uv);
+ assert_eq!(local.len(), QUADS as usize * 4);
+ for (at, camera) in [
+ ([0.0; 3], DVec3::ZERO),
+ ([12.5, 64.0, -12.5], DVec3::new(-4.25, 71.125, 32.5)),
+ (
+ [29_999_999.5, -64.0, -29_999_999.5],
+ DVec3::new(29_999_987.125, 67.75, -29_999_983.875),
+ ),
+ ] {
+ let offset = offset(&Bolt { seed, at }, camera);
+ let translated: Vec<_> = local
+ .iter()
+ .map(|v| Vertex {
+ pos: (glam::Vec3::from_array(offset) + glam::Vec3::from_array(v.pos))
+ .to_array(),
+ ..*v
+ })
+ .collect();
+ let expected = reference(seed, at, camera, uv);
+ assert_eq!(
+ bytemuck::cast_slice::<_, u8>(&translated),
+ bytemuck::cast_slice::<_, u8>(&expected),
+ "seed {seed}"
+ );
+ }
+ }
+}
+
+#[test]
+fn cache_tracks_seed_lifecycle_movement_and_atlas_reload() {
+ let mut cache = Cache::new();
+ let builds = Cell::new(0);
+ let build = |seed, uv| {
+ builds.set(builds.get() + 1);
+ geometry(seed, uv)
+ };
+ let mut bolts = [
+ Bolt {
+ seed: 123,
+ at: [0.0; 3],
+ },
+ Bolt {
+ seed: 456,
+ at: [1.0; 3],
+ },
+ ];
+ fn input(bolts: &[Bolt]) -> Input<'_> {
+ Input {
+ bolts,
+ uv: [0.25, 0.5],
+ }
+ }
+ cache.prepare(&input(&bolts), build);
+ assert_eq!(builds.get(), 2);
+ assert_eq!(cache.meshes.len(), 2);
+ // Any number of rendered frames or multiplayer position updates reuse meshes.
+ for i in 0..100 {
+ bolts[0].at = [i as f64; 3];
+ cache.prepare(&input(&bolts), build);
+ }
+ assert_eq!(builds.get(), 2);
+ // A flash changes the seed; retire its previous mesh immediately.
+ bolts[0].seed = 789;
+ cache.prepare(&input(&bolts), build);
+ assert_eq!(builds.get(), 3);
+ assert!(!cache.meshes.contains_key(&123));
+ // Removal retains other bolts, and repeated seeds still share geometry.
+ bolts[0].seed = 456;
+ cache.prepare(&input(&bolts), build);
+ assert_eq!(builds.get(), 3);
+ assert_eq!(cache.meshes.len(), 1);
+ // Atlas replacement must update white texel UVs without changing the seed.
+ cache.prepare(
+ &Input {
+ bolts: &bolts,
+ uv: [0.75, 0.25],
+ },
+ build,
+ );
+ assert_eq!(builds.get(), 4);
+ assert_eq!(cache.meshes[&456].mesh[0].uv, [0.75, 0.25]);
+ // Disconnect/dimension switch/expiry drops every retained resource.
+ cache.prepare(&Input::default(), build);
+ assert!(cache.meshes.is_empty());
+ assert_eq!(cache.meshes.capacity(), 0);
+ cache.prepare(&input(&bolts), build);
+ assert_eq!(builds.get(), 5);
+}
+
+#[test]
+fn long_flash_sequence_keeps_only_active_seeds() {
+ let mut cache = Cache::new();
+ for seed in 0..10_000 {
+ cache.prepare(
+ &Input {
+ bolts: &[Bolt { seed, at: [0.0; 3] }],
+ uv: [0.0; 2],
+ },
+ |seed, _| seed,
+ );
+ assert_eq!(cache.meshes.len(), 1);
+ assert_eq!(cache.meshes[&seed].mesh, seed);
+ assert!(cache.meshes.capacity() < 16);
+ }
+}
+
+/// Exercise the actual entity shader and retained draw path offscreen. Run
+/// explicitly, separately from other headless device tests (some GPU drivers
+/// fail during concurrent device teardown). Machines without an adapter skip it.
+#[test]
+#[ignore = "requires GPU; run separately with --ignored --exact"]
+fn retained_gpu_draw_matches_transient_additive_draw() {
+ use bytemuck::Zeroable;
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
+ let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
+ eprintln!("no GPU adapter: skipped");
+ return;
+ };
+ eprintln!("lightning differential GPU: {}", adapter.get_info().name);
+ let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).unwrap();
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("Lightning differential shader"),
+ source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()),
+ });
+ let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4];
+ let offsets = wgpu::vertex_attr_array![6=>Float32x3];
+ let vertices = [Some(wgpu::VertexBufferLayout {
+ array_stride: std::mem::size_of::() as u64,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &attributes,
+ })];
+ let retained_vertices = [
+ vertices[0].clone(),
+ Some(wgpu::VertexBufferLayout {
+ array_stride: 12,
+ step_mode: wgpu::VertexStepMode::Instance,
+ attributes: &offsets,
+ }),
+ ];
+ let pipelines: Vec<_> = [false, true]
+ .into_iter()
+ .map(|retained| {
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Lightning differential pipeline"),
+ layout: None,
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some(if retained {
+ "vs_lightning"
+ } else {
+ "vs_entity"
+ }),
+ compilation_options: Default::default(),
+ buffers: if retained {
+ &retained_vertices
+ } else {
+ &vertices
+ },
+ },
+ primitive: wgpu::PrimitiveState {
+ cull_mode: None,
+ ..Default::default()
+ },
+ depth_stencil: Some(wgpu::DepthStencilState {
+ format: wgpu::TextureFormat::Depth32Float,
+ depth_write_enabled: Some(false),
+ depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
+ stencil: Default::default(),
+ bias: Default::default(),
+ }),
+ multisample: Default::default(),
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_celestial"),
+ compilation_options: Default::default(),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: Some(wgpu::BlendState {
+ color: wgpu::BlendComponent {
+ src_factor: wgpu::BlendFactor::SrcAlpha,
+ dst_factor: wgpu::BlendFactor::One,
+ operation: wgpu::BlendOperation::Add,
+ },
+ alpha: wgpu::BlendComponent {
+ src_factor: wgpu::BlendFactor::SrcAlpha,
+ dst_factor: wgpu::BlendFactor::One,
+ operation: wgpu::BlendOperation::Add,
+ },
+ }),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ }),
+ multiview_mask: None,
+ cache: None,
+ })
+ })
+ .collect();
+ let globals = crate::gfx::Globals {
+ view_proj: (glam::Mat4::orthographic_rh(-100.0, 100.0, -10.0, 150.0, 0.1, 400.0)
+ * glam::Mat4::look_at_rh(
+ glam::Vec3::new(80.0, 30.0, 160.0),
+ glam::Vec3::new(0.0, 60.0, 0.0),
+ glam::Vec3::Y,
+ ))
+ .to_cols_array_2d(),
+ ..crate::gfx::Globals::zeroed()
+ };
+ let globals = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: bytemuck::bytes_of(&globals),
+ usage: wgpu::BufferUsages::UNIFORM,
+ });
+ let size = wgpu::Extent3d {
+ width: 256,
+ height: 256,
+ depth_or_array_layers: 1,
+ };
+ let texture = |format, usage| {
+ device.create_texture(&wgpu::TextureDescriptor {
+ label: None,
+ size,
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage,
+ view_formats: &[],
+ })
+ };
+ let white = device
+ .create_texture_with_data(
+ &queue,
+ &wgpu::TextureDescriptor {
+ label: None,
+ size: wgpu::Extent3d {
+ width: 1,
+ height: 1,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ },
+ wgpu::util::TextureDataOrder::LayerMajor,
+ &[255; 4],
+ )
+ .create_view(&Default::default());
+ let sampler = device.create_sampler(&Default::default());
+ let groups: Vec<_> = pipelines
+ .iter()
+ .map(|pipeline| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &pipeline.get_bind_group_layout(0),
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: globals.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&white),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(&white),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
+ })
+ })
+ .collect();
+ let mut renderer = Renderer::new();
+ let mut uploads = Uploads::new(&device);
+ let mut bolts = [Bolt {
+ seed: 123,
+ at: [29_999_999.5, 64.0, -29_999_999.5],
+ }; 3];
+ bolts[1].seed = -456;
+ bolts[1].at[0] -= 32.0;
+ bolts[2].at[2] += 20.0;
+ let indices = crate::gfx::Renderer::quad_indices(&device, QUADS * 3);
+ for frame in 0..4 {
+ let camera = DVec3::new(29_999_997.125 + frame as f64, 62.75, -29_999_998.875);
+ if frame == 2 {
+ bolts[0].seed = 789;
+ }
+ let input = Input {
+ bolts: &bolts[..if frame == 3 { 1 } else { 3 }],
+ uv: if frame == 3 { [0.75; 2] } else { [0.5; 2] },
+ };
+ let expected: Vec<_> = input
+ .bolts
+ .iter()
+ .flat_map(|bolt| reference(bolt.seed, bolt.at, camera, input.uv))
+ .collect();
+ let transient = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: bytemuck::cast_slice(&expected),
+ usage: wgpu::BufferUsages::VERTEX,
+ });
+ let mut encoder = device.create_command_encoder(&Default::default());
+ renderer.prepare(&device, &mut uploads, &mut encoder, &input, camera);
+ let mut readbacks = Vec::new();
+ for mode in 0..2 {
+ let color = texture(
+ wgpu::TextureFormat::Rgba8Unorm,
+ wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ );
+ let view = color.create_view(&Default::default());
+ let depth = texture(
+ wgpu::TextureFormat::Depth32Float,
+ wgpu::TextureUsages::RENDER_ATTACHMENT,
+ )
+ .create_view(&Default::default());
+ {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ resolve_target: None,
+ depth_slice: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
+ view: &depth,
+ depth_ops: Some(wgpu::Operations {
+ load: wgpu::LoadOp::Clear(0.0),
+ store: wgpu::StoreOp::Discard,
+ }),
+ stencil_ops: None,
+ }),
+ ..Default::default()
+ });
+ pass.set_pipeline(&pipelines[mode]);
+ pass.set_bind_group(0, &groups[mode], &[]);
+ pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
+ if mode == 0 {
+ pass.set_vertex_buffer(0, transient.slice(..));
+ pass.draw_indexed(0..expected.len() as u32 / 4 * 6, 0, 0..1);
+ } else {
+ renderer.draw(&mut pass, &input);
+ }
+ }
+ let read = device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size: 256 * 256 * 4,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ encoder.copy_texture_to_buffer(
+ color.as_image_copy(),
+ wgpu::TexelCopyBufferInfo {
+ buffer: &read,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(1024),
+ rows_per_image: None,
+ },
+ },
+ size,
+ );
+ readbacks.push(read);
+ }
+ uploads.finish(&encoder);
+ queue.submit([encoder.finish()]);
+ for read in &readbacks {
+ read.slice(..)
+ .map_async(wgpu::MapMode::Read, |r| r.unwrap());
+ }
+ device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ let pixels: Vec> = readbacks
+ .iter()
+ .map(|read| read.slice(..).get_mapped_range().unwrap().to_vec())
+ .collect();
+ assert!(pixels[0].iter().any(|&b| b != 0), "empty reference frame");
+ assert_eq!(pixels[0], pixels[1], "frame {frame}: GPU output differs");
+ }
+}
diff --git a/crates/horizon-client/src/gfx/weather.rs b/crates/horizon-client/src/gfx/weather.rs
new file mode 100644
index 000000000..15886b8f2
--- /dev/null
+++ b/crates/horizon-client/src/gfx/weather.rs
@@ -0,0 +1,330 @@
+//! Weather's unsplit quads, using the entity atlas/lightmap resources.
+use crate::weather::{Time, Vertex};
+
+pub(super) struct Weather {
+ pipeline: wgpu::RenderPipeline,
+ group: wgpu::BindGroup,
+ uniform: wgpu::Buffer,
+ vertices: wgpu::Buffer,
+ capacity: usize,
+ count: u32,
+}
+impl Weather {
+ pub fn new(
+ device: &wgpu::Device,
+ format: wgpu::TextureFormat,
+ entities: &wgpu::BindGroupLayout,
+ shader: &wgpu::ShaderModule,
+ ) -> Self {
+ let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Weather time"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::VERTEX,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+ let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Weather layout"),
+ bind_group_layouts: &[Some(entities), Some(&bindings)],
+ ..Default::default()
+ });
+ let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Float32x4,
+ 3=>Float32x4,4=>Uint32x4,5=>Unorm8x4,6=>Uint8x4,7=>Uint32];
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Weather"),
+ layout: Some(&layout),
+ vertex: wgpu::VertexState {
+ module: shader,
+ entry_point: Some("vs_weather"),
+ compilation_options: Default::default(),
+ buffers: &[Some(wgpu::VertexBufferLayout {
+ array_stride: std::mem::size_of::() as u64,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &attributes,
+ })],
+ },
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ ..Default::default()
+ },
+ depth_stencil: Some(wgpu::DepthStencilState {
+ format: wgpu::TextureFormat::Depth32Float,
+ depth_write_enabled: Some(true),
+ depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
+ stencil: Default::default(),
+ bias: Default::default(),
+ }),
+ multisample: Default::default(),
+ fragment: Some(wgpu::FragmentState {
+ module: shader,
+ entry_point: Some("fs_weather"),
+ compilation_options: Default::default(),
+ targets: &[Some(wgpu::ColorTargetState {
+ format,
+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ }),
+ multiview_mask: None,
+ cache: None,
+ });
+ let uniform = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("Weather time"),
+ size: 16,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Weather time"),
+ layout: &bindings,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 1,
+ resource: uniform.as_entire_binding(),
+ }],
+ });
+ Self {
+ pipeline,
+ group,
+ uniform,
+ vertices: Self::buffer(device, 4),
+ capacity: 4,
+ count: 0,
+ }
+ }
+ fn buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("Weather vertices"),
+ size: (capacity * std::mem::size_of::()) as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ })
+ }
+ pub fn prepare(
+ &mut self,
+ device: &wgpu::Device,
+ encoder: &mut wgpu::CommandEncoder,
+ uploads: &mut super::upload::Uploads,
+ vertices: &[Vertex],
+ time: Time,
+ ) {
+ self.count = vertices.len() as u32;
+ if vertices.is_empty() {
+ return;
+ }
+ if vertices.len() > self.capacity {
+ self.capacity = vertices.len().next_power_of_two();
+ self.vertices = Self::buffer(device, self.capacity);
+ }
+ uploads.buffer(encoder, &self.vertices, 0, bytemuck::cast_slice(vertices));
+ uploads.buffer(encoder, &self.uniform, 0, bytemuck::bytes_of(&time));
+ }
+ pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>, entities: &wgpu::BindGroup) {
+ if self.count == 0 {
+ return;
+ }
+ pass.set_pipeline(&self.pipeline);
+ pass.set_bind_group(0, entities, &[]);
+ pass.set_bind_group(1, &self.group, &[]);
+ pass.set_vertex_buffer(0, self.vertices.slice(..));
+ // The renderer binds the shared triangle-list quad indices.
+ pass.draw_indexed(0..self.count / 4 * 6, 0, 0..1);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::weather::{Parameters, Time};
+ use wgpu::util::DeviceExt;
+
+ #[repr(C)]
+ #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+ struct Case {
+ animation: [f32; 4],
+ bases: [u32; 4],
+ time: [f32; 4],
+ uv: [f32; 2],
+ snow: u32,
+ _pad: u32,
+ }
+
+ /// Execute the production WGSL math, rather than a Rust translation of it.
+ /// Requires a GPU; run explicitly on renderer changes, not on headless CI.
+ #[test]
+ #[ignore = "requires a Vulkan/Metal/DX12 adapter"]
+ fn weather_shader_uvs_match_legacy_bits() {
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
+ let adapter =
+ pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
+ .unwrap();
+ eprintln!("weather parity adapter: {:?}", adapter.get_info());
+ let (device, queue) =
+ pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap();
+ let mut cases = Vec::new();
+ let mut expected = Vec::new();
+ for i in 0..4096i32 {
+ let x = i.wrapping_mul(45_238_971);
+ let z = i.wrapping_mul(-418_711).wrapping_add(i32::MIN);
+ let p = Parameters::new(x, z);
+ let bases = p.snow_base.map(f64::to_bits);
+ for ticks in [-1, 0, 511, 512, 131_071, 131_072, i64::MAX] {
+ let partial = [0.0, 0.5, 0.999, f32::from_bits(0x3f7fffff)][i as usize % 4];
+ for snow in [false, true] {
+ let column = p.column(snow, ticks, x, -64, 320, z, 0, partial);
+ let uv = [1.0, if i & 1 == 0 { -16.0 } else { 80.0 }];
+ cases.push(Case {
+ animation: [
+ p.rain_speed,
+ p.rain_tick_offset,
+ p.snow_drift[0],
+ p.snow_drift[1],
+ ],
+ bases: [
+ bases[0] as u32,
+ (bases[0] >> 32) as u32,
+ bases[1] as u32,
+ (bases[1] >> 32) as u32,
+ ],
+ time: Time::new(ticks, partial).values,
+ uv,
+ snow: u32::from(snow),
+ _pad: 0,
+ });
+ expected.push([
+ (uv[0] + column.u_offset).to_bits(),
+ (uv[1] + column.v_offset).to_bits(),
+ ]);
+ }
+ }
+ }
+ // Force halfway rounding, cancellation, zero, tiny bases and either
+ // sign of drift. Gaussian seeds alone rarely land on exact midpoints.
+ for base in [
+ 0.0,
+ 2.0f64.powi(-53),
+ 0.5,
+ 0.5 + 2.0f64.powi(-25),
+ 0.5 + 2.0f64.powi(-25) + 2.0f64.powi(-53),
+ 0.5 + 2.0f64.powi(-14) + 2.0f64.powi(-53),
+ 1.0 - 2.0f64.powi(-53),
+ ] {
+ for delta in [0.0f32, -0.0, -0.5, 0.5, 1024.0, -1024.0, 2.0f32.powi(-40)] {
+ // time=100, u scale=.01 -> delta exactly, v is unused.
+ let bits = base.to_bits();
+ cases.push(Case {
+ animation: [3.0, 0.0, delta, 0.0],
+ bases: [bits as u32, (bits >> 32) as u32, 0, 0],
+ time: [100.0, 0.0, 0.0, 0.0],
+ uv: [0.0, 0.0],
+ snow: 1,
+ _pad: 0,
+ });
+ expected.push([((base + f64::from(delta)) as f32).to_bits(), 0]);
+ }
+ }
+ let expected: Vec<[u32; 4]> = expected
+ .into_iter()
+ .map(|bits| {
+ let uv = bits.map(f32::from_bits);
+ let texel = [
+ 256 + ((uv[0] - uv[0].floor()) * 16.0).floor() as u32,
+ 512 + ((uv[1] - uv[1].floor()) * 32.0).floor() as u32,
+ ];
+ [bits[0], bits[1], texel[0], texel[1]]
+ })
+ .collect();
+ let math = include_str!("../entity.wgsl")
+ .split("// WEATHER_MATH_BEGIN")
+ .nth(1)
+ .unwrap()
+ .split("// WEATHER_MATH_END")
+ .next()
+ .unwrap();
+ let source = format!(
+ "{math}\n{}",
+ r#"
+struct Case { animation: vec4, bases: vec4, time: vec4, uv: vec2, snow: u32, pad: u32 }
+@group(0) @binding(0) var cases: array;
+@group(0) @binding(1) var results: array>;
+@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) {
+ if id.x >= arrayLength(&cases) { return; }
+ let c = cases[id.x];
+ let uv = c.uv + weather_phase(c.animation, c.bases, c.snow, c.time);
+ let texel = weather_texel(uv, vec4(0.25, 0.5, 0.015625, 0.03125), vec2(1024u));
+ results[id.x] = vec4(bitcast>(uv), vec2(texel));
+}"#
+ );
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("Weather parity"),
+ source: wgpu::ShaderSource::Wgsl(source.into()),
+ });
+ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("Weather parity"),
+ layout: None,
+ module: &shader,
+ entry_point: Some("main"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: bytemuck::cast_slice(&cases),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let size = (expected.len() * 16) as u64;
+ let output = device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ mapped_at_creation: false,
+ });
+ let readback = device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &pipeline.get_bind_group_layout(0),
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: input.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: output.as_entire_binding(),
+ },
+ ],
+ });
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &group, &[]);
+ pass.dispatch_workgroups((cases.len() as u32).div_ceil(64), 1, 1);
+ }
+ encoder.copy_buffer_to_buffer(&output, 0, &readback, 0, size);
+ queue.submit([encoder.finish()]);
+ let (tx, rx) = std::sync::mpsc::channel();
+ readback.map_async(wgpu::MapMode::Read, .., move |r| tx.send(r).unwrap());
+ device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ rx.recv().unwrap().unwrap();
+ let mapped = readback.get_mapped_range(..).unwrap();
+ let actual: &[[u32; 4]] = bytemuck::cast_slice(&mapped);
+ for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
+ assert_eq!(
+ actual, expected,
+ "case {i}, snow={}, time={:?}, animation={:?}",
+ cases[i].snow, cases[i].time, cases[i].animation
+ );
+ }
+ eprintln!("{} GPU weather UV cases matched bit for bit", cases.len());
+ }
+}
diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs
index bea0ffaa9..2541168d1 100644
--- a/crates/horizon-client/src/graphics.rs
+++ b/crates/horizon-client/src/graphics.rs
@@ -204,8 +204,6 @@ pub struct Graphics {
pub resolution_scale: u32,
/// FXAA over the world.
pub fxaa: bool,
- /// The settings level last shown: Advanced, or Simple.
- pub advanced: bool,
/// Battery mode: at most 60 frames per second in a world and 30 in menus
/// or behind other windows, and half the worker threads. Off by default;
/// it changes when frames are drawn, never what they show or the ticks.
@@ -236,7 +234,6 @@ impl Default for Graphics {
overlay: Overlay::Off,
resolution_scale: 100,
fxaa: false,
- advanced: false,
battery: false,
shader_pack: String::new(),
api: GraphicsApi::Auto,
@@ -288,7 +285,6 @@ impl Graphics {
"workers" => g.workers = number(g.workers).min(64),
"resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200),
"fxaa" => g.fxaa = flag(g.fxaa),
- "level" => g.advanced = value == "advanced",
"batteryMode" => g.battery = flag(g.battery),
"shaderPack" => g.shader_pack = value.to_string(),
"graphicsApi" => g.api = GraphicsApi::from_name(value).unwrap_or_default(),
@@ -306,7 +302,7 @@ impl Graphics {
}
pub fn serialize(&self) -> String {
format!(
- "preset:{}\nlodDistance:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\ngraphicsApi:{}\n",
+ "preset:{}\nlodDistance:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nbatteryMode:{}\nshaderPack:{}\ngraphicsApi:{}\n",
self.preset.name(),
self.lod_distance,
bool_text(self.cave_culling),
@@ -331,7 +327,6 @@ impl Graphics {
},
self.resolution_scale,
bool_text(self.fxaa),
- if self.advanced { "advanced" } else { "simple" },
bool_text(self.battery),
self.shader_pack,
self.api.name(),
@@ -425,13 +420,14 @@ mod tests {
overlay: Overlay::Graph,
resolution_scale: 75,
fxaa: true,
- advanced: true,
battery: true,
shader_pack: "horizon-sample".into(),
api: GraphicsApi::Dx12,
};
assert_eq!(Graphics::parse(&g.serialize()), g);
assert_eq!(Graphics::parse(""), Graphics::default());
+ // The old menus' Simple / Advanced choice is ignored.
+ assert_eq!(Graphics::parse("level:advanced\n"), Graphics::default());
assert_eq!(
Graphics::parse("workers:abc\nsky:maybe\ncullLeaves:maybe\nentityCulling:maybe\n"),
Graphics::default()
diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs
index 9722ddc21..fddca6f2e 100644
--- a/crates/horizon-client/src/graphics_ui.rs
+++ b/crates/horizon-client/src/graphics_ui.rs
@@ -285,7 +285,7 @@ pub fn rows(level: Level) -> Vec {
const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384];
-/// Classic's submenus supplement the vanilla options on their parent screens.
+/// Horizon's graphics screens supplement the vanilla options on Video Settings.
fn extra_rows(level: Level) -> Vec {
let mut rows = rows(level);
rows.retain(|row| !matches!(row, Row::Setting(s) if matches!(s.item, Item::Vanilla(_))));
@@ -444,7 +444,7 @@ fn max_workers() -> u32 {
}
impl Item {
- /// On/off settings, drawn as switches by the Horizon menus.
+ /// On/off settings and their value.
pub fn switch(self, s: &Settings) -> Option {
let g = &s.horizon;
Some(match self {
diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs
index 0cc99b07b..8537baa61 100644
--- a/crates/horizon-client/src/hud.rs
+++ b/crates/horizon-client/src/hud.rs
@@ -30,8 +30,10 @@ pub struct HudAtlas {
}
/// Atlas rows reserved for glyphs rasterized at run time.
pub const GLYPH_ROWS: u32 = 512;
-/// 128x128 atlas slots for map textures.
-pub const MAP_SLOTS: usize = 16;
+/// 128x128 atlas slots for map textures. A lobby paints its signs as walls of
+/// framed maps, so the pool holds a wall; too few slots re-upload every map
+/// every frame. 26.3's `MapTextureManager` keeps a texture per map instead.
+pub const MAP_SLOTS: usize = 256;
/// The atlas slot the minimap extra draws into.
pub const MINIMAP_SPRITE: &str = "horizon/minimap";
/// Atlas slots for downloaded player skins (`skins/`), 64x64 each.
@@ -158,7 +160,7 @@ impl HudAtlas {
)
}
/// Empty slots written at run time: map textures (game/maps.rs), the
- /// minimap, downloaded skins, world icons and the Horizon menu text.
+ /// minimap, downloaded skins, world icons and the on-screen keyboard's text.
fn slots(images: &mut Vec) {
for i in 0..MAP_SLOTS {
images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4]));
@@ -182,7 +184,7 @@ impl HudAtlas {
vec![0; 64 * 64 * 4],
));
}
- // Horizon-style menu text and corner masks (ui_theme), rasterized at run time.
+ // The on-screen keyboard's text and corner masks (ui_theme), rasterized at run time.
images.push((
"horizon/ui-text".into(),
2048,
@@ -363,6 +365,8 @@ pub struct HudBatch {
pub patches: Vec,
/// Vertex ranges with another blend or depth/scissor state, in order.
pub blends: Vec<(std::ops::Range, Blend)>,
+ /// Screen's first vertex: the preceding HUD is part of its blurred background.
+ pub blur_at: u32,
}
/// How a run of HUD vertices blends and tests depth.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -398,6 +402,7 @@ impl HudBatch {
height: (window[1] as f32 / scale as f32).ceil(),
patches: Vec::new(),
blends: Vec::new(),
+ blur_at: 0,
}
}
/// Draw the vertices added since `start` with the inverting blend.
@@ -450,6 +455,14 @@ impl HudBatch {
}
out
}
+ fn runs_in(&self, vertices: std::ops::Range) -> Vec<(std::ops::Range, Blend)> {
+ let mut runs = self.runs();
+ for (range, _) in &mut runs {
+ *range = range.start.max(vertices.start)..range.end.min(vertices.end);
+ }
+ runs.retain(|(range, _)| !range.is_empty());
+ runs
+ }
/// `AbstractContainerScreen.init`: center in integer GUI coordinates.
pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) {
(
@@ -1078,7 +1091,26 @@ impl HudRenderer {
batch: &HudBatch,
size: [u32; 2],
) {
- if batch.vertices.is_empty() || size.contains(&0) {
+ self.draw_range(
+ encoder,
+ target,
+ depth,
+ batch,
+ size,
+ 0..batch.vertices.len() as u32,
+ );
+ }
+ /// Draw part of the prepared batch, preserving its blend/depth runs.
+ pub fn draw_range(
+ &self,
+ encoder: &mut wgpu::CommandEncoder,
+ target: &wgpu::TextureView,
+ depth: &wgpu::TextureView,
+ batch: &HudBatch,
+ size: [u32; 2],
+ vertices: std::ops::Range,
+ ) {
+ if vertices.is_empty() || size.contains(&0) {
return;
}
let attachments = [Some(wgpu::RenderPassColorAttachment {
@@ -1090,7 +1122,7 @@ impl HudRenderer {
store: wgpu::StoreOp::Store,
},
})];
- let runs = batch.runs();
+ let runs = batch.runs_in(vertices);
let mut at = 0;
while at < runs.len() {
let clip = match runs[at].1 {
@@ -1329,6 +1361,33 @@ mod tests {
]
);
}
+
+ #[test]
+ fn blur_boundary_splits_blend_runs_without_losing_or_repeating_vertices() {
+ let mut batch = HudBatch::new([854, 480]);
+ for _ in 0..5 {
+ batch.quad([[0.0; 2]; 4], [[0.0; 2]; 4], 0);
+ }
+ batch.blends = vec![
+ (6..18, Blend::Invert),
+ (18..24, Blend::Depth([0, 0, 10, 10])),
+ ];
+ for split in [0, 6, 12, 18, 24, 30] {
+ let before = batch.runs_in(0..split);
+ let after = batch.runs_in(split..30);
+ let actual: Vec<_> = before
+ .into_iter()
+ .chain(after)
+ .flat_map(|(range, blend)| range.map(move |v| (v, blend)))
+ .collect();
+ let expected: Vec<_> = batch
+ .runs()
+ .into_iter()
+ .flat_map(|(range, blend)| range.map(move |v| (v, blend)))
+ .collect();
+ assert_eq!(actual, expected, "blur at {split}");
+ }
+ }
#[test]
fn container_origins_use_java_integer_division() {
// Odd scaled dimensions, odd image sizes and an oversized panel.
@@ -1340,6 +1399,7 @@ mod tests {
height: height as f32,
patches: Vec::new(),
blends: Vec::new(),
+ blur_at: 0,
};
for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] {
assert_eq!(
diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs
index 2ba8d39a9..1376dde98 100644
--- a/crates/horizon-client/src/item_data.rs
+++ b/crates/horizon-client/src/item_data.rs
@@ -302,7 +302,10 @@ fn filterable_text(t: &Tag) -> Option {
fn read_text(t: &Tag) -> Option {
match t {
Tag::String(s) => Some(s.to_string_lossy()),
- Tag::Compound(_) => t.get("text").and_then(string),
+ // A component's root `text` may be empty with the visible words in
+ // `extra` (every legacy display name ViaVersion produces looks like
+ // this), so flatten the whole component instead of reading one key.
+ Tag::Compound(_) => Some(crate::entity_nbt::name_text(t).plain()),
_ => None,
}
}
@@ -860,6 +863,26 @@ mod tests {
assert_eq!(back.custom_name(), Some("Blade"));
}
+ #[test]
+ fn custom_name_reads_the_extra_spans() {
+ let name = Tag::compound([
+ (
+ "extra",
+ Tag::List(vec![
+ Tag::compound([("text", Tag::String("Games ".into()))]),
+ Tag::compound([("text", Tag::String("Right click".into()))]),
+ ]),
+ ),
+ ("text", Tag::String("".into())),
+ ]);
+ let components = Tag::compound([("minecraft:custom_name", name)]);
+ let (_, extra) = decode_components(Some(&components));
+ assert_eq!(
+ extra.and_then(|d| d.custom_name.clone()).as_deref(),
+ Some("Games Right click")
+ );
+ }
+
#[test]
fn banner_layers_and_shield_base_round_trip() {
let mut stack = ItemStack::new("minecraft:shield", 1);
diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs
index 0fc9910d1..ca6ff481b 100644
--- a/crates/horizon-client/src/item_tooltip.rs
+++ b/crates/horizon-client/src/item_tooltip.rs
@@ -486,10 +486,28 @@ pub fn lines(
translate: &dyn Fn(&str) -> Option,
) -> Vec {
let mut lines = vec![name_line(stack, translate)];
+ if TooltipDisplay::for_stack(stack).shows("minecraft:lore") {
+ lines.extend(lore_lines(stack));
+ }
lines.extend(detail_lines(stack, info, translate));
lines
}
+/// `LoreComponent.addToTooltip`: the saved component lines, as plain text.
+fn lore_lines(stack: &ItemStack) -> Vec {
+ let Some(Tag::List(entries)) = stack.data().and_then(|d| d.other("minecraft:lore")) else {
+ return Vec::new();
+ };
+ entries
+ .iter()
+ .map(|entry| {
+ let json = crate::scoreboard::tag_to_json(entry);
+ let text = crate::component::to_text(&json, &mut |s| crate::text::Text::literal(s));
+ text.plain()
+ })
+ .collect()
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -591,6 +609,65 @@ mod tests {
assert!(container_lines(&ItemStack::new("minecraft:chest", 1), &name, &lang).is_empty());
}
+ #[test]
+ fn fireworks_use_loaded_tooltip_translations() {
+ let root = std::env::temp_dir().join(format!(
+ "horizon-firework-tooltip-language-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos(),
+ ));
+ let dir = root.join("assets/minecraft/lang");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(
+ dir.join("en_us.json"),
+ serde_json::to_vec(&serde_json::json!({
+ "item.minecraft.firework_rocket.flight_duration": "Flight Duration: %s",
+ "item.minecraft.firework_rocket.multiple_stars": "%s x %s",
+ "item.minecraft.firework_star.shape.small_ball": "Small Ball",
+ "item.minecraft.firework_star.red": "Red",
+ "item.minecraft.firework_star.custom_color": "Custom",
+ "item.minecraft.firework_star.fade_to": "Fade to",
+ "item.minecraft.firework_star.trail": "Trail",
+ "item.minecraft.firework_star.flicker": "Twinkle",
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ let enchantments = crate::enchant::Enchantments::load(&root);
+ std::fs::remove_dir_all(&root).unwrap();
+ let translate = |key: &str| enchantments.translate(key).map(str::to_owned);
+ let mut rocket = ItemStack::new("minecraft:firework_rocket", 1);
+ assert_eq!(firework_lines(&rocket, &translate), ["Flight Duration: 1"]);
+ let explosion = crate::particles::FireworkExplosion {
+ colors: vec![0xB3312C],
+ fade: vec![0x123456],
+ trail: true,
+ twinkle: true,
+ ..Default::default()
+ };
+ rocket.data_mut().fireworks = Some((3, vec![explosion.clone(), explosion.clone()]));
+ assert_eq!(
+ firework_lines(&rocket, &translate),
+ [
+ "Flight Duration: 3",
+ "2 x Small Ball",
+ " Red",
+ " Fade to Custom",
+ " Trail",
+ " Twinkle",
+ ]
+ );
+ let mut star = ItemStack::new("minecraft:firework_star", 1);
+ star.data_mut().firework_explosion = Some(explosion);
+ assert_eq!(
+ firework_lines(&star, &translate),
+ ["Small Ball", "Red", "Fade to Custom", "Trail", "Twinkle"]
+ );
+ }
+
#[test]
fn amounts_use_two_decimals_at_most() {
assert_eq!(format_amount(8.0), "8");
diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs
index 4be5aa29f..1916344bb 100644
--- a/crates/horizon-client/src/lan/guest.rs
+++ b/crates/horizon-client/src/lan/guest.rs
@@ -71,6 +71,13 @@ pub struct Guest {
/// The permission level (0 none, 2 game masters, 4 owners).
pub permission: u8,
pub sneaking: bool,
+ /// The last `ServerboundPlayerInputPacket` flags (forward 1, backward 2,
+ /// left 4, right 8, jump 16, shift 32, sprint 64).
+ pub input: u8,
+ /// The boat or minecart the player rides (`Entity.getVehicle`).
+ pub vehicle: Option,
+ /// `ServerGamePacketListenerImpl.lastGoodX/Y/Z` of the vehicle it controls.
+ pub vehicle_good: Option<[f64; 3]>,
pub sprinting: bool,
pub fall_flying: bool,
pub flying: bool,
@@ -233,6 +240,9 @@ impl Guest {
game_mode: SURVIVAL,
permission: 0,
sneaking: false,
+ input: 0,
+ vehicle: None,
+ vehicle_good: None,
sprinting: false,
fall_flying: false,
flying: false,
diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs
index af0c1ac83..8d7b5e29a 100644
--- a/crates/horizon-client/src/lan/hub.rs
+++ b/crates/horizon-client/src/lan/hub.rs
@@ -242,6 +242,30 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool {
dx * dx + dz * dz < i64::from(r) * i64::from(r)
}
+/// The view's queue around a new centre: the queued chunks still tracked, then
+/// the tracked ones neither sent nor queued, closest first (a stable sort, so
+/// equally close chunks keep their order).
+fn requeue(
+ queue: &mut Vec<(i32, i32)>,
+ sent: &crate::fast_hash::FxHashSet<(i32, i32)>,
+ (cx, cz): (i32, i32),
+ r: i32,
+) {
+ queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
+ // A walking player changes chunk every few ticks with hundreds of chunks
+ // queued: a set, not a scan of the queue for each of the view's chunks.
+ let mut queued: crate::fast_hash::FxHashSet<(i32, i32)> = queue.iter().copied().collect();
+ for dz in -r - 2..=r + 2 {
+ for dx in -r - 2..=r + 2 {
+ let key = (cx + dx, cz + dz);
+ if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && queued.insert(key) {
+ queue.push(key);
+ }
+ }
+ }
+ queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
+}
+
/// What a level's players were last told of its clock and weather.
#[derive(Clone, Copy)]
struct LevelSync {
@@ -1295,20 +1319,7 @@ impl Hub {
g.sent_chunks.remove(&(x, z));
g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] }));
}
- g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
- for dz in -r - 2..=r + 2 {
- for dx in -r - 2..=r + 2 {
- let key = (cx + dx, cz + dz);
- if tracked(cx, cz, r, key.0, key.1)
- && !g.sent_chunks.contains(&key)
- && !g.chunk_queue.contains(&key)
- {
- g.chunk_queue.push(key);
- }
- }
- }
- g.chunk_queue
- .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
+ requeue(&mut g.chunk_queue, &g.sent_chunks, (cx, cz), r);
}
/// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first,
@@ -1957,6 +1968,7 @@ impl Hub {
g.center = None;
}
S::PlayerInput(p) => {
+ self.guests[i].input = p.flags;
self.guests[i].sneaking = p.flags & 32 != 0;
self.guests[i].sprinting = p.flags & 64 != 0 && p.flags & 1 != 0;
}
@@ -2039,6 +2051,11 @@ impl Hub {
to[2].clamp(-3.0E7, 3.0E7),
];
let (yaw, pitch) = (wrap_degrees(yaw), wrap_degrees(pitch));
+ // A passenger only turns: its vehicle carries it (absSnapTo where it is).
+ if g.vehicle.is_some() {
+ (g.yaw, g.pitch) = (yaw, pitch);
+ return;
+ }
let d = [0, 1, 2].map(|k| to[k] - g.first_good[k]);
let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if g.sleeping {
@@ -2485,3 +2502,76 @@ fn ticking_state(rate: f32, frozen: bool) -> C {
w.bool(frozen);
raw(ids::TICKING_STATE, w.data)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::fast_hash::FxHashSet;
+
+ /// `requeue` as it was, scanning the queue for each chunk of the view.
+ fn requeue_scan(
+ queue: &mut Vec<(i32, i32)>,
+ sent: &FxHashSet<(i32, i32)>,
+ (cx, cz): (i32, i32),
+ r: i32,
+ ) {
+ queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
+ for dz in -r - 2..=r + 2 {
+ for dx in -r - 2..=r + 2 {
+ let key = (cx + dx, cz + dz);
+ if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && !queue.contains(&key)
+ {
+ queue.push(key);
+ }
+ }
+ }
+ queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
+ }
+
+ /// A player walking a loop, sending a few chunks a tick: the queue
+ /// after every move is the one the scan built.
+ #[test]
+ fn requeue_matches_the_scan() {
+ for r in [2, 5, 10, 12, 32] {
+ let (mut a, mut b) = (Vec::new(), Vec::new());
+ let mut sent = FxHashSet::default();
+ for step in 0..60i32 {
+ let center = ((step % 17) - 8, (step * 3 % 11) - 5);
+ requeue(&mut a, &sent, center, r);
+ requeue_scan(&mut b, &sent, center, r);
+ assert_eq!(a, b, "radius {r}, step {step}");
+ for key in a.drain(..a.len().min(7)) {
+ sent.insert(key);
+ }
+ b.drain(..b.len().min(7));
+ sent.retain(|&(x, z)| tracked(center.0, center.1, r, x, z));
+ }
+ }
+ }
+
+ /// cargo test --release -p horizon-client --lib lan::hub::tests::requeue_cost -- --ignored --nocapture
+ #[test]
+ #[ignore]
+ fn requeue_cost() {
+ for r in [10, 16, 32] {
+ for (name, f) in [
+ ("scan", requeue_scan as fn(&mut _, &_, _, _)),
+ ("set", requeue as fn(&mut _, &_, _, _)),
+ ] {
+ let sent = FxHashSet::default();
+ let mut queue = Vec::new();
+ let start = std::time::Instant::now();
+ let moves = 200;
+ for step in 0..moves {
+ // Nothing sent yet (an explorer waiting on generation).
+ f(&mut queue, &sent, (step, 0), r);
+ }
+ let per = start.elapsed().as_secs_f64() * 1e6 / f64::from(moves);
+ println!(
+ "view {r}: {name} {per:.1} us per chunk crossed, {} queued",
+ queue.len()
+ );
+ }
+ }
+ }
+}
diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs
index a71418f18..612509133 100644
--- a/crates/horizon-client/src/lib.rs
+++ b/crates/horizon-client/src/lib.rs
@@ -69,7 +69,7 @@ pub mod first_person;
pub mod flatgen;
pub mod fog;
pub mod font;
-pub mod front;
+pub mod friends_screen;
pub mod game_mode_switcher;
pub mod gamepad;
pub mod gamerules;
@@ -127,7 +127,6 @@ pub mod nether_portal;
pub mod offline_name;
pub mod options_file;
pub mod options_fixes;
-pub mod options_horizon;
pub mod options_ui;
pub mod osk;
pub mod overlay;
@@ -141,7 +140,6 @@ pub mod player_sync;
pub mod poi_sections;
pub mod portal_sections;
pub mod pose;
-pub mod post;
pub mod projectiles;
pub mod raid;
pub mod random_sequences;
diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs
index e87032f07..db2ebeb60 100644
--- a/crates/horizon-client/src/mobs.rs
+++ b/crates/horizon-client/src/mobs.rs
@@ -807,7 +807,11 @@ pub struct Mob {
pub persistent: bool,
/// `CustomName` (plain text) and `CustomNameVisible`.
pub custom_name: Option,
+ /// The styled `CustomName`, when it came from a component.
+ pub custom_name_text: Option,
pub name_visible: bool,
+ /// `Entity.DATA_SHARED_FLAGS_ID` bit 0x20: the model is hidden.
+ pub invisible: bool,
pub random: LegacyRandom,
pub ai: Box,
pub extra: Extra,
@@ -846,6 +850,9 @@ pub struct Mob {
/// from the game), handed over with the next tick's events or drained
/// by the game.
pub outbox: Vec,
+ /// The skin texture of a player mob (`PlayerInfo.getSkin`), which
+ /// replaces the type's default when its download is ready.
+ pub skin: Option,
}
/// Events a mob tick asks the game to act on.
#[derive(Clone, Debug)]
@@ -1310,31 +1317,67 @@ impl Mob {
/// `Entity.push` on other mobs acts at once in vanilla: a mob ticking later
/// moves with it this tick. Takes the `Push` events aimed at mobs out of
/// `events[from..]` into `pending`, which the caller adds to each mob's
-/// velocity before its tick (and to every mob once all have ticked).
-pub fn take_mob_pushes(events: &mut Vec, from: usize, pending: &mut Vec<(u32, Vec3)>) {
- let mut i = from;
- while i < events.len() {
+/// velocity before its tick (and to every mob once all have ticked). The
+/// other events keep their order.
+pub fn take_mob_pushes(events: &mut Vec, from: usize, pending: &mut PendingPushes) {
+ // One pass: a crowd's tick holds a push per neighbour, and removing each
+ // in place would shift the rest every time.
+ let mut kept = from;
+ for i in from..events.len() {
if let MobEvent::Push {
target: Who::Mob(id),
velocity,
} = events[i]
{
- pending.push((id, Vec3::new(velocity[0], velocity[1], velocity[2])));
- events.remove(i);
+ pending.push(id, Vec3::new(velocity[0], velocity[1], velocity[2]));
} else {
- i += 1;
+ events.swap(kept, i);
+ kept += 1;
}
}
+ events.truncate(kept);
+}
+/// Pushes waiting for their mob's tick, in push order. A list while short;
+/// past [`PendingPushes::LIST_MAX`] (a crowd pushing each other) one list
+/// per mob, as scanning the whole list for each mob grows with its square.
+#[derive(Default)]
+pub struct PendingPushes {
+ list: Vec<(u32, Vec3)>,
+ by_mob: crate::fast_hash::FxHashMap>,
+}
+impl PendingPushes {
+ const LIST_MAX: usize = 64;
+ pub fn push(&mut self, id: u32, v: Vec3) {
+ if self.by_mob.is_empty() && self.list.len() < Self::LIST_MAX {
+ self.list.push((id, v));
+ return;
+ }
+ // Older pushes first, so each mob's stay in order.
+ for (id, v) in self.list.drain(..) {
+ self.by_mob.entry(id).or_default().push(v);
+ }
+ self.by_mob.entry(id).or_default().push(v);
+ }
}
/// Adds the pending pushes aimed at `m` to its velocity, in push order.
-pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) {
- pending.retain(|(id, v)| {
- if *id != m.id {
- return true;
- }
+pub fn apply_mob_pushes(m: &mut Mob, pending: &mut PendingPushes) {
+ let mut add = |v: Vec3| {
m.velocity = Vec3::new(m.velocity.x + v.x, m.velocity.y + v.y, m.velocity.z + v.z);
- false
- });
+ };
+ if !pending.list.is_empty() {
+ pending.list.retain(|(id, v)| {
+ if *id != m.id {
+ return true;
+ }
+ add(*v);
+ false
+ });
+ }
+ if !pending.by_mob.is_empty()
+ && let Some(pushes) = pending.by_mob.remove(&m.id)
+ {
+ pushes.into_iter().for_each(add);
+ }
}
/// Applies the brain memories a mob's tick set on other mobs (from event
/// index `from` on), at once: vanilla sets them on the other entity during
@@ -1406,6 +1449,7 @@ pub struct PlayerView {
/// (`EntitySelector.pushableBy` on the client).
pub remote: bool,
}
+#[derive(Clone)]
pub struct MobWorld<'a> {
pub world: &'a World,
pub registry: &'a horizon_world::registry::BlockRegistry,
@@ -1420,6 +1464,8 @@ pub struct MobWorld<'a> {
pub others: &'a [Seen],
/// `others` by position, when the caller keeps one (the mob ticks).
pub others_grid: Option<&'a seen_grid::SeenGrid>,
+ /// Where each id stands in `others`, when the caller keeps one.
+ pub others_index: Option<&'a crate::fast_hash::FxHashMap>,
pub daylight: bool,
pub game_time: i64,
pub day_time: i64,
@@ -1438,22 +1484,23 @@ pub struct MobWorld<'a> {
pub world_seed: i64,
/// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world).
pub sea_level: i32,
- /// The scoreboard teams of the player and the mobs (collision rules).
- pub teams: Teams,
+ /// The scoreboard teams of the player and the mobs (collision rules),
+ /// shared: the mob ticks build them once a tick, not once a mob.
+ pub teams: std::sync::Arc>,
/// Item data (max stack sizes), when the host has it.
pub items: Option<&'a crate::items::Items>,
}
/// `Entity.getTeam` of the player and of the mobs on a team.
#[derive(Clone, Debug, Default)]
-pub struct Teams {
- pub player: Option,
- pub mobs: HashMap,
+pub struct Teams<'a> {
+ pub player: Option<&'a crate::scoreboard::Team>,
+ pub mobs: HashMap,
}
-impl Teams {
- pub fn of(&self, who: Who) -> Option<&crate::scoreboard::Team> {
+impl<'a> Teams<'a> {
+ pub fn of(&self, who: Who) -> Option<&'a crate::scoreboard::Team> {
match who {
- Who::Player => self.player.as_ref(),
- Who::Mob(id) => self.mobs.get(&id),
+ Who::Player => self.player,
+ Who::Mob(id) => self.mobs.get(&id).copied(),
}
}
}
@@ -1515,10 +1562,13 @@ impl Mob {
last_damage: None,
removed: false,
custom_name: None,
+ custom_name_text: None,
name_visible: false,
+ invisible: false,
anim: anim::AnimState::default(),
rider: None,
outbox: Vec::new(),
+ skin: None,
attrs: Attrs {
speed: kind.speed,
attack_damage: kind.attack_damage,
@@ -2139,3 +2189,504 @@ mod elytra_tests {
assert!((wings.angles[1] - 0.08726646).abs() < 0.00001);
}
}
+#[cfg(test)]
+mod teams_tests {
+ use super::*;
+ use crate::save::uuid_text;
+ use crate::scoreboard::{Scoreboard, Team};
+
+ /// A board where every other mob is on the player's team, as with a
+ /// datapack that colours its mobs' names.
+ fn board(mobs: u32) -> (Scoreboard, HashMap) {
+ let mut board = Scoreboard::default();
+ board.add_team("red");
+ board.add_to_team("Steve", "red");
+ let uuids: HashMap