Merge origin/main into feat/win-screen

hud.rs: HudBatch keeps both new fields, end_portal (this branch) and
blur_at (main's menu blur), in the struct, its constructor and the test
batch. draw_range already draws EndPortal runs on either side of blur_at.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-22 22:56:56 +02:00
196 changed files with 13287 additions and 1652 deletions
+12 -9
View File
@@ -1,17 +1,20 @@
name: promote
# Beta game releases become stable (docs/release-flow.md, "Channels"): every 30 minutes tools/release_channels.py
# promotes the newest beta that has been out 6 hours, passed its release smoke test and isn't covered by an issue
# labelled release-blocker. By hand, from GitHub's app too (Actions > promote > Run workflow):
# gh workflow run promote -f tag=v2026.10.19.03 # that beta now, without the wait
# gh workflow run promote -f tag=v2026.10.19.03 -f force=true # even blocked or without its smoke test
# gh workflow run promote -f dry_run=true # say what would be promoted
# Beta game releases become stable once a day (docs/release-flow.md, "Channels"): at 20:00 UTC (21:00 in Paris in
# winter time, 22:00 in summer) tools/release_channels.py promotes the newest beta that had been out 6 hours by then,
# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Alpha
# channel install every beta when it is published; Stable gets the day's promotion. The later runs of the evening are
# retries for a run GitHub starts late or skips: they promote the same beta, so stable still moves once.
# By hand, from GitHub's app too (Actions > promote > Run workflow):
# gh workflow run promote -f tag=v0.2.3 # that beta now, without waiting for 20:00
# gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without its smoke test
# gh workflow run promote -f dry_run=true # say what would be promoted
# Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it
# still holds the betas published before it closed. The issue's text is never read (its author could edit it).
# When the oldest waiting beta is 24 hours old, an issue "Promotion to stable has stalled" says so; it closes itself
# after the next promotion.
# When the oldest waiting beta is 30 hours old (it missed a promotion it was due for), an issue "Promotion to stable
# has stalled" says so; it closes itself after the next promotion.
on:
schedule:
- cron: '13,43 * * * *'
- cron: '7,37 20-21 * * *'
workflow_dispatch:
inputs:
tag:
+5 -4
View File
@@ -1,14 +1,14 @@
name: release
# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides:
# a release when pull requests merged since the last one changed what players run and the newest merged 15 minutes
# ago (the oldest an hour ago, if merges never pause), or at once for a pull request labelled release-now.
# a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes
# ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now.
# RELEASES_PAUSED=1 (repository variable) stops them.
# Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and
# Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then
# publishes vX.Y.Z on the release line in .github/release-line.txt (docs/versioning.md; without it, the dated
# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes
# stable after 6 hours. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with
# stable in its daily promotion. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with
# Developer ID and the hardened runtime and the zip is notarized, from the runner's signing keychain
# (packaging/macos/README.md); unset (forks), ad hoc.
# gh workflow run release --ref <branch> # dry run: builds and notes, publishes nothing
@@ -349,7 +349,8 @@ jobs:
run: |
signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig)
smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json)
# A beta (pre-release): promote.yml makes it stable and latest after 6 hours (docs/release-flow.md).
# A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion
# (docs/release-flow.md).
gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \
--notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \
dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \
+3 -2
View File
@@ -42,8 +42,9 @@ log = "0.4"
chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] }
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
horizon-theme = { path = "../horizon-theme" }
# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md); `live` is
# the anonymous "I'm playing" ping the game sends itself (`heartbeat.rs`).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false, features = ["live"] }
horizon-bench = { path = "../horizon-bench" }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
zip = { version = "2", default-features = false, features = ["deflate"] }
@@ -82,12 +82,19 @@ fn main() -> horizon_client::Result<()> {
let brewing = horizon_client::brewing::Brewing::load(root, &items);
// The inventory menu never reads banner patterns.
let banners = horizon_client::banner::Banners::default();
let station_recipes = horizon_client::stations::StationRecipes::default();
let enchantments = horizon_client::enchant::Enchantments::default();
let names = horizon_client::creative::Names::default();
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
enchantments: &enchantments,
names: &names,
trade: None,
maps: None,
};
let mut out = String::new();
for line in input.lines() {
@@ -1,7 +1,7 @@
//! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the
//! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line;
//! the `#resources` line names the prepared resources for en_us).
use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language};
use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines};
use std::{error::Error, fmt::Write, path::PathBuf};
fn main() -> Result<(), Box<dyn Error>> {
@@ -12,8 +12,9 @@ fn main() -> Result<(), Box<dyn Error>> {
.find_map(|l| l.strip_prefix("#resources "))
.map(PathBuf::from)
.ok_or("no #resources line")?;
let language = Language::load(&[&root], "en_us");
let translate = |key: &str| language.get(key).map(str::to_owned);
// Use the inventory's filtered translations so missing tooltip keys are caught.
let enchantments = Enchantments::load(&root);
let translate = |key: &str| enchantments.translate(key).map(str::to_owned);
let mut output = String::new();
for line in input.lines().filter(|l| !l.starts_with('#')) {
let stack = parse_stack(line)?.ok_or("empty stack")?;
@@ -14,13 +14,22 @@ fn main() {
for count in [0, 1, 4, 64] {
let mut slot = Some(ItemStack::new("minecraft:stone", count));
let mut dropped = 0;
let mut swings = 0;
let mut packets = 0;
for _ in 0..2 {
if let Some(stack) =
take_held_drop(&mut slot, all, mode == GameMode::Spectator)
{
dropped += stack.count;
swings += 1;
}
println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped);
if mode != GameMode::Spectator {
packets += 1;
}
println!(
"{} {dropped} {swings} {packets}",
slot.as_ref().map_or(0, |s| s.count),
);
}
}
}
@@ -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<T> = std::result::Result<T, Box<dyn std::error::Error>>;
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<String> = 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<usize> {
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::<std::io::Result<_>>()?;
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::<usize>()})
);
// 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(())
}
+106 -4
View File
@@ -11,8 +11,41 @@ use horizon_client::{
items::Items,
menu::{Env, Input, Kind, Menu},
};
use horizon_protocol::registry::Ids;
use serde_json::Value;
use std::{fs, path::Path};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
fs,
path::Path,
};
/// The case's maps: (locked, scale) by id, and the next free id.
#[derive(Default)]
struct CaseMaps {
maps: RefCell<HashMap<i32, (bool, u8)>>,
next: Cell<i32>,
}
impl horizon_client::menu::Maps for CaseMaps {
fn state(&self, id: i32) -> Option<(bool, u8)> {
self.maps.borrow().get(&id).copied()
}
/// `MapItemSavedData.scaled` (unlocked, one scale up) or `locked`.
fn derive(&self, id: i32, scale: bool) -> Option<i32> {
let (_, s) = self.state(id)?;
let new = self.next.get();
self.next.set(new + 1);
let made = if scale {
(false, (s + 1).min(4))
} else {
(true, s)
};
self.maps.borrow_mut().insert(new, made);
Some(new)
}
}
fn state(menu: &Menu) -> String {
let slots: Vec<String> = (0..menu.slot_count())
@@ -24,13 +57,21 @@ fn state(menu: &Menu) -> String {
.iter()
.map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref())))
.collect();
format!(
let line = format!(
"{} | {} |{data} | {} | {}",
slots.join(" "),
canon_stack(menu.carried.as_ref()),
menu.drops.join(";"),
equipped.join(";")
)
);
if menu.kind() != Kind::Lectern {
return line;
}
// No inventory slots: the inventory Take Book fills.
let items: String = (0..36)
.map(|i| format!(" {}", canon_stack(menu.player_item(i))))
.collect();
format!("{line} | inv{items}")
}
fn main() -> horizon_client::Result<()> {
@@ -44,13 +85,28 @@ fn main() -> horizon_client::Result<()> {
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let banners = horizon_client::banner::Banners::load(root);
let station_recipes = horizon_client::stations::StationRecipes::load(root, &items);
let enchantments = horizon_client::enchant::Enchantments::load(root);
let names = horizon_client::creative::Names::load(root);
let case_maps = CaseMaps::default();
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
enchantments: &enchantments,
names: &names,
trade: None,
maps: Some(&case_maps),
};
// The mob effects' network ids (BeaconMenu.encodeEffect).
let builtin = horizon_protocol::registry::Builtin::find(root)
.and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok());
let effects = builtin
.as_ref()
.and_then(|b| b.get("minecraft:mob_effect"))
.cloned();
let mut out = String::new();
for line in input.lines() {
let case: Value = serde_json::from_str(line)?;
@@ -68,15 +124,41 @@ fn main() -> horizon_client::Result<()> {
.unwrap_or(name),
)
.ok_or("menu kind")?;
// [id, scale, locked] each; the level's new maps from 1000.
case_maps.next.set(1000);
*case_maps.maps.borrow_mut() = case["maps"]
.as_array()
.into_iter()
.flatten()
.map(|m| {
let id = m[0].as_i64().unwrap_or(0) as i32;
(
id,
(
m[2].as_bool().unwrap_or(false),
m[1].as_u64().unwrap_or(0) as u8,
),
)
})
.collect();
let mut menu = Menu::new(kind);
menu.creative = case["creative"].as_bool().unwrap_or(false);
menu.levels = case["levels"].as_i64().unwrap_or(0) as i32;
for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() {
menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?);
}
menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?;
for (i, item) in case["inventory"]
.as_array()
.into_iter()
.flatten()
.enumerate()
{
menu.set_player_item(i, parse_stack(item.as_str().unwrap_or("-"))?);
}
menu.settle(&env);
for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() {
menu.data[i] = v.as_i64().unwrap_or(0) as i32;
menu.set_data(i, v.as_i64().unwrap_or(0) as i32);
}
let mut furnace = furnace_kind.map(|kind| Furnace {
kind,
@@ -100,6 +182,26 @@ fn main() -> horizon_client::Result<()> {
out += &format!("{}\n", state(&menu));
continue;
}
// ServerboundRenameItemPacket: AnvilMenu.setItemName.
"RENAME" => {
menu.rename(&env, op[3].as_str().unwrap_or_default());
out += &format!("{}\n", state(&menu));
continue;
}
// ServerboundSetBeaconPacket: BeaconMenu.updateEffects.
"SET_BEACON" => {
fn power<'a>(ids: Option<&Ids>, v: &'a Value) -> Option<(i32, &'a str)> {
let name = v.as_str()?;
Some((ids?.id(name)?, name))
}
let (primary, secondary) = (
power(effects.as_ref(), &op[3]),
power(effects.as_ref(), &op[4]),
);
menu.beacon_update(&env, primary, secondary);
out += &format!("{}\n", state(&menu));
continue;
}
// ServerboundContainerSlotStateChangedPacket.
"SLOT_STATE" => {
if (0..9).contains(&slot) {
@@ -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<String> = Vec::new();
let mut pushes = Vec::new();
let mut pushes = horizon_client::mobs::PendingPushes::default();
let mut born = Vec::new();
for i in 0..mobs.len() {
if mobs[i].removed {
@@ -38,12 +38,19 @@ fn main() -> horizon_client::Result<()> {
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let banners = horizon_client::banner::Banners::default();
let station_recipes = horizon_client::stations::StationRecipes::default();
let enchantments = horizon_client::enchant::Enchantments::default();
let names = horizon_client::creative::Names::default();
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
enchantments: &enchantments,
names: &names,
trade: None,
maps: None,
};
let mut out = String::new();
for (line, order) in cases.lines().zip(orders.lines()) {
@@ -3,6 +3,7 @@
//! what the render thread pays for it in `Streaming::update`.
//!
//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F]
//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z]
//!
//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x
//! at that speed for T seconds while frames run at F per second. Each phase reports
@@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn cpu_seconds() -> f64 {
std::fs::read_to_string("/proc/self/stat")
.ok()
.and_then(|stat| {
let fields = stat
.rsplit_once(')')?
.1
.split_whitespace()
.collect::<Vec<_>>();
Some((fields[11].parse::<f64>().ok()? + fields[12].parse::<f64>().ok()?) / 100.0)
})
.unwrap_or(0.0)
}
#[derive(Default)]
struct Phase {
updates: Vec<f64>,
local: (u64, u64),
uploads: usize,
stage_samples: [u64; 7],
cpu_start: f64,
}
impl Phase {
fn update(&mut self, streaming: &mut Streaming, world: &mut World) {
if self.updates.is_empty() {
self.cpu_start = cpu_seconds();
}
let before = LOCAL.with(Cell::get);
let started = Instant::now();
let (uploads, _) = streaming.update(world);
@@ -89,6 +109,9 @@ impl Phase {
self.local.1 += after.1 - before.1;
self.uploads += uploads.len();
drop(uploads);
for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) {
*sum += count as u64;
}
}
fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) {
let mut sorted = self.updates.clone();
@@ -106,6 +129,16 @@ impl Phase {
at(0.99),
sorted.last().copied().unwrap_or(0.0),
);
println!(
"BENCH {}",
serde_json::json!({
"phase": name, "wall_s": wall.as_secs_f64(),
"cpu_s": cpu_seconds() - self.cpu_start,
"chunks": streaming.generated_total - generated, "sections": self.uploads,
"updates": self.updates.len(), "update_ms": total,
"mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64),
})
);
if TRACK {
println!(
" update allocations: {} ({:.1} MiB)",
@@ -142,6 +175,22 @@ fn main() -> Result<()> {
let fly = flag("--fly", 0.0);
let seconds = flag("--seconds", 10.0);
let hz = flag("--hz", 240.0);
let dimension = args
.iter()
.position(|a| a == "--dimension")
.and_then(|i| args.get(i + 1))
.map(|d| {
if d.contains(':') {
d.clone()
} else {
format!("minecraft:{d}")
}
})
.unwrap_or_else(|| "minecraft:overworld".into());
let center = (
flag("--center-x", 0.0) as i32,
flag("--center-z", 0.0) as i32,
);
let assets = Arc::new(Assets::load(&root)?);
let render = Arc::new(assets.reload(&root)?);
@@ -154,11 +203,12 @@ fn main() -> Result<()> {
models::load_visibility(&root, assets.registry)?,
)?);
let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?);
let terrain = Arc::new(VanillaTerrain::new(
let terrain = Arc::new(VanillaTerrain::for_dimension(
&root.join("worldgen"),
assets.registry,
&biomes,
seed,
&dimension,
)?);
let context = Arc::new(WorkerContext {
assets,
@@ -170,8 +220,12 @@ fn main() -> Result<()> {
let mut world = World::new(facts.air, seed);
let mut streaming = Streaming::new(terrain, context, threads);
streaming.radius = radius;
streaming.center = (0, 0);
println!("{threads} workers, radius {radius}, seed {seed}");
streaming.center = center;
streaming.nether_shading = dimension == "minecraft:the_nether";
streaming.sky_light = dimension != "minecraft:the_nether";
println!(
"{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}"
);
let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed));
// Fill: update as often as the game would uncapped, until settled.
@@ -198,12 +252,12 @@ fn main() -> Result<()> {
let mut behind = Vec::new();
while started.elapsed().as_secs_f64() < seconds {
let next = Instant::now() + frame;
let x = (started.elapsed().as_secs_f64() * fly) as i32;
streaming.center = (x, 0);
let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32;
streaming.center = (x, center.1);
phase.update(&mut streaming, &mut world);
// Columns within 2 chunks of the player still missing their meshes.
let near = (-2..=2)
.flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz)))
.flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz)))
.filter(|&(cx, cz)| !streaming.is_lit(cx, cz))
.count();
behind.push(near);
@@ -239,10 +239,12 @@ fn main() -> horizon_client::Result<()> {
let vanilla = fs::read_to_string(args.get(3).ok_or(usage)?)?;
let items = Items::catalog(root)?;
let enchantments = Enchantments::load(root);
let names = horizon_client::creative::Names::default();
let trades = Trades::load(root);
let recipes = horizon_client::crafting::Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let banners = horizon_client::banner::Banners::load(root);
let station_recipes = horizon_client::stations::StationRecipes::default();
let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)?
.types
.into_iter()
@@ -378,7 +380,11 @@ fn main() -> horizon_client::Result<()> {
recipes: &recipes,
brewing: &brewing,
banners: &banners,
station_recipes: &station_recipes,
enchantments: &enchantments,
names: &names,
trade: Some(&env_trade),
maps: None,
};
trade(&mut out, name, &kv, &mut world, &env, origin)?;
}
+1 -1
View File
@@ -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);
}
+96
View File
@@ -1102,7 +1102,11 @@ pub struct Recipes {
facts: HashMap<Arc<str>, Facts>,
/// The `#minecraft:curse` enchantments.
curses: HashSet<String>,
/// 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<CookIndex>,
}
type CookIndex = HashMap<String, crate::fast_hash::FxHashMap<String, usize>>;
/// `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::<Vec<_>>()
.iter()
.map(String::as_str)
.collect::<Vec<_>>(),
),
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<ItemStack> = (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<ItemStack> {
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,
+1
View File
@@ -44,6 +44,7 @@ pub struct Creative {
search_index: Vec<SearchEntry>,
}
/// Display names from the pinned en_us language file.
#[derive(Default)]
pub struct Names {
map: HashMap<String, String>,
}
+3
View File
@@ -60,6 +60,7 @@ pub struct ItemProps {
/// `minecraft:brewing_fuel` present.
pub brewing_fuel: bool,
}
#[derive(Default)]
pub struct Enchantments {
pub list: Vec<Enchantment>,
index: HashMap<Arc<str>, usize>,
@@ -192,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.")
+6
View File
@@ -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<crate::text::Text>,
/// `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,
}
}
+7
View File
@@ -109,6 +109,13 @@ fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
return entity_vertex(position, uv, overlay, color, light, normal);
}
// Retained bolt-local geometry, translated using the same f64 camera
// subtraction as the former CPU path before adding each local f32 position.
@vertex fn vs_lightning(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>,
@location(6) offset: vec3<f32>) -> Out {
return entity_vertex(offset + position, uv, overlay, color, light, normal);
}
struct CloudInfo {
offset: vec4<f32>,
colors: array<vec4<f32>, 4>,
+52
View File
@@ -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<String> {
_ => 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<String, Arc<MobType>>, id: u32) -> Option<Mob> {
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<String, Arc<MobType>>, 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<ArmorStand> {
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"))]);
@@ -21,6 +21,8 @@ pub enum ItemPose {
Trident {
ticks_used: f32,
},
/// Riptide's spin (`isAutoSpinAttack`): the item held up like a fork.
SpinAttack,
Bow {
ticks_used: f32,
},
@@ -67,6 +69,12 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -
if matches!(pose, ItemPose::Using) {
return m;
}
if matches!(pose, ItemPose::SpinAttack) {
return m
* Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3))
* Mat4::from_rotation_y((invert * 65.0f32).to_radians())
* Mat4::from_rotation_z((invert * -85.0f32).to_radians());
}
let charging = match pose {
ItemPose::Bow { ticks_used } => {
let power = ticks_used / 20.0;
+271 -43
View File
@@ -74,6 +74,7 @@ mod lan_entities;
mod lan_mobs;
mod lan_pvp;
mod lan_screen;
mod lan_stations;
mod lan_trading;
mod lan_waypoints;
mod leads;
@@ -119,6 +120,7 @@ mod recipe_book;
mod remote;
mod remote_objects;
mod remote_projectiles;
mod remote_stations;
mod render_control;
mod render_tick;
mod respawn_anchor;
@@ -213,6 +215,7 @@ use horizon_world::{
registry::BlockStateId,
};
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
path::PathBuf,
sync::{
@@ -271,9 +274,10 @@ struct Options {
benchmark: Option<String>,
/// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt.
dev_mods: Vec<PathBuf>,
/// 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,
@@ -330,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,
};
@@ -340,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);
@@ -905,6 +909,8 @@ struct WorldRest {
behaviours: Behaviours,
player_arm: Option<horizon_client::mobs::Part>,
player_type: Option<Arc<horizon_client::mobs::MobType>>,
/// `SpinAttackEffectModel` (Riptide's spinning boxes).
spin_attack: Option<horizon_client::mobs::Part>,
stations: horizon_client::stations::StationData,
}
@@ -980,6 +986,9 @@ impl Resources {
fn player_type(&self) -> &Option<Arc<horizon_client::mobs::MobType>> {
&self.rest().player_type
}
fn spin_attack(&self) -> &Option<horizon_client::mobs::Part> {
&self.rest().spin_attack
}
fn stations(&self) -> &horizon_client::stations::StationData {
&self.rest().stations
}
@@ -1385,7 +1394,7 @@ struct Game<'a> {
map_patches: Vec<horizon_client::font::Patch>,
/// Player skin downloads, and which skin each atlas skin slot holds
/// (least recently shown first).
skin_downloads: horizon_client::skins::Downloader,
skin_downloads: RefCell<horizon_client::skins::Downloader>,
skin_slots: Vec<(String, usize)>,
cart_models: minecarts::CartModels,
/// The boat the player rides.
@@ -1415,6 +1424,8 @@ struct Game<'a> {
arrow_model: Option<horizon_client::mobs::Part>,
tnts: Vec<tnt::PrimedTnt>,
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
/// Where item entities are, while the block entities tick (hoppers).
item_columns: Option<machines::ItemColumns>,
creative_screen: Creative,
control: Option<horizon_client::control::Server>,
frame_stats: horizon_client::control::FrameStats,
@@ -2562,14 +2573,23 @@ impl Game<'_> {
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
1031 => Some(("minecraft:block.anvil.land", 0.3)),
1505 => Some(("minecraft:item.bone_meal.use", 1.0)),
1042 => Some(("minecraft:block.grindstone.use", 1.0)),
1044 => Some(("minecraft:block.smithing_table.use", 1.0)),
// LevelEvent.SOUND_PAGE_TURN (a lectern's page).
1043 => Some(("minecraft:item.book.page_turn", 1.0)),
_ => None,
};
if let Some((name, volume)) = sound {
let pitch = if id == 1009 {
2.6 + (self.world.random.next_float() - self.world.random.next_float())
* 0.8
} else {
1.0
let pitch = match id {
1009 => {
2.6 + (self.world.random.next_float()
- self.world.random.next_float())
* 0.8
}
1029 | 1030 | 1042 | 1043 | 1044 => {
self.world.random.next_float() * 0.1 + 0.9
}
_ => 1.0,
};
self.audio.play(name, c, volume, pitch);
}
@@ -3925,6 +3945,7 @@ impl Game<'_> {
}
let riding = self.riding.is_some();
let ghast_collisions = self.happy_ghast_player_collisions();
let spin_targets = self.spin_targets();
let Some(player) = self.player.as_mut() else {
// A dedicated server has no local player: the world still runs.
if self.options.dedicated.is_some() {
@@ -4002,6 +4023,7 @@ impl Game<'_> {
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)));
// The dimension's FAST_LAVA: the Nether's lava pushes harder.
player.fluids.fast_lava = self.dim == Dim::Nether;
player.spin_targets = spin_targets;
let grounded = player.ground.on_ground;
let before = (
grounded,
@@ -4024,6 +4046,7 @@ impl Game<'_> {
}
}
let events = std::mem::take(&mut player.events);
let spin_hit = player.spin_hit.take();
let glider_wear = std::mem::take(&mut player.glider_wear);
if glider_wear > 0
&& !self.creative
@@ -4042,6 +4065,7 @@ impl Game<'_> {
self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5;
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
self.tick_avatar(before, riding);
self.end_spin_attack(spin_hit);
self.record_combat(&events);
for event in events {
match event {
@@ -4474,10 +4498,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);
}
@@ -4831,6 +4862,9 @@ impl Game<'_> {
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.
@@ -5446,6 +5480,17 @@ impl Game<'_> {
.station
.as_ref()
.is_some_and(|s| s.kind == stations::Kind::Merchant);
let stonecutter_open = self
.station
.as_ref()
.is_some_and(|s| s.kind == stations::Kind::Stonecutter);
let station_kind = self.station.as_ref().map(|s| s.kind);
let grindstone_open = station_kind == Some(stations::Kind::Grindstone);
let cartography_open = station_kind == Some(stations::Kind::Cartography);
let anvil_open = station_kind == Some(stations::Kind::Anvil);
let smithing_open = station_kind == Some(stations::Kind::Smithing);
let enchanting_open = station_kind == Some(stations::Kind::Enchanting);
let beacon_open = station_kind == Some(stations::Kind::Beacon);
let (kind, game_of): (Kind, Vec<Option<usize>>) = if self.creative_tab_open() {
// ItemPickerMenu: the display slots (clicked by the screen), then the hotbar.
let mut v = vec![None; 45];
@@ -5472,6 +5517,51 @@ impl Game<'_> {
v.push(Some(stations::RESULT));
v.extend((9..36).chain(0..9).map(Some));
(Kind::Loom, v)
} else if stonecutter_open {
// StonecutterMenu: the input, the result, then the inventory.
let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)];
v.extend((9..36).chain(0..9).map(Some));
(Kind::Stonecutter, v)
} else if grindstone_open || cartography_open {
// GrindstoneMenu and CartographyTableMenu: the two inputs, the
// result, then the inventory.
let mut v = vec![
Some(stations::INPUT),
Some(stations::INPUT + 1),
Some(stations::RESULT),
];
v.extend((9..36).chain(0..9).map(Some));
let kind = if grindstone_open {
Kind::Grindstone
} else {
Kind::Cartography
};
(kind, v)
} else if enchanting_open {
// EnchantmentMenu: the item, the lapis, then the inventory.
let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)];
v.extend((9..36).chain(0..9).map(Some));
(Kind::Enchanting, v)
} else if beacon_open {
// BeaconMenu: the payment, then the inventory.
let mut v = vec![Some(stations::INPUT)];
v.extend((9..36).chain(0..9).map(Some));
(Kind::Beacon, v)
} else if anvil_open || smithing_open {
// ItemCombinerMenu: the inputs, the result, then the inventory.
let inputs = if anvil_open { 2 } else { 3 };
let mut v: Vec<Option<usize>> =
(0..inputs).map(|i| Some(stations::INPUT + i)).collect();
v.push(Some(stations::RESULT));
v.extend((9..36).chain(0..9).map(Some));
(
if anvil_open {
Kind::Anvil
} else {
Kind::Smithing
},
v,
)
} else {
let (kind, map) = if self.container.is_some() {
let size = self.container_size();
@@ -5554,6 +5644,10 @@ impl Game<'_> {
s.loom.patterns.clone(),
)
});
let stone = self
.station
.as_ref()
.map(|s| (s.selected.map_or(-1, |i| i as i32), s.stone.clone()));
let crafter_data = match self.container_kind() {
Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)),
_ => None,
@@ -5567,6 +5661,18 @@ impl Game<'_> {
if let Some((s, mob)) = session.as_mut() {
self.merchant_sync_in(s, *mob);
}
// The cartography table reads and makes the level's maps; a
// server's (the client menu's ContainerLevelAccess.NULL) doesn't.
let level_maps = (kind == Kind::Cartography && self.remote.is_none()).then(|| {
let held: Vec<ItemStack> = before
.iter()
.flatten()
.chain(self.inventory.iter().flatten())
.chain(self.carried.iter())
.cloned()
.collect();
self.level_maps(&held)
});
let next_map = if merchant_open { self.peek_map_id() } else { 0 };
let tag = |t: &str| self.structure_tag(t);
let maps = trading::GameMaps {
@@ -5585,10 +5691,21 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
enchantments: &self.res.stations().enchantments,
names: &self.pack.names,
trade: Some(&trade_env),
maps: level_maps
.as_ref()
.map(|m| m as &dyn horizon_client::menu::Maps),
};
menu.creative = creative;
menu.selected = self.selected;
menu.levels = self.experience.level;
if anvil_open {
// The rename box as AnvilScreen.onNameChanged gives it to the menu.
menu.anvil.name = self.station.as_ref().map(|s| self.anvil_item_name(s));
}
for (i, stack) in before.iter().enumerate() {
menu.set_slot(&env, i, stack.clone());
}
@@ -5606,6 +5723,25 @@ impl Game<'_> {
menu.loom_patterns = patterns;
menu.set_slot(&env, 3, before[3].clone());
}
if kind == Kind::Stonecutter
&& let Some((selected, state)) = stone
{
// The same: the list and selection between clicks, then the result.
menu.data[0] = selected;
menu.stone = state;
menu.set_slot(&env, 1, before[1].clone());
}
if kind == Kind::Enchanting
&& let Some(s) = self.station.as_ref()
{
// The offers between clicks (what copying the slots in flagged is not a change).
menu.enchant_changed = false;
for i in 0..3 {
menu.data[i] = s.offers.costs[i];
menu.data[7 + i] = s.offers.clues[i].as_ref().map_or(-1, |(_, l)| *l as i32);
}
menu.data[3] = self.level.xp_seed;
}
if let Some((disabled, triggered)) = crafter_data {
for (i, d) in disabled.iter().enumerate() {
menu.data[i] = i32::from(*d);
@@ -5660,10 +5796,37 @@ impl Game<'_> {
s.loom.selected = usize::try_from(menu.data[0]).ok();
s.loom.patterns = std::mem::take(&mut menu.loom_patterns);
}
for sound in sounds {
self.loom_sound(sound);
// A server's loom plays its own sounds (the client's menu has no level).
for sound in sounds.into_iter().filter(|_| !predicting) {
self.station_sound(sound);
}
self.loom_screen_changed();
} else if kind == Kind::Cartography {
for sound in sounds.into_iter().filter(|_| !predicting) {
self.station_sound(sound);
}
} else if kind == Kind::Stonecutter {
if let Some(s) = self.station.as_mut() {
s.selected = usize::try_from(menu.data[0]).ok();
s.stone = std::mem::take(&mut menu.stone);
s.stonecutter_changed();
}
for sound in sounds.into_iter().filter(|_| !predicting) {
self.station_sound(sound);
}
}
if let Some(amount) = menu.ground.take().filter(|_| !predicting)
&& let Some(pos) = self.station.as_ref().map(|s| s.pos)
{
self.grindstone_taken(pos, amount);
}
if kind == Kind::Anvil || kind == Kind::Smithing {
self.combiner_session_end(&menu, predicting);
}
if kind == Kind::Enchanting && (menu.enchant_changed || before[0] != menu.slot(0).cloned())
{
// EnchantmentMenu.slotsChanged: new offers for the item.
self.station_changed();
}
if kind == Kind::CrafterBlock
&& let Some(BlockEntity::Crafter(c)) = self
@@ -5691,6 +5854,9 @@ impl Game<'_> {
}
}
self.apply_equipment();
if let Some(maps) = level_maps {
self.register_made_maps(maps);
}
true
}
/// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar
@@ -6774,7 +6940,13 @@ impl Game<'_> {
/// enchantments.
pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) {
let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage);
let damage = hand_damage + self.effect_attack_bonus();
// Riptide's spin replaces the attack damage attribute.
let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg);
let damage = if spin > 0.0 {
spin
} else {
hand_damage + self.effect_attack_bonus()
};
let scale = self.attack_strength_scale();
let mut amount = damage * (0.2 + scale * scale * 0.8);
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
@@ -6902,6 +7074,14 @@ impl Game<'_> {
return false;
}
}
self.attack_mob(index);
// Minecraft.startAttack swings after the attack.
self.swing_arm();
true
}
/// `Player.attack` on a mob: the damage, knockback, sweep, particles and
/// sounds.
pub(super) fn attack_mob(&mut self, index: usize) {
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
let (amount, scale, crit) = self.melee_damage(&target_kind);
@@ -6919,7 +7099,6 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0);
}
self.swing_arm();
// LivingEntity.setLastHurtMob (tamed wolves join in).
self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time));
let old_health = self.mobs[index].health;
@@ -7012,7 +7191,6 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
}
true
}
/// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step.
/// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the
@@ -8512,6 +8690,10 @@ impl Game<'_> {
}
let shown = self.hands_to_render();
let used_hand = self.used_hand();
let spinning = self
.player
.as_ref()
.is_some_and(|p| p.auto_spin_attack_ticks > 0);
for (i, (hand, item)) in Hand::BOTH
.into_iter()
.zip(self.visible_hand_items())
@@ -8631,6 +8813,7 @@ impl Game<'_> {
ItemPose::Using
}
}
_ if spinning => ItemPose::SpinAttack,
_ => ItemPose::Swing,
};
let m = to_world
@@ -9626,15 +9809,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`.
@@ -9656,8 +9841,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)
};
@@ -9704,6 +9889,12 @@ impl Game<'_> {
title: title && !live,
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,
@@ -9746,6 +9937,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 {
@@ -9851,9 +10049,8 @@ 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<f32> {
let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
let blurred = !horizon_client::ui_theme::horizon()
@@ -9861,7 +10058,10 @@ impl Game<'_> {
|| self.title.as_ref().is_some_and(|t| {
matches!(self.screen, Screen::Options | Screen::Win)
|| !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)
}
@@ -10968,6 +11168,10 @@ impl ApplicationHandler for Game<'_> {
WindowEvent::RedrawRequested => {
self.observe_fullscreen();
let now = Instant::now();
let frame_cpu = self
.options
.spikes
.and_then(|_| horizon_client::spans::thread_cpu());
let elapsed = now.duration_since(self.previous);
self.frame_ticks = elapsed.as_secs_f32() * 20.0;
self.previous = now;
@@ -10997,6 +11201,8 @@ impl ApplicationHandler for Game<'_> {
}
let updated = Instant::now();
self.track_toggle_screens();
// For the "I'm playing" ping: an atomic, sent on when it changes.
horizon_client::heartbeat::set_lan(self.is_published());
let steps = self.clock.advance(elapsed);
for _ in 0..steps {
let started = Instant::now();
@@ -11035,15 +11241,16 @@ impl ApplicationHandler for Game<'_> {
let cpu = now.elapsed().saturating_sub(r.last_wait).as_secs_f32() * 1000.0;
let spans = horizon_client::spans::take();
if cpu > threshold {
let list: Vec<String> = spans
.iter()
.filter(|(_, ms)| *ms >= 0.5)
.map(|(n, ms)| format!("{n} {ms:.1}"))
.collect();
// The render thread's own CPU time in the frame:
// far below the wall time, the frame waited.
let worked = horizon_client::spans::thread_cpu()
.zip(frame_cpu)
.map_or_else(String::new, |(end, start)| {
format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0)
});
log::info!(
"Horizon: slow frame {cpu:.1} ms ({} ticks): {}",
steps,
list.join(", ")
"Horizon: slow frame {cpu:.1} ms{worked} ({steps} ticks): {}",
horizon_client::spans::describe(&spans)
);
}
}
@@ -11472,11 +11679,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,
@@ -11496,6 +11703,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(),
@@ -12091,6 +12299,7 @@ fn load_world_rest(
player_type: perspective::player_type(root),
player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main")
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
spin_attack: horizon_client::mobs::load_model(root, "minecraft:spin_attack#main"),
})
}
@@ -12207,6 +12416,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,
@@ -12221,6 +12431,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
entities: &[],
dynamic_lights: &[],
clouds: None,
lightning: Default::default(),
additive: &[],
see_through: &[],
celestial: &[],
@@ -12793,9 +13004,26 @@ pub fn run() -> Result<()> {
if options.dedicated.is_some() && !dedicated::preflight(&mut options)? {
return Ok(());
}
if options.dedicated.is_some() {
// Before any worker starts: on Linux they go behind the server thread.
horizon_threads::put_helpers_behind();
// Before any worker starts: on Linux they go behind the server thread
// and the render thread.
horizon_threads::put_helpers_behind();
if options.dedicated.is_none() {
// The render thread, like the server thread, ahead of the workers on
// macOS and Windows. While terrain loads, the worker pools (two with
// single player's server thread) and other programs outnumber the
// cores, and a frame that gave its core up (in a GPU submit) waited
// 10 to 200 ms to get one back.
horizon_threads::favour_current();
}
// Someone is playing: the anonymous ping behind the launcher's "N playing now". Not for a
// server, a benchmark or a run that quits by itself.
if options.dedicated.is_none()
&& options.benchmark.is_none()
&& !options.offscreen
&& options.frames.is_none()
&& options.world_frames.is_none()
{
horizon_client::heartbeat::start();
}
let started = Instant::now();
horizon_client::spans::enable(options.spikes.is_some());
+16 -6
View File
@@ -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<Vec<(i32, i32, i32)>> = 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]);
+11 -1
View File
@@ -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,
+16 -6
View File
@@ -15,6 +15,7 @@ use horizon_client::{
mesher::Vertex,
mobs::render::{DYE, DYE_NAMES},
};
use horizon_protocol::packets::play::{self, Serverbound as S};
/// The beacon screen is 54 px wider than the 176-px menus it shares an origin with.
pub(super) const SHIFT: f32 = -27.0;
@@ -35,9 +36,6 @@ const PAYMENT: [&str; 5] = [
"minecraft:diamond",
"minecraft:netherite_ingot",
];
pub(super) fn is_payment(item: &str) -> bool {
PAYMENT.contains(&item)
}
/// `BeaconMenu.PaymentSlot` and the player inventory, relative to the 176 origin.
pub(super) fn slot_position(i: usize) -> Option<(f32, f32)> {
Some(match i {
@@ -171,7 +169,7 @@ impl Game<'_> {
}
}
}
fn beacon_sound(&mut self, p: [i32; 3], sound: &str) {
pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) {
let at = [
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
@@ -255,9 +253,13 @@ impl Game<'_> {
}
}
fn beacon_levels(&self) -> i32 {
let Some(pos) = self.station.as_ref().map(|s| s.pos) else {
let Some(s) = self.station.as_ref() else {
return 0;
};
if let Some(levels) = s.beacon_levels {
return levels;
}
let pos = s.pos;
match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) {
Some(BlockEntity::Beacon(b)) => b.levels,
_ => 0,
@@ -346,8 +348,16 @@ impl Game<'_> {
self.screen = super::Screen::Playing;
self.capture(true);
}
/// `BeaconMenu.updateEffects`: spend the payment and set the powers.
/// `BeaconMenu.updateEffects`: spend the payment and set the powers. On
/// a server, `BeaconScreen`'s confirm button sends them
/// (`ServerboundSetBeaconPacket`) and the server's menu does it.
fn confirm_beacon(&mut self, sel: [Option<usize>; 2]) {
if self.remote.is_some() {
let id = |e: Option<usize>| e.and_then(|e| self.remote_effect_network_id(EFFECTS[e].0));
let (primary, secondary) = (id(sel[0]), id(sel[1]));
self.send(S::SetBeacon(play::SetBeacon { primary, secondary }));
return;
}
let Some(s) = self.station.as_mut() else {
return;
};
@@ -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
+206 -39
View File
@@ -9,6 +9,7 @@ use horizon_client::{
hud::{HudBatch, rgba},
item_data::WrittenBook,
items::ItemStack,
menu::{Kind, Menu},
text::Text,
ui,
};
@@ -89,6 +90,17 @@ impl Game<'_> {
self.capture(false);
}
pub(super) fn close_book(&mut self) {
// A server's lectern: LecternScreen's menu closes (closeContainer).
if matches!(
self.book,
Some(BookScreen::View {
lectern: Some(_),
..
})
) && self.remote.is_some()
{
self.remote_close_container();
}
self.book = None;
self.capture(true);
}
@@ -319,38 +331,25 @@ impl Game<'_> {
}
}
Some(BookScreen::View {
pages,
page,
lectern,
}) => {
let before = *page;
lectern: Some(key), ..
}) => lectern_page = Some(*key),
Some(BookScreen::View { pages, page, .. }) => {
if forward && *page + 1 < pages.len() {
*page += 1;
} else if !forward && *page > 0 {
*page -= 1;
}
if *page != before
&& let Some(pos) = *lectern
{
lectern_page = Some((pos, *page));
}
}
None => return,
}
// LecternScreen's page buttons click the menu's (1 back, 2 forward);
// the page turns with the server's data slot and level event 1043.
if let Some(key) = lectern_page {
self.lectern_button(key, if forward { 2 } else { 1 });
return;
}
self.audio
.play("minecraft:item.book.page_turn", None, 1.0, 1.0);
if let Some((pos, page)) = lectern_page {
self.set_lectern_page(pos, page as i32);
}
}
/// `LecternBlockEntity.setPage` and `LecternBlock.signalPageChange`.
fn set_lectern_page(&mut self, key: (i32, i32, i32), page: i32) {
if let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) {
l.page = page;
}
self.set_lectern_powered(key, true);
self.lectern_pulses.push((key, 2));
self.container_changed(key);
}
fn set_lectern_powered(&mut self, key: (i32, i32, i32), powered: bool) {
self.set_lectern_property(key, "powered", powered);
@@ -380,6 +379,7 @@ impl Game<'_> {
}
/// The 2-tick pulses of turned lecterns.
pub(super) fn tick_lecterns(&mut self) {
self.follow_lectern();
let mut done = Vec::new();
for (key, left) in &mut self.lectern_pulses {
*left -= 1;
@@ -452,6 +452,7 @@ impl Game<'_> {
.or_else(|| data.map(|d| d.writable_pages.clone()))
.unwrap_or_default();
let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1));
self.stats.custom("interact_with_lectern", 1);
self.open_book(BookScreen::View {
pages,
page,
@@ -459,24 +460,189 @@ impl Game<'_> {
});
true
}
/// `LecternMenu` "Take Book".
fn take_lectern_book(&mut self, key: (i32, i32, i32)) {
let book = match self.world.block_entities.get_mut(&key) {
Some(BlockEntity::Lectern(l)) => {
l.page = 0;
l.book.take()
/// A `LecternMenu` button of the open lectern screen: on a server it is
/// sent (`handleInventoryButtonClick`); here the lectern's menu takes it
/// with the player's inventory, and the screen follows the block entity.
fn lectern_button(&mut self, key: (i32, i32, i32), id: i32) {
if self.remote.is_some() {
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) {
self.send(
horizon_protocol::packets::play::Serverbound::ContainerButtonClick(
horizon_protocol::packets::play::ContainerButtonClick {
container: *container,
button: id,
},
),
);
}
_ => None,
};
if let Some(book) = book
&& let Some(rest) = self.give(book)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40);
return;
}
let Some(mut menu) = self.lectern_menu(key) else {
return;
};
for i in 0..36 {
menu.set_player_item(i, self.inventory[i].clone());
}
menu.set_player_item(40, self.offhand.clone());
menu.creative = self.creative;
menu.selected = self.selected;
menu.may_build = self.may_build();
if !menu.button(&self.menu_env(), id) {
return;
}
for i in 0..36 {
self.inventory[i] = menu.player_item(i).cloned();
}
self.offhand = menu.player_item(40).cloned();
for stack in std::mem::take(&mut menu.dropped) {
self.player_drop(stack);
}
self.lectern_menu_done(key, &menu);
self.follow_lectern();
}
/// The `book` control command: a button of the open book or lectern
/// screen (the page arrows, Take Book, Done), then its page.
pub(super) fn book_control(
&mut self,
action: Option<&str>,
) -> horizon_client::Result<serde_json::Value> {
let lectern = match &self.book {
Some(BookScreen::View { lectern, .. }) => *lectern,
Some(BookScreen::Edit { .. }) => None,
None => return Err("no book is open".into()),
};
match action {
None => {}
Some("next") => self.turn_page(true),
Some("back") => self.turn_page(false),
Some("take") => match lectern {
Some(key) => self.lectern_button(key, 3),
None => return Err("not a lectern".into()),
},
Some("done") => self.close_book(),
Some(other) => return Err(format!("unknown book button {other}").into()),
}
Ok(match &self.book {
Some(BookScreen::View {
pages,
page,
lectern,
}) => serde_json::json!({
"page": page, "pages": pages.len(), "lectern": lectern.map(|k| [k.0, k.1, k.2]),
}),
Some(BookScreen::Edit { pages, page, .. }) => {
serde_json::json!({ "page": page, "pages": pages.len(), "lectern": null })
}
None => serde_json::json!({ "closed": true }),
})
}
/// A server's `minecraft:lectern` menu: LecternScreen, its book and
/// page to come (`remote_lectern_book`, `remote_lectern_page`).
pub(super) fn remote_open_lectern(&mut self, key: (i32, i32, i32)) {
self.open_book(BookScreen::View {
pages: Vec::new(),
page: 0,
lectern: Some(key),
});
}
/// `LecternScreen.bookChanged`: the menu's book slot.
pub(super) fn remote_lectern_book(&mut self, book: Option<ItemStack>) {
if let Some(BookScreen::View {
lectern: Some(_),
pages,
page,
}) = self.book.as_mut()
{
let data = book.as_ref().and_then(ItemStack::data);
*pages = data
.and_then(|d| d.written.as_ref().map(|w| w.pages.clone()))
.or_else(|| data.map(|d| d.writable_pages.clone()))
.unwrap_or_default();
*page = (*page).min(pages.len().saturating_sub(1));
}
}
/// `LecternScreen.pageChanged`: the menu's page data slot.
pub(super) fn remote_lectern_page(&mut self, value: i32) {
if let Some(BookScreen::View {
lectern: Some(_),
pages,
page,
}) = self.book.as_mut()
{
*page = (value.max(0) as usize).min(pages.len().saturating_sub(1));
}
}
/// The server closed its lectern menu; false when none is open.
pub(super) fn remote_lectern_closed(&mut self) -> bool {
if !matches!(
self.book,
Some(BookScreen::View {
lectern: Some(_),
..
})
) {
return false;
}
if let Some(r) = self.remote.as_mut() {
r.menu = None;
r.menu_title = None;
}
self.book = None;
self.capture(true);
true
}
/// `LecternMenu` over the lectern at `key` (the menu engine, for the
/// local player and LAN guests alike): its book and page.
pub(super) fn lectern_menu(&self, key: (i32, i32, i32)) -> Option<Menu> {
let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get(&key) else {
return None;
};
let mut menu = Menu::new(Kind::Lectern);
menu.set_slot(&self.menu_env(), 0, l.book.clone());
menu.data[0] = l.page;
Some(menu)
}
/// The lectern menu's book and page back in the block entity: a new page
/// is `LecternBlock.signalPageChange` (the 2-tick pulse, level event
/// 1043), a book gone `onBookItemRemove` (`resetBookState`).
pub(super) fn lectern_menu_done(&mut self, key: (i32, i32, i32), menu: &Menu) {
let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) else {
return;
};
let (had, before) = (l.book.is_some(), l.page);
l.book = menu.slot(0).cloned();
l.page = menu.data[0];
if had && l.book.is_none() {
self.set_lectern_powered(key, false);
self.set_lectern_property(key, "has_book", false);
self.container_changed(key);
} else if menu.data[0] != before {
self.set_lectern_powered(key, true);
self.lectern_pulses.push((key, 2));
self.level_event_at(1043, [key.0, key.1, key.2], 0);
self.container_changed(key);
}
}
/// The open lectern screen follows its block entity (`LecternScreen`'s
/// menu listener): the page, and closing once the book is gone.
pub(super) fn follow_lectern(&mut self) {
let Some(BookScreen::View {
lectern: Some(key),
page,
pages,
}) = self.book.as_mut()
else {
return;
};
if self.remote.is_some() {
return;
}
match self.world.block_entities.get(key) {
Some(BlockEntity::Lectern(l)) if l.book.is_some() => {
*page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1));
}
_ => self.close_book(),
}
self.set_lectern_property(key, "has_book", false);
self.container_changed(key);
self.close_book();
}
pub(super) fn book_click(&mut self, size: [u32; 2]) {
let b = HudBatch::new(size);
@@ -537,7 +703,8 @@ impl Game<'_> {
self.close_book();
} else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) {
click(self);
self.take_lectern_book(key);
// LecternScreen's Take Book: the menu's button 3.
self.lectern_button(key, 3);
}
} else if inside((w - 200.0) / 2.0, 196.0, 200.0, 20.0) {
click(self);
+68 -58
View File
@@ -1,70 +1,80 @@
//! The cartography table (`CartographyTableMenu`, `CartographyTableScreen`):
//! zooming a map out with paper, cloning it with an empty map, locking it
//! with a glass pane, the post-processing on take (`MapItem.scaleMap`,
//! `lockMap`) and the preview with its error and lock sprites.
//! The cartography table (`CartographyTableMenu` on the menu engine,
//! `CartographyTableScreen`): zooming a map out with paper, cloning it with
//! an empty map, locking it with a glass pane. The engine reads the level's
//! maps through `LevelMaps`; the scaled and locked copies a take makes
//! (`MapItem.scaleMap`, `lockMap`) are registered after the click. The
//! screen draws the preview with its error and lock sprites.
use super::{
Game,
maps::{MapData, map_id},
stations::Station,
};
use horizon_client::{hud::HudBatch, items::ItemStack};
use horizon_client::{hud::HudBatch, items::ItemStack, menu::Maps};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
};
/// The level's maps as a menu sees them (`ContainerLevelAccess`): the
/// states of the maps the click can reach, and the copies it makes.
pub(super) struct LevelMaps {
states: RefCell<HashMap<i32, (bool, u8)>>,
next_id: Cell<i32>,
/// (new id, source id, scaled) for each copy made.
made: RefCell<Vec<(i32, i32, bool)>>,
}
impl Maps for LevelMaps {
fn state(&self, id: i32) -> Option<(bool, u8)> {
self.states.borrow().get(&id).copied()
}
fn derive(&self, id: i32, scale: bool) -> Option<i32> {
let (_, s) = self.state(id)?;
let new = self.next_id.get();
self.next_id.set(new + 1);
let made = if scale {
(false, (s + 1).min(4))
} else {
(true, s)
};
self.states.borrow_mut().insert(new, made);
self.made.borrow_mut().push((new, id, scale));
Some(new)
}
}
impl Game<'_> {
/// `setupResultSlot`.
pub(super) fn cartography_result(&self, s: &Station) -> Option<ItemStack> {
let (map, extra) = (s.inputs[0].as_ref()?, s.inputs[1].as_ref()?);
let data = self.maps.data.get(&map_id(map)?)?;
match &*extra.item {
"minecraft:paper" if !data.locked && data.scale < 4 => Some(ItemStack {
count: 1,
..map.clone()
}),
"minecraft:glass_pane" if !data.locked => Some(ItemStack {
count: 1,
..map.clone()
}),
"minecraft:map" => Some(ItemStack {
count: 2,
..map.clone()
}),
_ => None,
/// The maps of `stacks` (loaded as needed) for a menu over this level.
pub(super) fn level_maps<'s>(
&mut self,
stacks: impl IntoIterator<Item = &'s ItemStack>,
) -> LevelMaps {
let ids: Vec<i32> = stacks.into_iter().filter_map(map_id).collect();
let mut states = HashMap::new();
for id in ids {
if let Some(m) = self.map(id) {
states.insert(id, (m.locked, m.scale));
}
}
LevelMaps {
states: RefCell::new(states),
next_id: Cell::new(self.peek_map_id()),
made: RefCell::new(Vec::new()),
}
}
/// `onCraftedPostProcess` for the taken result: a scaled or locked copy
/// under a new map id. Also spends the inputs' extra item kind check.
pub(super) fn cartography_post(&mut self, mut result: ItemStack) -> ItemStack {
let extra = self
.station
.as_ref()
.and_then(|s| s.inputs[1].as_ref())
.map(|e| e.item.clone());
let Some(id) = map_id(&result) else {
return result;
};
let new = match extra.as_deref() {
Some("minecraft:paper") => self.map(id).map(|m| m.scaled()),
Some("minecraft:glass_pane") => self.map(id).map(|m| m.locked_copy()),
_ => None,
};
if let Some(data) = new {
let new_id = self.new_map_id(data);
result.data_mut().map_id = Some(new_id);
/// The scaled and locked copies a menu made (`level.setMapData`).
pub(super) fn register_made_maps(&mut self, maps: LevelMaps) {
for (id, source, scale) in maps.made.into_inner() {
let Some(data) = self
.map(source)
.map(|m| if scale { m.scaled() } else { m.locked_copy() })
else {
continue;
};
let new = self.new_map_id(data);
debug_assert_eq!(new, id, "map ids follow peek_map_id");
}
result
}
/// The take sound (once per tick).
pub(super) fn cartography_taken(&mut self, pos: [i32; 3]) {
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
self.audio.play(
"minecraft:ui.cartography_table.take_result",
Some(at),
1.0,
1.0,
);
}
/// `CartographyTableScreen.extractBackground` after the background.
pub(super) fn draw_cartography(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) {
+11 -2
View File
@@ -524,13 +524,22 @@ impl Game<'_> {
Screen::Inventory if self.recipe_search_focused() => {
self.recipe_text(Some(text), false)
}
// The anvil's rename box.
Screen::Inventory
if self
.station
.as_ref()
.is_some_and(|s| s.kind == super::stations::Kind::Anvil) =>
{
self.station_text(Some(text), false)
}
Screen::Creative if self.creative_screen.tab().search => {
// As typed: replaces a selected query, keeps the length limit.
self.creative_search_edit(Some(text), false)
}
_ => {
return Err(
"type needs the chat screen (key t tap), the language search, the creative search or World Options".into(),
"type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(),
);
}
}
@@ -913,7 +922,7 @@ impl Game<'_> {
"chunks": self.world.chunks.len(),
"mobs": self.mobs.len(),
"block_entities": self.world.block_entities.len(),
"pending_chunks": self.streaming.pending() + self.pending_uploads.len(),
"pending_chunks": self.streaming.pending() + self.pending_uploads.len() + self.remote_backlog(),
"generated_chunks": self.streaming.generated_total,
"meshed_sections": self.streaming.meshed_total,
"streaming": self.streaming.stages().into_iter().map(|(k, v)| (k.to_string(), v.into())).collect::<serde_json::Map<_, _>>(),
+38 -9
View File
@@ -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::<u32, u32>::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<u32> =
mobs.iter().map(|m| m.id).collect();
bindings.retain(|id, _| live.contains(id));
host.mob_players = bindings;
}
self.mobs.append(&mut mobs);
@@ -2107,15 +2125,22 @@ impl Game<'_> {
let from = pl.position;
self.spawn_mob("minecraft:endermite", [from.x, from.y, from.z], false);
}
// To where the pearl started its last tick (oldPosition).
let to = p.previous;
if let Some(pl) = self.player.as_mut() {
pl.position = at;
pl.position = to;
pl.velocity = Vec3::ZERO;
pl.fall_distance = 0.0;
pl.teleported = true;
}
self.previous_position = at;
self.previous_position = to;
self.hurt_player_by("minecraft:ender_pearl", 5.0);
self.audio
.play("minecraft:entity.player.teleport", Some(atp), 1.0, 1.0);
self.audio.play(
"minecraft:entity.player.teleport",
Some([to.x, to.y, to.z]),
1.0,
1.0,
);
}
}
(ProjectileKind::SmallFireball, hit) => match hit {
@@ -2922,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.
+1 -1
View File
@@ -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 = [
@@ -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;
+5 -40
View File
@@ -138,47 +138,12 @@ impl Game<'_> {
}
}
/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times,
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
pub(super) fn end_sky_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::with_capacity(6 * 256 * 4);
let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else {
/// SkyRenderer.renderEndFlash, drawn after the renderer's resident sky mesh.
pub(super) fn end_flash_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::new();
// The old combined sky/flash draw also skipped the flash without a sky sprite.
if !self.gui.atlas.sprites.contains_key("environment/end_sky") {
return out;
};
use std::f32::consts::FRAC_PI_2;
let faces = [
glam::Mat4::IDENTITY,
glam::Mat4::from_rotation_x(FRAC_PI_2),
glam::Mat4::from_rotation_x(-FRAC_PI_2),
glam::Mat4::from_rotation_x(std::f32::consts::PI),
glam::Mat4::from_rotation_z(FRAC_PI_2),
glam::Mat4::from_rotation_z(-FRAC_PI_2),
];
let step = 200.0 / 16.0;
for pose in faces {
for a in 0..16 {
for b in 0..16 {
let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32);
let (x1, z1) = (x0 + step, z0 + step);
let corners = [
(x0, z0, [r.u0, r.v0]),
(x0, z1, [r.u0, r.v1]),
(x1, z1, [r.u1, r.v1]),
(x1, z0, [r.u1, r.v0]),
];
for (x, z, uv) in corners {
let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z));
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 2,
color: 0xFF28_2828,
light: 0,
});
}
}
}
}
// SkyRenderer.renderEndFlash: the end_flash sprite at height 100, scale 60.
let intensity = self.end.flash.intensity(self.clock.fraction() as f32);
+4 -3
View File
@@ -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},
+18 -1
View File
@@ -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<String, Rect>,
skins: &'a RefCell<horizon_client::skins::Downloader>,
}
impl SpecialHost for Host<'_> {
fn banner_texture(&self, pattern: &str) -> Option<String> {
@@ -138,6 +141,18 @@ impl SpecialHost for Host<'_> {
.pattern(pattern)
.map(|_| self.banners.shield_texture(pattern))
}
fn player_skin(&self, profile: &Value) -> Option<String> {
// 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.
+49 -75
View File
@@ -10,7 +10,7 @@ use horizon_client::{
self, Lan, MAX_PLAYERS, NetConfig,
chunks::ChunkEncoder,
data::SyncData,
entity::EntityState,
entity::{EntityState, States},
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
playerdata,
},
@@ -69,6 +69,9 @@ pub(super) struct LanHost {
/// Guests' commands waiting for the hub to be back in `self.lan`, where
/// a command can reach every player (game/lan_actions.rs).
pub commands: Vec<super::lan_actions::GuestCommand>,
/// The entities the guests track, described again every tick
/// (`lan_entities`) over last tick's states.
states: lan::entity::States,
}
/// The player who owns an integrated server's world: a guest whose state is
@@ -136,8 +139,7 @@ fn baby_index(kind: &str) -> Option<u8> {
/// A mob's synched data as ServerEntity sends it (only the values that differ
/// from the defaults the client constructs), with vanilla's entry indices:
/// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses.
fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
let mut meta = Vec::new();
fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
let kind = m.kind.id.as_str();
if m.fire_ticks > 0 {
meta.push((0, serializer::BYTE, Value::Byte(1)));
@@ -280,14 +282,16 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
}
_ => {}
}
meta
}
/// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand,
/// off hand, feet, legs, chest, head, body, saddle).
fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option<horizon_protocol::item::Stack>)> {
fn mob_equipment(
m: &Mob,
hub: &mut Hub,
out: &mut Vec<(u8, Option<horizon_protocol::item::Stack>)>,
) {
let e = &m.extra;
let mut out = Vec::new();
let slots = [
(0u8, &e.main_hand),
(1, &e.off_hand),
@@ -316,7 +320,6 @@ fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option<horizon_protocol::it
});
out.push((7, hub.stack(&Some(stack))));
}
out
}
pub const HELP: &[&str] = &[
@@ -537,6 +540,7 @@ impl Game<'_> {
waypoints: Default::default(),
waypoint_dead: Default::default(),
commands: Vec::new(),
states: Default::default(),
});
self.audio.capture = Some(Vec::new());
Ok(())
@@ -740,77 +744,44 @@ impl Game<'_> {
equipment,
health: p.health.health(),
attributes: horizon_client::lan::attributes::syncable(&p.attributes),
living_flags: living_flags(self.using),
// Bit 4: Riptide's spin (LivingEntity.isAutoSpinAttack).
living_flags: living_flags(self.using)
| if p.auto_spin_attack_ticks > 0 { 4 } else { 0 },
bed: self.sleeping,
})
}
/// The entities guests track: mobs, items and the rest (game/lan_entities.rs).
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub) -> Vec<EntityState> {
let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len());
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub, out: &mut States) {
out.clear();
for m in self.mobs.iter().filter(|m| !m.removed) {
let kind = m.kind.id.as_str();
let meta = mob_meta(m, hub);
let equipment = mob_equipment(m, hub);
let attributes = self.mob_attributes(m);
let (yaw, pitch) = (m.yaw, m.head_pitch);
out.push(EntityState {
id: m.id as i32,
uuid: entity_uuid(m.id),
kind: kind.to_owned(),
position: [m.position.x, m.position.y, m.position.z],
yaw,
pitch,
head_yaw: m.head_yaw,
on_ground: m.on_ground,
velocity: [m.velocity.x, m.velocity.y, m.velocity.z],
data: 0,
meta,
equipment,
attributes,
precise: false,
});
let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str());
e.position = [m.position.x, m.position.y, m.position.z];
(e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw);
e.on_ground = m.on_ground;
e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z];
mob_meta(m, hub, &mut e.meta);
mob_equipment(m, hub, &mut e.equipment);
self.mob_attributes(m, &mut e.attributes);
}
for d in &self.dropped {
let stack = hub.stack(&Some(d.stack.clone()));
out.push(EntityState {
id: d.id as i32,
uuid: entity_uuid(d.id),
kind: "minecraft:item".to_owned(),
position: [d.position.x, d.position.y, d.position.z],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: d.on_ground,
velocity: [d.velocity.x, d.velocity.y, d.velocity.z],
data: 0,
meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))],
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
});
let e = out.add(d.id as i32, entity_uuid(d.id), "minecraft:item");
e.position = [d.position.x, d.position.y, d.position.z];
e.on_ground = d.on_ground;
e.velocity = [d.velocity.x, d.velocity.y, d.velocity.z];
e.meta.push((8, serializer::ITEM_STACK, Value::Item(stack)));
}
for o in &self.orbs {
out.push(EntityState {
id: o.id as i32,
uuid: entity_uuid(o.id),
kind: "minecraft:experience_orb".to_owned(),
position: [o.position.x, o.position.y, o.position.z],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: o.on_ground,
velocity: [o.velocity.x, o.velocity.y, o.velocity.z],
data: 0,
// ExperienceOrb.DATA_VALUE.
meta: vec![(8, serializer::INT, Value::Int(o.value as i32))],
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
});
let e = out.add(o.id as i32, entity_uuid(o.id), "minecraft:experience_orb");
e.position = [o.position.x, o.position.y, o.position.z];
e.on_ground = o.on_ground;
e.velocity = [o.velocity.x, o.velocity.y, o.velocity.z];
// ExperienceOrb.DATA_VALUE.
e.meta
.push((8, serializer::INT, Value::Int(o.value as i32)));
}
self.lan_object_states(host_entity, hub, &mut out);
out
self.lan_object_states(host_entity, hub, out);
}
/// Run the hub for this tick and apply what the guests did.
@@ -832,21 +803,23 @@ impl Game<'_> {
// A dedicated server runs the hub without a host player.
if state.is_some() || host.hub.config.dedicated {
let has_guests = !host.hub.guests.is_empty();
let entities = if has_guests {
let mut states = std::mem::take(&mut host.states);
if has_guests {
let host_entity = state.as_ref().map(|s| s.entity_id);
self.lan_assign_ids();
self.lan_riding(host_entity, &mut host.hub.riding);
self.lan_entities(host_entity, &mut host.hub)
self.lan_entities(host_entity, &mut host.hub, &mut states);
} else {
Vec::new()
};
states.clear();
}
let entities = states.as_slice();
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
let clock_rate = self.network_clock_rate();
let mut ctx = TickCtx {
world: &mut self.world,
host: state.as_ref(),
entities: &entities,
entities,
next_entity: &mut self.next_entity,
spawn,
difficulty: i32::from(self.ui.difficulty),
@@ -887,7 +860,7 @@ impl Game<'_> {
self.lan_log_event(event);
}
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn);
self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn);
if self.options.dedicated.is_some()
&& let Some(g) = host.hub.guest(conn)
{
@@ -952,6 +925,7 @@ impl Game<'_> {
}
}
}
host.states = states;
}
self.lan_flush_effects(&mut host);
self.tick_guests(&mut host);
@@ -1011,15 +985,15 @@ impl Game<'_> {
g.dimension = in_place;
}
self.load_guest_records(host, conn);
let theirs;
let mut theirs = States::default();
let entities = if elsewhere {
if let Err(e) = self.enter_level(Some(host), level) {
log::error!("could not open {}: {e}", level.id());
return;
}
// A dedicated server has no host player.
theirs = self.lan_entities(None, &mut host.hub);
&theirs[..]
self.lan_entities(None, &mut host.hub, &mut theirs);
theirs.as_slice()
} else {
entities
};
+48 -4
View File
@@ -53,6 +53,10 @@ pub(super) struct GuestPlay {
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
/// The inventory menu and the crafting table the guest crafts in.
pub(super) crafting: super::lan_crafting::GuestCrafting,
/// The workstation menu the guest has open (game/lan_stations.rs).
pub(super) station: Option<super::lan_stations::GuestStation>,
/// The lectern the guest reads (game/lan_stations.rs).
pub(super) lectern: Option<super::lan_stations::GuestLectern>,
/// What the guest's body was given for its effects and enchantments.
potions: super::potions::BodyPotions,
/// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw.
@@ -476,7 +480,13 @@ impl Game<'_> {
self.container = container;
self.screen = screen;
self.sign_edit = host_sign;
self.book = host_book;
// A lectern the guest's use opened (LecternBlock.openScreen).
let guest_lectern = match std::mem::replace(&mut self.book, host_book) {
Some(super::books::BookScreen::View {
lectern: Some(key), ..
}) => Some(key),
_ => None,
};
self.command_block_screen = host_command_block;
self.mount_menu = host_mount_menu;
self.keys = host_keys;
@@ -532,12 +542,14 @@ impl Game<'_> {
g.health = m.health.health();
g.food = m.health.food.food;
g.saturation = m.health.food.saturation;
// A teleport (commands) moves the guest.
// A teleport (commands, a pearl) moves the guest; a pearl's is
// sent even to where they stand (ServerPlayer.teleport).
let at = [m.position.x, m.position.y, m.position.z];
m.sprinting = false;
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 {
if moved > 0.0001 || turned || teleported {
host.hub.teleport(i, Some(at));
}
}
@@ -571,6 +583,9 @@ impl Game<'_> {
if let Some(station) = opened_station {
self.lan_station_opened(host, conn, station);
}
if let Some(key) = guest_lectern {
self.lan_open_lectern(host, conn, key);
}
if opened_table {
self.lan_open_crafting(host, conn);
}
@@ -637,6 +652,13 @@ impl Game<'_> {
_ => ("minecraft:furnace", "container.furnace"),
};
(menu, title, Slots::Block(pos))
} else if let Some(BlockEntity::Crafter(_)) = self.world.block_entities.get(&pos) {
// CrafterBlock.useWithoutItem: CrafterMenu over the block entity.
(
"minecraft:crafter_3x3",
"container.crafter",
Slots::Block(pos),
)
} else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) {
// BrewingStandBlock.useWithoutItem: BrewingStandMenu.
(
@@ -679,6 +701,7 @@ impl Game<'_> {
};
// ServerPlayer.openMenu closes the menu that was open.
self.guest_container_closed(host, conn);
self.lan_station_closed(host, conn, None);
host.hub.open_container(
conn,
menu,
@@ -913,6 +936,16 @@ impl Game<'_> {
S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_lectern_click(host, conn, &p) => {}
S::ContainerButtonClick(p) => {
self.lan_station_button(host, conn, p.container, p.button);
}
S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name),
S::ContainerSlotStateChanged(p) => {
self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled);
}
S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary),
S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item),
S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => {
let g = &mut host.hub.guests[gi];
@@ -920,7 +953,10 @@ impl Game<'_> {
self.drop_guest_items(host, gi, vec![c]);
}
}
S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => {
S::ContainerClose(p)
if self.lan_crafting_closed(host, conn, Some(p.container))
|| self.lan_station_closed(host, conn, Some(p.container)) =>
{
let g = &mut host.hub.guests[gi];
if let Some(c) = g.carried.take() {
self.drop_guest_items(host, gi, vec![c]);
@@ -1438,6 +1474,7 @@ impl Game<'_> {
/// Per tick, for every guest: dig, use items, pick up drops, die.
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
self.lan_merchant_tick(host);
self.lan_stations_tick(host);
self.announce_guest_advancements(host);
let conns: Vec<u32> = host
.hub
@@ -1693,6 +1730,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);
@@ -83,17 +83,16 @@ impl Game<'_> {
/// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed
/// modifier, its effects' modifiers, its equipment's, and what
/// `/attribute` changed.
pub(super) fn mob_attributes(&self, m: &Mob) -> Vec<AttributeSnapshot> {
pub(super) fn mob_attributes(&self, m: &Mob, out: &mut Vec<AttributeSnapshot>) {
let kind = m.kind.id.as_str();
let mut out = Vec::new();
if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") {
instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed));
instance(out, a, finalize::base_value(m, Attr::MovementSpeed));
}
if let Some(s) = m.extra.attributes.as_deref() {
for (attr, v) in &s.bases {
if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name()))
{
instance(&mut out, a, *v).base = *v;
instance(out, a, *v).base = *v;
}
}
for x in &s.modifiers {
@@ -101,7 +100,7 @@ impl Game<'_> {
self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name()))
{
add_modifier(
&mut out,
out,
a,
finalize::base_value(m, x.attr),
AttributeModifier {
@@ -122,7 +121,7 @@ impl Game<'_> {
finalize::transient(m, Attr::MovementSpeed),
) {
add_modifier(
&mut out,
out,
a,
finalize::base_value(m, Attr::MovementSpeed),
AttributeModifier {
@@ -150,7 +149,7 @@ impl Game<'_> {
};
let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute));
add_modifier(
&mut out,
out,
a,
start,
AttributeModifier {
@@ -172,10 +171,9 @@ impl Game<'_> {
("chest", e.chest.as_ref()),
("head", e.head.as_ref()),
],
&mut out,
out,
);
self.generic_attributes_of(Target::Mob(m.id), &mut out);
out
self.generic_attributes_of(Target::Mob(m.id), out);
}
/// An armor stand's synced instances: movement speed (its first
+99 -11
View File
@@ -55,6 +55,7 @@ fn load_player(menu: &mut Menu, g: &Guest) {
menu.set_player_item(OFFHAND, g.offhand.clone());
menu.selected = g.selected;
menu.creative = g.creative();
menu.levels = g.xp_level;
menu.carried = g.carried.clone();
}
@@ -83,27 +84,47 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec<ItemStack>) {
}
impl Game<'_> {
fn menu_env(&self) -> Env<'_> {
pub(super) fn menu_env(&self) -> Env<'_> {
Env {
items: self.res.items(),
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
enchantments: &self.res.stations().enchantments,
names: &self.pack.names,
trade: None,
maps: None,
}
}
/// Runs `op` on the guest's menu with their inventory copied in and back.
fn guest_menu_op<R>(
pub(super) fn guest_menu_op<R>(
&mut self,
host: &mut LanHost,
gi: usize,
menu: &mut Menu,
op: impl FnOnce(&mut Menu, &Env) -> R,
) -> R {
let env = self.menu_env();
// The cartography table reads and makes the host level's maps.
let maps = (menu.kind() == Kind::Cartography).then(|| {
let g = &host.hub.guests[gi];
let held: Vec<ItemStack> = (0..menu.slot_count())
.filter_map(|s| menu.slot(s).cloned())
.chain(g.inventory.iter().flatten().cloned())
.chain(g.carried.clone())
.collect();
self.level_maps(&held)
});
let env = Env {
maps: maps.as_ref().map(|m| m as &dyn horizon_client::menu::Maps),
..self.menu_env()
};
load_player(menu, &host.hub.guests[gi]);
let result = op(menu, &env);
if let Some(maps) = maps {
self.register_made_maps(maps);
}
let dropped = std::mem::take(&mut menu.dropped);
let equipped = std::mem::take(&mut menu.equipped);
menu.drops.clear();
@@ -201,8 +222,14 @@ impl Game<'_> {
(Kind::Furnace(recipe), f.items.to_vec())
}
Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()),
Some(BlockEntity::Crafter(c)) => (Kind::CrafterBlock, c.items.to_vec()),
_ => return false,
};
// CrafterBlockEntity.containerData: the disabled slots, then triggered.
let crafter_data = match self.world.block_entities.get(&pos) {
Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)),
_ => None,
};
if host.hub.guests[gi].spectator() {
return true;
}
@@ -219,6 +246,13 @@ impl Game<'_> {
for (k, s) in items.iter().enumerate() {
menu.set_slot(env, k, s.clone());
}
// After the slots: setting a disabled slot (CrafterBlockEntity.setItem) enables it.
if let Some((disabled, triggered)) = crafter_data {
for (k, d) in disabled.iter().enumerate() {
menu.data[k] = i32::from(*d);
}
menu.data[9] = i32::from(triggered);
}
let before: Vec<_> = (0..menu.slot_count())
.map(|s| menu.slot(s).cloned())
.collect();
@@ -241,6 +275,13 @@ impl Game<'_> {
b.items[k] = menu.slot(k).cloned();
}
}
// CrafterBlockEntity.setItem: filling a disabled slot enables it.
Some(BlockEntity::Crafter(c)) => {
for k in 0..9 {
c.items[k] = menu.slot(k).cloned();
c.disabled[k] = menu.data[k] == 1;
}
}
_ => {}
}
host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu));
@@ -248,6 +289,39 @@ impl Game<'_> {
true
}
/// `ServerGamePacketListenerImpl.handleContainerSlotStateChanged`: a
/// guest's crafter slot toggle (`CrafterBlockEntity.setSlotState`) in
/// their open crafter window.
pub(super) fn lan_crafter_slot_state(
&mut self,
host: &mut LanHost,
conn: u32,
window: i32,
slot: i32,
enabled: bool,
) {
let Some(pos) = host
.hub
.guest(conn)
.filter(|g| !g.spectator())
.and_then(|g| g.menu.as_ref())
.filter(|m| window != 0 && m.window == window)
.and_then(|m| match m.slots {
Slots::Block(pos) => Some(pos),
_ => None,
})
else {
return;
};
if let (Some(BlockEntity::Crafter(c)), Ok(slot)) = (
self.world.block_entities.get_mut(&pos),
usize::try_from(slot),
) {
c.set_slot_state(slot, enabled);
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
}
}
/// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe
/// book places a known recipe in their inventory grid or crafting table
/// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items
@@ -331,6 +405,7 @@ impl Game<'_> {
/// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`).
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) {
self.lan_crafting_closed(host, conn, None);
self.lan_station_closed(host, conn, None);
// The container it replaces loses its opener.
self.guest_container_closed(host, conn);
let title = horizon_protocol::text::translatable("container.crafting", &[]);
@@ -430,22 +505,35 @@ impl Game<'_> {
None => return false,
}
};
if grid.is_empty() {
return true;
if !grid.is_empty() {
self.lan_place_back(host, gi, grid);
}
let mut menu = Menu::new(Kind::Inventory);
self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid));
true
}
/// A guest left: what their crafting grids held goes back into their
/// `Inventory.placeItemBackInInventory` of `stacks` for guest `gi`, what
/// doesn't fit dropped (`clearContainer`).
pub(super) fn lan_place_back(&mut self, host: &mut LanHost, gi: usize, stacks: Vec<ItemStack>) {
let mut menu = Menu::new(Kind::Inventory);
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
place_back(menu, env, stacks)
});
}
/// A guest left: what their crafting grids and workstation held goes back into their
/// inventory before it is saved (dropped where they stood if full).
pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) {
let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table);
let play = host.play.remove(&g.conn);
let mut grid: Vec<ItemStack> = g.craft_grid.iter_mut().filter_map(Option::take).collect();
g.craft_result = None;
if let Some((_, _, menu)) = table {
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
if let Some(play) = play {
if let Some((_, _, menu)) = play.crafting.table {
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
}
// A workstation's inputs too.
if let Some(station) = &play.station {
grid.extend(super::lan_stations::station_inputs(station));
}
}
if grid.is_empty() {
return;
@@ -5,7 +5,7 @@
//! synched data that differs from the defaults), and who rides what.
use super::Game;
use horizon_client::lan::{
entity::{EntityState, Riding},
entity::{EntityState, Riding, States},
hub::Hub,
};
use horizon_protocol::entity_data::{Value, serializer};
@@ -107,7 +107,7 @@ impl Game<'_> {
&self,
host_entity: Option<i32>,
hub: &mut Hub,
out: &mut Vec<EntityState>,
out: &mut States,
) {
for b in &self.boats {
let p = b.position;
@@ -268,12 +268,7 @@ impl Game<'_> {
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
/// end crystals, as guests track them.
fn lan_projectile_states(
&self,
host_entity: Option<i32>,
hub: &mut Hub,
out: &mut Vec<EntityState>,
) {
fn lan_projectile_states(&self, host_entity: Option<i32>, hub: &mut Hub, out: &mut States) {
let owner = |who: Option<horizon_client::mobs::Who>| match who {
Some(horizon_client::mobs::Who::Mob(id)) => id as i32,
Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0),
@@ -0,0 +1,672 @@
//! Workstation menus for LAN guests: the screen a guest's use opens runs on
//! the host's menu engine (`horizon_client::menu`), the one single player
//! uses, with vanilla's packets: OpenScreen with the station's `MenuType`,
//! container clicks, `ServerboundContainerButtonClickPacket`, the content and
//! data slot sync after each (`broadcastChanges`), and the inputs back into
//! the inventory when the menu closes (`AbstractContainerMenu.clearContainer`).
use super::{
Game,
lan::LanHost,
lan_crafting::input,
stations::{Kind as StationKind, Station},
};
use horizon_client::{
containers::BlockEntity,
items::ItemStack,
menu::{Kind, Menu},
};
use horizon_core::random::RandomSource;
use horizon_protocol::packets::play::{self, Clientbound as C};
/// A guest's open workstation menu.
pub(super) struct GuestStation {
window: i32,
state: i32,
kind: StationKind,
pos: [i32; 3],
menu: Box<Menu>,
/// The data slots the client was last sent.
sent_data: Vec<i32>,
/// The game time of the menu's last sound (`lastSoundTime`).
last_sound: u64,
}
/// A guest's open lectern: `LecternMenu` over the block entity, made on the
/// menu engine for each click (`Game::lectern_menu`).
pub(super) struct GuestLectern {
window: i32,
state: i32,
key: (i32, i32, i32),
/// The book and page the client was last sent (`broadcastChanges`).
sent: Option<(Option<ItemStack>, i32)>,
}
/// The `MenuType`, the engine's menu and the input slots
/// (`clearContainer`'s container) of a station a guest can use.
fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range<usize>)> {
Some(match kind {
StationKind::Loom => ("minecraft:loom", Kind::Loom, 0..3),
StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1),
StationKind::Grindstone => ("minecraft:grindstone", Kind::Grindstone, 0..2),
StationKind::Anvil => ("minecraft:anvil", Kind::Anvil, 0..2),
StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3),
StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2),
StationKind::Beacon => ("minecraft:beacon", Kind::Beacon, 0..1),
StationKind::Cartography => ("minecraft:cartography_table", Kind::Cartography, 0..2),
_ => return None,
})
}
impl Game<'_> {
/// A workstation a guest's use opened (`ServerPlayer.openMenu`); false
/// when guests can't use that one yet.
pub(super) fn lan_open_station(
&mut self,
host: &mut LanHost,
conn: u32,
station: &Station,
) -> bool {
let Some((menu_type, kind, _)) = menu_of(station.kind) else {
return false;
};
self.lan_station_closed(host, conn, None);
self.lan_crafting_closed(host, conn, None);
// The container it replaces loses its opener.
self.guest_container_closed(host, conn);
let title = horizon_protocol::text::translatable(station.kind.title_key(), &[]);
let Some(window) = host.hub.open_window(conn, menu_type, title) else {
return true;
};
let mut menu = Box::new(Menu::new(kind));
if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn)
&& kind == Kind::Enchanting
{
// Player.enchantmentSeed, made when first needed.
if g.xp_seed == 0 {
g.xp_seed = self.world.random.next_int();
}
menu.data[3] = g.xp_seed;
}
if kind == Kind::Beacon {
menu.data = self.beacon_data(host, station.pos).to_vec();
}
host.play.entry(conn).or_default().station = Some(GuestStation {
window,
state: 0,
kind: station.kind,
pos: station.pos,
menu,
sent_data: Vec::new(),
last_sound: 0,
});
self.lan_send_station(host, conn);
true
}
/// Runs `op` on the guest's open station (window `window`, any when
/// None) with their inventory in it, then sends what changed. False when
/// no such window is open.
fn lan_station_op(
&mut self,
host: &mut LanHost,
conn: u32,
window: Option<i32>,
op: impl FnOnce(&mut Menu, &horizon_client::menu::Env),
) -> bool {
let Some(mut gs) = host
.play
.get_mut(&conn)
.and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w)))
else {
return false;
};
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& !host.hub.guests[gi].spectator()
{
self.guest_menu_op(host, gi, &mut gs.menu, op);
self.lan_station_sounds(&mut gs);
if let Some(amount) = gs.menu.ground.take() {
self.grindstone_taken(gs.pos, amount);
}
self.lan_station_combined(host, conn, &mut gs);
if let Some(button) = gs.menu.enchant_button.take() {
self.lan_enchant(host, gi, &mut gs, button);
}
if std::mem::take(&mut gs.menu.enchant_changed) {
self.lan_enchant_offers(host, gi, &mut gs);
}
}
host.play.entry(conn).or_default().station = Some(gs);
self.lan_send_station(host, conn);
true
}
/// `LecternBlock.openScreen` for a guest: `minecraft:lectern` over the
/// block entity, with its book and page.
pub(super) fn lan_open_lectern(&mut self, host: &mut LanHost, conn: u32, key: (i32, i32, i32)) {
self.lan_station_closed(host, conn, None);
self.lan_crafting_closed(host, conn, None);
self.guest_container_closed(host, conn);
let title = horizon_protocol::text::translatable("container.lectern", &[]);
let Some(window) = host.hub.open_window(conn, "minecraft:lectern", title) else {
return;
};
host.play.entry(conn).or_default().lectern = Some(GuestLectern {
window,
state: 0,
key,
sent: None,
});
self.lan_send_lectern(host, conn, true);
}
/// The lectern's book and page for the client: everything (`all`), or
/// what changed since it was last sent.
fn lan_send_lectern(&mut self, host: &mut LanHost, conn: u32, all: bool) {
let Some(gl) = host.play.get_mut(&conn).and_then(|p| p.lectern.as_mut()) else {
return;
};
let (book, page) = match self.world.block_entities.get(&gl.key) {
Some(BlockEntity::Lectern(l)) => (l.book.clone(), l.page),
_ => (None, 0),
};
let now = Some((book.clone(), page));
if !all && gl.sent == now {
return;
}
let page_changed = gl.sent.as_ref().is_none_or(|(_, p)| *p != page);
gl.sent = now;
gl.state = (gl.state + 1) & 0x7FFF;
let (window, state) = (gl.window, gl.state);
let carried = host
.hub
.guests
.iter()
.find(|g| g.conn == conn)
.and_then(|g| g.carried.clone());
let content = C::ContainerSetContent(play::ContainerSetContent {
container: window,
state,
items: vec![host.hub.stack(&book)],
carried: host.hub.stack(&carried),
});
host.hub.send_to(conn, &content);
if all || page_changed {
host.hub.send_to(
conn,
&C::ContainerSetData(play::ContainerSetData {
container: window,
id: 0,
value: page as i16,
}),
);
}
}
/// Runs `op` on the guest's lectern menu (window `window`) with their
/// inventory, the block entity takes the book and page back, and the
/// client gets what changed. False when no such window is open.
fn lan_lectern_op(
&mut self,
host: &mut LanHost,
conn: u32,
window: i32,
op: impl FnOnce(&mut Menu, &horizon_client::menu::Env),
) -> bool {
let Some(key) = host
.play
.get(&conn)
.and_then(|p| p.lectern.as_ref())
.filter(|l| l.window == window)
.map(|l| l.key)
else {
return false;
};
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& !host.hub.guests[gi].spectator()
&& let Some(mut menu) = self.lectern_menu(key)
{
// Player.mayBuild: survival and creative.
let may_build = matches!(host.hub.guests[gi].game_mode, 0 | 1);
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
menu.may_build = may_build;
op(menu, env);
});
self.lectern_menu_done(key, &menu);
}
self.lan_send_lectern(host, conn, true);
true
}
/// A click on the guest's lectern window; false for other windows.
pub(super) fn lan_lectern_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
self.lan_lectern_op(host, conn, p.container, |menu, env| {
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
})
}
/// The rest of a taken anvil or smithing result's `onTake`: the guest
/// pays the levels, the anvil wears (level event 1030 or 1029), the
/// smithing table sounds (1044).
fn lan_station_combined(&mut self, host: &mut LanHost, conn: u32, gs: &mut GuestStation) {
let change = std::mem::take(&mut gs.menu.level_change);
if change != 0 {
self.as_guest(host, conn, |g| g.give_levels(change));
}
if !std::mem::take(&mut gs.menu.combined) {
return;
}
if gs.kind == StationKind::Smithing {
self.level_event_at(1044, gs.pos, 0);
} else {
let creative = gs.menu.creative;
// A broken anvil closes the menu on the next stillValid check.
self.anvil_used(gs.pos, creative);
}
}
/// `EnchantmentMenu.slotsChanged` with a level: the costs and clues for
/// the guest's seed and the bookshelves around the table.
fn lan_enchant_offers(&mut self, host: &LanHost, gi: usize, gs: &mut GuestStation) {
let seed = host.hub.guests[gi].xp_seed;
let bookcases = self.count_bookshelves(gs.pos);
let offers = horizon_client::stations::enchant_offers(
&self.res.stations().enchantments,
self.res.items(),
seed,
bookcases,
gs.menu.slot(0),
);
for i in 0..3 {
gs.menu.data[i] = offers.costs[i];
let clue = offers.clues[i].as_ref();
gs.menu.data[4 + i] = clue
.and_then(|(e, _)| host.hub.registry_id("minecraft:enchantment", e))
.unwrap_or(-1);
gs.menu.data[7 + i] = clue.map_or(-1, |(_, l)| *l as i32);
}
gs.menu.data[3] = seed;
}
/// `EnchantmentMenu.clickMenuButton`'s `access.execute`: the item gets
/// the offer's enchantments, the guest pays its levels and lapis and
/// gets a new seed, the table sounds, and the offers are made again.
fn lan_enchant(&mut self, host: &mut LanHost, gi: usize, gs: &mut GuestStation, button: usize) {
let Some(item) = gs.menu.slot(0).cloned() else {
return;
};
let g = &host.hub.guests[gi];
let (seed, creative, conn) = (g.xp_seed, g.creative(), g.conn);
let Some(enchanted) = horizon_client::stations::apply_enchantment(
&self.res.stations().enchantments,
self.res.items(),
seed,
button,
gs.menu.data[button],
&item,
) else {
return;
};
let need = button as i32 + 1;
// Player.onEnchantmentPerformed, and EnchantmentMenu's awardStat(ENCHANT_ITEM).
self.as_guest(host, conn, |game| {
game.give_levels(-need);
game.stats.custom("enchant_item", 1);
});
host.hub.guests[gi].xp_seed = self.world.random.next_int();
let env = self.menu_env();
let lapis = gs.menu.slot(1).cloned().filter(|_| !creative).map(|mut l| {
l.count = l.count.saturating_sub(need as u32);
l
});
gs.menu.set_slot(&env, 0, Some(enchanted));
if !creative {
gs.menu.set_slot(&env, 1, lapis.filter(|l| l.count > 0));
}
gs.menu.enchant_changed = false;
self.lan_enchant_offers(host, gi, gs);
let pitch = self.world.random.next_float() * 0.1 + 0.9;
let at = gs.pos.map(|v| f64::from(v) + 0.5);
self.audio.play(
"minecraft:block.enchantment_table.use",
Some(at),
1.0,
pitch,
);
}
/// `ServerGamePacketListenerImpl.handleRenameItem`: the guest's anvil
/// takes the name (`AnvilMenu.setItemName`).
pub(super) fn lan_station_rename(&mut self, host: &mut LanHost, conn: u32, name: &str) {
let anvil = host
.play
.get(&conn)
.and_then(|p| p.station.as_ref())
.is_some_and(|s| s.kind == StationKind::Anvil);
if anvil {
self.lan_station_op(host, conn, None, |menu, env| {
menu.rename(env, name);
});
}
}
/// The sounds the menu played, at the station (heard by everyone around,
/// as `level.playSound(null, pos, ...)`), once per tick.
fn lan_station_sounds(&mut self, gs: &mut GuestStation) {
let sounds = std::mem::take(&mut gs.menu.sounds);
if sounds.is_empty() || gs.last_sound == self.ticks {
return;
}
gs.last_sound = self.ticks;
let at = gs.pos.map(|v| f64::from(v) + 0.5);
for sound in sounds {
self.audio.play(sound, Some(at), 1.0, 1.0);
}
}
/// A click on the guest's station window; false for other windows.
pub(super) fn lan_station_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
self.lan_station_op(host, conn, Some(p.container), |menu, env| {
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
})
}
/// `ServerGamePacketListenerImpl.handleContainerButtonClick`:
/// `clickMenuButton`, then `broadcastChanges` when the menu took it.
pub(super) fn lan_station_button(
&mut self,
host: &mut LanHost,
conn: u32,
window: i32,
id: i32,
) {
// LecternMenu's page buttons and Take Book.
if self.lan_lectern_op(host, conn, window, |menu, env| {
menu.button(env, id);
}) {
return;
}
self.lan_station_op(host, conn, Some(window), |menu, env| {
menu.button(env, id);
});
}
/// The whole station menu and its changed data slots for the client
/// (`sendAllDataToRemote` / `broadcastChanges`).
fn lan_send_station(&mut self, host: &mut LanHost, conn: u32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) else {
return;
};
gs.state = (gs.state + 1) & 0x7FFF;
let own = gs.menu.slot_count() - 36;
let mut items: Vec<Option<ItemStack>> =
(0..own).map(|s| gs.menu.slot(s).cloned()).collect();
let g = &host.hub.guests[gi];
items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone()));
let carried = g.carried.clone();
let packet = C::ContainerSetContent(play::ContainerSetContent {
container: gs.window,
state: gs.state,
items: items.iter().map(|s| host.hub.stack(s)).collect(),
carried: host.hub.stack(&carried),
});
gs.sent_data.resize(gs.menu.data.len(), i32::MIN);
let mut data = Vec::new();
for (k, &v) in gs.menu.data.iter().enumerate() {
if gs.sent_data[k] != v {
gs.sent_data[k] = v;
data.push(C::ContainerSetData(play::ContainerSetData {
container: gs.window,
id: k as i16,
value: v as i16,
}));
}
}
host.hub.send_to(conn, &packet);
for packet in data {
host.hub.send_to(conn, &packet);
}
}
/// `AbstractContainerMenu.removed` of the guest's station (`window`;
/// None closes it whichever it is): the carried stack and the inputs go
/// back to the inventory, what doesn't fit is dropped. False when no such
/// window is open.
pub(super) fn lan_station_closed(
&mut self,
host: &mut LanHost,
conn: u32,
window: Option<i32>,
) -> bool {
// A lectern's menu keeps nothing of its own (the book is the block entity's).
let lectern = host
.play
.get_mut(&conn)
.and_then(|p| p.lectern.take_if(|l| window.is_none_or(|w| l.window == w)));
if lectern.is_some() {
// AbstractContainerMenu.removed: the carried stack goes back.
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& let Some(carried) = host.hub.guests[gi].carried.take()
{
self.lan_place_back(host, gi, vec![carried]);
}
if window.is_some() {
return true;
}
}
let Some(gs) = host
.play
.get_mut(&conn)
.and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w)))
else {
return false;
};
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return true;
};
// AbstractContainerMenu.removed: the carried stack first, then the inputs.
let mut back: Vec<ItemStack> = host.hub.guests[gi].carried.take().into_iter().collect();
let inputs = station_inputs(&gs);
if gs.kind == StationKind::Beacon {
// BeaconMenu.removed drops the payment (player.drop).
if !back.is_empty() {
self.lan_place_back(host, gi, std::mem::take(&mut back));
}
self.drop_guest_items(host, gi, inputs);
} else {
back.extend(inputs);
}
if !back.is_empty() {
self.lan_place_back(host, gi, back);
}
true
}
/// `BeaconBlockEntity.dataAccess`: the pyramid's levels and the powers
/// (`BeaconMenu.encodeEffect`: the `mob_effect` id + 1, 0 for none).
fn beacon_data(&self, host: &LanHost, pos: [i32; 3]) -> [i32; 3] {
let Some(BlockEntity::Beacon(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
else {
return [0; 3];
};
let encode = |e: &Option<String>| {
e.as_deref()
.and_then(|n| host.hub.registry_id("minecraft:mob_effect", n))
.map_or(0, |id| id + 1)
};
[b.levels, encode(&b.primary), encode(&b.secondary)]
}
/// `ServerGamePacketListenerImpl.handleSetBeaconPacket`: the guest's
/// beacon menu takes the powers (`BeaconMenu.updateEffects`), and they
/// become the block entity's (`dataAccess.set`: the power_select sound
/// while the beam is up).
pub(super) fn lan_station_beacon(
&mut self,
host: &mut LanHost,
conn: u32,
primary: Option<i32>,
secondary: Option<i32>,
) {
let Some(pos) = host
.play
.get(&conn)
.and_then(|p| p.station.as_ref())
.filter(|s| s.kind == StationKind::Beacon)
.map(|s| s.pos)
else {
return;
};
// An id the registry doesn't have fails the packet's codec.
let mut powers: [Option<(i32, String)>; 2] = [None, None];
for (k, id) in [primary, secondary].into_iter().enumerate() {
if let Some(id) = id {
let Some(name) = host.hub.registry_name("minecraft:mob_effect", id) else {
return;
};
powers[k] = Some((id, name.to_owned()));
}
}
let data = self.beacon_data(host, pos);
let mut updated = false;
self.lan_station_op(host, conn, None, |menu, env| {
menu.data.copy_from_slice(&data);
let power = |k: usize| powers[k].as_ref().map(|(id, n)| (*id, n.as_str()));
updated = menu.beacon_update(env, power(0), power(1));
});
if !updated {
return;
}
let [primary, secondary] = powers.map(|p| p.map(|(_, n)| n));
let mut select_sound = false;
if let Some(BlockEntity::Beacon(b)) =
self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2]))
{
b.primary = primary;
b.secondary = secondary;
select_sound = !b.sections.is_empty();
}
if select_sound {
self.beacon_sound(pos, "minecraft:block.beacon.power_select");
}
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
}
/// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its
/// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`).
pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) {
self.lan_lecterns_tick(host);
let conns: Vec<u32> = host
.play
.iter()
.filter(|(_, p)| p.station.is_some())
.map(|(c, _)| *c)
.collect();
for conn in conns {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
if !host.hub.here(g) {
continue;
}
let Some(gs) = host.play.get(&conn).and_then(|p| p.station.as_ref()) else {
continue;
};
let [x, y, z] = gs.pos;
let name = &self.res.facts().get(self.world.block(x, y, z)).name;
let block = StationKind::from_block(name) == Some(gs.kind);
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
// The block interaction range (4.5, creative 5) and the buffer.
let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0;
let near = (0..3)
.map(|k| {
let lo = f64::from(gs.pos[k]);
(lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2)
})
.sum::<f64>()
< reach * reach;
if !(block && near) {
let window = gs.window;
self.lan_station_closed(host, conn, Some(window));
host.hub.send_to(
conn,
&C::ContainerClose(play::ContainerClose { container: window }),
);
} else if gs.kind == StationKind::Beacon {
// The beacon's data slots follow its block entity.
let data = self.beacon_data(host, gs.pos);
if let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut())
&& gs.menu.data[..] != data[..]
{
gs.menu.data.copy_from_slice(&data);
self.lan_send_station(host, conn);
}
}
}
}
}
impl Game<'_> {
/// The guests' lecterns each tick: `stillValid` (the block entity, its
/// book, the reach) closes them, and `broadcastChanges` sends a book or
/// page another player changed.
fn lan_lecterns_tick(&mut self, host: &mut LanHost) {
let open: Vec<(u32, i32, (i32, i32, i32))> = host
.play
.iter()
.filter_map(|(c, p)| p.lectern.as_ref().map(|l| (*c, l.window, l.key)))
.collect();
for (conn, window, key) in open {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
if !host.hub.here(g) {
continue;
}
let has_book = matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Lectern(l)) if l.book.is_some()
);
// Container.stillValidBlockEntity: the interaction range and its buffer.
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0;
let pos = [key.0, key.1, key.2];
let near = (0..3)
.map(|k| {
let lo = f64::from(pos[k]);
(lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2)
})
.sum::<f64>()
< reach * reach;
if has_book && near {
self.lan_send_lectern(host, conn, false);
} else {
self.lan_station_closed(host, conn, Some(window));
host.hub.send_to(
conn,
&C::ContainerClose(play::ContainerClose { container: window }),
);
}
}
}
}
/// What `clearContainer` gives back from a station's menu.
pub(super) fn station_inputs(gs: &GuestStation) -> Vec<ItemStack> {
menu_of(gs.kind)
.map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect())
.unwrap_or_default()
}
+10 -3
View File
@@ -55,8 +55,9 @@ impl Game<'_> {
state.session.update_special_prices();
}
let title = self.merchant_display_name(&state);
// The container the trading screen replaces loses its opener.
// The container or workstation the trading screen replaces is closed.
self.guest_container_closed(host, conn);
self.lan_station_closed(host, conn, None);
let Some(window) = host.hub.open_merchant_window(conn, title) else {
self.merchant_closed(&mut state);
return;
@@ -254,7 +255,11 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
enchantments: &self.res.stations().enchantments,
names: &self.pack.names,
trade: Some(&trade_env),
maps: None,
};
let mut menu = Menu::new(Kind::Merchant);
{
@@ -393,8 +398,8 @@ impl Game<'_> {
});
}
}
/// Takes a station a guest's action opened: a trading screen goes to the
/// guest; other stations are not shown to guests yet.
/// Takes a station a guest's action opened: a trading screen or a
/// workstation menu goes to the guest (game/lan_stations.rs).
pub(super) fn lan_station_opened(
&mut self,
host: &mut LanHost,
@@ -406,6 +411,8 @@ impl Game<'_> {
&& let Some(m) = station.merchant.take()
{
self.lan_open_merchant(host, conn, *m);
return;
}
self.lan_open_station(host, conn, &station);
}
}
+1 -6
View File
@@ -312,15 +312,10 @@ impl Game<'_> {
.map_or_else(String::new, |(end, start)| {
format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0)
});
let list: Vec<String> = spans
.iter()
.filter(|(_, ms)| *ms >= 0.5)
.map(|(n, ms)| format!("{n} {ms:.1}"))
.collect();
log::info!(
"Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}",
self.mobs.len(),
list.join(", ")
horizon_client::spans::describe(&spans)
);
}
result
+11 -74
View File
@@ -5,14 +5,8 @@
//! 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],
@@ -349,71 +343,14 @@ impl Game<'_> {
|| e.stack.item.contains("netherite")
});
}
/// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8
/// segments of 16 blocks, from the bolt's seed.
pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let white = self.gui.atlas.font.white();
let uv = [white.u0, white.v0];
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
for b in &self.bolts {
let o = (glam::DVec3::from_array(b.at) - camera).as_vec3();
let mut random = LegacyRandom::new(b.seed);
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
let (mut x_off, mut z_off) = (0f32, 0f32);
for i in (0..8).rev() {
xs[i] = x_off;
zs[i] = z_off;
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
}
for layer in 0..4 {
let mut random = LegacyRandom::new(b.seed);
for branch in 0..3 {
let trunk = branch == 0;
let start = 7 - branch;
let end = if trunk { 0 } else { start - 3 + 1 };
let mut sx = xs[start] - x_off;
let mut sz = zs[start] - z_off;
for segment in (end..=start).rev() {
let (ex, ez) = (sx, sz);
let spread = if trunk { 11 } else { 31 };
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
let mut top = 0.1 + layer as f32 * 0.2;
let mut bottom = top;
if trunk {
top *= segment as f32 * 0.1 + 1.0;
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
}
for (rx, rz, lx, lz) in [
(false, false, true, false),
(true, false, true, true),
(true, true, false, true),
(false, true, false, false),
] {
let s = |p: bool, r: f32| if p { r } else { -r };
let y0 = segment as f32 * 16.0;
let corners = [
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
];
for c in corners {
out.push(Vertex {
normal: [0; 4],
pos: (o + glam::Vec3::from_array(c)).to_array(),
uv,
layer: 2,
color,
light: 240 | 240 << 8,
});
}
}
}
}
}
}
/// Simulation-order render inputs; seeded geometry lives in the renderer.
pub(super) fn bolt_instances(&self) -> Vec<horizon_client::gfx::lightning::Bolt> {
self.bolts
.iter()
.map(|b| horizon_client::gfx::lightning::Bolt {
at: b.at,
seed: b.seed,
})
.collect()
}
}
+4 -2
View File
@@ -68,8 +68,9 @@ impl Game<'_> {
}
l.last_inputs = inputs;
}
/// A sound the loom menu played: the result's once per tick.
pub(super) fn loom_sound(&mut self, sound: &str) {
/// A sound the loom or stonecutter menu played: the result's once per
/// tick (`lastSoundTime`).
pub(super) fn station_sound(&mut self, sound: &str) {
let ticks = self.ticks;
let Some(s) = self.station.as_mut() else {
return;
@@ -98,6 +99,7 @@ impl Game<'_> {
if taken {
self.audio
.play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0);
self.remote_station_button(index as i32);
}
taken
}
+164
View File
@@ -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<u32>)>,
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<ItemEntity> = (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<bool> = 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<bool> = 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<ItemEntity> = 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}");
}
}
@@ -8,6 +8,7 @@ use horizon_client::{
containers::Crafter,
hud::{HudBatch, rgba},
};
use horizon_protocol::packets::play::{self, Serverbound as S};
use serde_json::Value;
/// `CrafterBlock`'s crafting animation length.
@@ -323,6 +324,15 @@ impl Game<'_> {
menu.set_slot_state(i, enabled);
Some(true)
});
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.clone()) {
self.send(S::ContainerSlotStateChanged(
play::ContainerSlotStateChanged {
slot: i as i32,
container,
enabled,
},
));
}
let pitch = if enabled { 1.0 } else { 0.75 };
self.audio
.play("minecraft:ui.button.click", None, 0.4, pitch);
+31
View File
@@ -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"))
+68 -3
View File
@@ -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,
@@ -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<Vec<Aabb>>,
/// The types and boxes of what a spawner created this tick.
pub(super) pending_ids: std::cell::RefCell<Vec<(String, Aabb)>>,
/// 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<MobBoxes>,
pub(super) box_queries: std::cell::Cell<u32>,
}
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<MobBox>,
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<Item = MobBox> + '_ {
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<dyn Iterator<Item = MobBox> + '_> {
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)))
@@ -191,7 +256,13 @@ impl NaturalLevel for GameLevel<'_, '_> {
StructureSpawns::shared(&self.game.options.resources)
}
fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option<f64> {
nearest_player(&self.players, x, y, z).map(|p| p.distance_sqr(x, y, z))
// The nearest player's distance (`nearest_player`), without finding
// which player it is: every spawn attempt asks.
self.players
.iter()
.filter(|p| !p.spectator)
.map(|p| p.distance_sqr(x, y, z))
.reduce(f64::min)
}
fn respawn(&self) -> Option<[i32; 3]> {
// The world spawn point lives in the overworld.
@@ -218,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()
@@ -238,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")
@@ -283,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
@@ -305,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
@@ -312,6 +312,7 @@ impl Game<'_> {
let crouching = p.pose == Pose::Crouching;
let (position, flying) = (p.position, p.flying || p.fall_flying);
let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity);
let spinning = p.auto_spin_attack_ticks > 0;
let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0);
let using_off_hand = self
.using
@@ -397,6 +398,7 @@ impl Game<'_> {
m.velocity = velocity;
m.extra.fall_flying = fall_flying;
m.extra.fall_fly_ticks = fly_ticks;
m.extra.auto_spin_attack = spinning;
m.extra.main_hand_left = self.settings.main_hand_left;
m.extra.using_item = using;
m.extra.using_off_hand = using_off_hand;
@@ -451,6 +453,7 @@ impl Game<'_> {
out,
);
self.player_elytra_geometry(m, camera, alpha as f32, packed, out);
self.spin_attack_geometry(m, camera, alpha as f32, packed, out);
self.held_item_geometry(m, camera, alpha, packed, true, out);
}
/// `extractEntityInInventoryFollowsMouse`: the player in the box
@@ -592,6 +595,47 @@ impl Game<'_> {
out,
);
}
/// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning
/// player (`SpinAttackEffectModel.setupAnim`).
fn spin_attack_geometry(
&self,
m: &Mob,
camera: glam::DVec3,
partial: f32,
light: u32,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
if !m.extra.auto_spin_attack {
return;
}
let (Some(model), Some(rect)) = (
self.res.spin_attack().as_ref(),
self.gui.atlas.sprites.get("entity/trident/trident_riptide"),
) else {
return;
};
let age = m.age as f32 + partial;
horizon_client::mobs::render_model(
model,
horizon_client::mobs::render::base_transform(m, partial, camera),
&|part| {
let mut p = part.pose;
if let Some(i) = part
.name
.strip_prefix("box")
.and_then(|i| i.parse::<u8>().ok())
{
let angle = age * -(45.0 + f32::from(i + 1) * 5.0);
p[4] = wrap(angle).to_radians();
}
p
},
[rect.u0, rect.v0, rect.u1, rect.v1],
light,
0,
out,
);
}
}
fn player_preview_quads(
+13 -1
View File
@@ -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<u32>)>, Vec<bool>) = (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));
@@ -279,7 +279,11 @@ impl Game<'_> {
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
station_recipes: &self.res.stations().recipes,
enchantments: &self.res.stations().enchantments,
names: &self.pack.names,
trade: None,
maps: None,
};
for i in 0..36 {
menu.set_player_item(i, self.inventory[i].clone());
+595 -88
View File
@@ -7,7 +7,7 @@
//! client predicts its own movement; the server stays authoritative for
//! everything else.
use super::{Dim, Game, Mining, Screen};
use horizon_client::first_person::Hand;
use horizon_client::first_person::{Hand, SwingAnimation};
use horizon_client::{
Result,
chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy},
@@ -41,7 +41,11 @@ use horizon_protocol::{
text::{Language, format_java, plain},
};
use horizon_world::{nbt::Tag, registry::BlockStateId};
use std::{collections::HashMap, sync::Arc, time::Instant};
use std::{
collections::{HashMap, VecDeque},
sync::Arc,
time::{Duration, Instant},
};
use winit::{event::MouseButton, keyboard::KeyCode};
/// A text component the server sent, for the HUD.
@@ -112,9 +116,9 @@ pub(super) struct Remote {
/// only replace the remembered state; then the block takes it.
predictions: HashMap<[i32; 3], (i32, i32)>,
/// Open container: (window id, menu name).
menu: Option<(i32, String)>,
pub(super) menu: Option<(i32, String)>,
/// The open menu's title as the server named it.
menu_title: Option<String>,
pub(super) menu_title: Option<String>,
state_id: i32,
use_target: Option<[i32; 3]>,
entities: HashMap<i32, Tracked>,
@@ -136,6 +140,8 @@ pub(super) struct Remote {
tab_players: HashMap<u128, horizon_client::tab_list::TabPlayer>,
/// Each listed profile's unpacked `textures` property.
skin_textures: HashMap<u128, horizon_client::skins::Textures>,
/// The skin texture each profile's players show, once its download is ready.
skins: HashMap<u128, String>,
listed: std::collections::HashSet<u128>,
/// `ClientboundLoginPacket.onlineMode`: the player list shows heads.
online_mode: bool,
@@ -162,8 +168,22 @@ pub(super) struct Remote {
clock_game_time: i64,
/// `ClientChunkCache.Storage`'s view centre (ClientboundSetChunkCacheCenterPacket).
chunk_center: (i32, i32),
/// Received events a frame left for the next one, in order, and when
/// the oldest of them first waited (`poll_remote`).
backlog: VecDeque<Event>,
backlog_since: Option<Instant>,
}
/// The time a frame spends on chunk packets before it leaves the rest of
/// the received events for the next frame. A batch of 25 to 60 columns
/// (0.1 ms each on an M4 Pro) all in one frame was a 3 to 8 ms frame every
/// time the player crossed a chunk border at 32 chunks.
const CHUNK_PACKETS_PER_FRAME: Duration = Duration::from_millis(1);
/// Events that have waited this long are all handled in the next frame,
/// whatever their cost: the packets after a slow machine's chunks never
/// wait more than a tick.
const BACKLOG_LIMIT: Duration = Duration::from_millis(50);
fn face_direction(face: [i32; 3]) -> u8 {
match face {
[0, -1, 0] => 0,
@@ -176,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::<Vec<_>>();
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};
@@ -288,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;
@@ -337,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(),
@@ -355,6 +405,8 @@ impl Game<'_> {
clock_partial: 0.0,
clock_game_time: 0,
chunk_center: (0, 0),
backlog: VecDeque::new(),
backlog_since: None,
});
// The level's TickRateManager follows the server's ticking packets.
self.clock = horizon_client::clock::FixedStep::client();
@@ -451,8 +503,15 @@ impl Game<'_> {
.unwrap_or("minecraft:air"),
)
}
/// The server's network id of a mob effect (`brewing::EFFECTS` id).
pub(super) fn remote_effect_network_id(&self, effect: &str) -> Option<i32> {
let r = self.remote.as_ref()?;
r.builtin
.get("minecraft:mob_effect")?
.id(&format!("minecraft:{effect}"))
}
/// A mob effect's network id as the effect (`brewing::EFFECTS` id).
fn remote_effect_id(&self, effect: i32) -> Option<&'static str> {
pub(super) fn remote_effect_id(&self, effect: i32) -> Option<&'static str> {
let r = self.remote.as_ref()?;
let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?;
horizon_client::brewing::effect(name).map(|d| d.id)
@@ -488,18 +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);
// 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<Tag> {
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<ItemStack>) -> Option<Stack> {
let s = s.as_ref()?;
let mut stack = Stack::new(self.item_id(&s.item), s.count as i32);
@@ -571,12 +730,34 @@ impl Game<'_> {
Some(r.chat.iter().rev().take(n).map(|l| l.0.clone()).collect())
}
/// Process everything the network thread received (once per frame, like
/// the client's packet processor).
/// Received events left for the next frame (`poll_remote`): until they
/// are handled, the terrain the server sent is not all there.
pub(super) fn remote_backlog(&self) -> usize {
self.remote.as_ref().map_or(0, |r| r.backlog.len())
}
/// Process what the network thread received (once per frame, like the
/// client's packet processor), in order. Chunk packets get
/// `CHUNK_PACKETS_PER_FRAME`: once a frame has spent it, the events from
/// the next chunk packet on wait for the next frame, unless they have
/// already waited `BACKLOG_LIMIT`.
pub(super) fn poll_remote(&mut self) -> Result<()> {
let Some(r) = &self.remote else { return Ok(()) };
let events = r.session.poll();
for event in events {
let Some(r) = self.remote.as_mut() else {
return Ok(());
};
let mut events = std::mem::take(&mut r.backlog);
events.extend(r.session.poll());
let overdue = r
.backlog_since
.is_some_and(|since| since.elapsed() >= BACKLOG_LIMIT);
let mut chunks = Duration::ZERO;
while let Some(event) = events.pop_front() {
let chunk =
matches!(&event, Event::Packet(p) if matches!(**p, C::LevelChunkWithLight(_)));
if chunk && !overdue && chunks >= CHUNK_PACKETS_PER_FRAME {
events.push_front(event);
break;
}
let started = chunk.then(Instant::now);
match event {
Event::Status(s) => {
if let Some(r) = self.remote.as_mut() {
@@ -622,10 +803,19 @@ impl Game<'_> {
}
Event::Packet(packet) => self.handle_packet(*packet)?,
}
chunks += started.map_or(Duration::ZERO, |t| t.elapsed());
if self.remote.is_none() {
break;
}
}
if let Some(r) = self.remote.as_mut() {
r.backlog_since = if events.is_empty() {
None
} else {
Some(r.backlog_since.unwrap_or_else(Instant::now))
};
r.backlog = events;
}
self.send_suggestion_request();
Ok(())
}
@@ -1243,9 +1433,39 @@ impl Game<'_> {
"minecraft:hopper" => slots(5),
"minecraft:generic_3x3" => slots(9),
"minecraft:brewing_stand" => slots(5),
_ => None,
// CrafterMenu: the grid, the inventory, then the result (the
// client's own).
"minecraft:crafter_3x3" => slots(9),
// A workstation: its inputs, its result, then the inventory.
m => {
let kind = Self::remote_station_kind(m)?;
let inputs = kind.inputs();
let own = inputs + usize::from(kind.has_result());
match s {
_ if s < inputs => Some(super::stations::INPUT + s),
_ if s < own => Some(super::stations::RESULT),
_ if s < own + 27 => Some(9 + s - own),
_ if s < own + 36 => Some(s - own - 27),
_ => None,
}
}
}
}
/// The workstation screen of a menu type a server opens.
pub(super) fn remote_station_kind(menu: &str) -> Option<super::stations::Kind> {
use super::stations::Kind;
Some(match menu {
"minecraft:loom" => Kind::Loom,
"minecraft:stonecutter" => Kind::Stonecutter,
"minecraft:grindstone" => Kind::Grindstone,
"minecraft:anvil" => Kind::Anvil,
"minecraft:smithing" => Kind::Smithing,
"minecraft:enchantment" => Kind::Enchanting,
"minecraft:beacon" => Kind::Beacon,
"minecraft:cartography_table" => Kind::Cartography,
_ => return None,
})
}
fn open_menu_name(&self, container: i32) -> String {
match self.remote.as_ref().and_then(|r| r.menu.as_ref()) {
Some((id, name)) if *id == container && container != 0 => name.clone(),
@@ -1254,6 +1474,12 @@ impl Game<'_> {
}
fn set_menu_slot(&mut self, container: i32, slot: i32, item: Option<ItemStack>) {
let menu = self.open_menu_name(container);
if menu == "minecraft:lectern" {
if slot == 0 {
self.remote_lectern_book(item);
}
return;
}
if container != 0 && menu == "inventory" {
return;
}
@@ -1264,6 +1490,9 @@ impl Game<'_> {
return; // the result slot is recomputed from the grid
}
*self.slot_mut(internal) = item;
if internal >= super::stations::INPUT && self.station.is_some() {
self.remote_station_slot_changed(internal);
}
}
fn handle_packet(&mut self, packet: C) -> Result<()> {
@@ -1532,6 +1761,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
{
@@ -1913,6 +2165,12 @@ impl Game<'_> {
}
self.remote_synced();
}
C::ContainerSetData(p) if self.open_menu_name(p.container) == "minecraft:lectern" => {
self.remote_lectern_page(i32::from(p.value));
}
C::ContainerSetData(p) if self.remote_station_open(p.container) => {
self.remote_station_data(usize::try_from(p.id).unwrap_or(usize::MAX), p.value);
}
C::ContainerSetData(p) => {
let v = i32::from(p.value);
match self
@@ -1926,6 +2184,12 @@ impl Game<'_> {
3 => f.cooking_total = v,
_ => {}
},
// CrafterBlockEntity.containerData.
Some(BlockEntity::Crafter(c)) => match usize::try_from(p.id) {
Ok(k @ 0..9) => c.disabled[k] = v == 1,
Ok(9) => c.triggered = v == 1,
_ => {}
},
// BrewingStandBlockEntity.dataAccess.
Some(BlockEntity::Brewing(b)) => match p.id {
0 => b.brew_time = v,
@@ -1943,6 +2207,7 @@ impl Game<'_> {
C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p),
C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p),
C::MerchantOffers(p) => self.remote_merchant_offers(p),
C::ContainerClose(_) if self.remote_lectern_closed() => {}
C::ContainerClose(_) => {
if self.screen == Screen::Inventory {
self.remote_close_local();
@@ -2160,6 +2425,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);
@@ -2305,33 +2571,20 @@ impl Game<'_> {
pub(super) fn remote_tab_players(
&mut self,
) -> Option<(Vec<horizon_client::tab_list::TabPlayer>, bool, Vec<u128>)> {
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
@@ -2344,9 +2597,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::<Vec<_>>(),
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<u8>) {
pub(super) fn store_skin(&mut self, location: String, rgba: Vec<u8>) {
use horizon_client::hud::SKIN_SLOTS;
let slot = if self.skin_slots.len() < SKIN_SLOTS {
self.skin_slots.len()
@@ -3155,10 +3467,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() {
@@ -3335,7 +3645,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;
@@ -3393,7 +3711,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 {
@@ -3408,26 +3730,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
@@ -3682,23 +4031,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 => {
@@ -3789,6 +4141,10 @@ impl Game<'_> {
/// engine doesn't model sends the clicks unpredicted. False when a click's
/// slot isn't one of the menu's.
pub(super) fn remote_menu_ops(&mut self, ops: &[(Option<usize>, i32, Input)]) -> bool {
// CrafterScreen.slotClicked: a slot toggle goes out before the click.
if let [(Some(slot), button, input)] = ops {
self.crafter_slot_clicked(*slot, *button, *input);
}
let (container, menu) = self.remote_menu();
let mut clicks = Vec::with_capacity(ops.len());
for &(slot, button, input) in ops {
@@ -3941,13 +4297,8 @@ impl Game<'_> {
r.menu = None;
r.menu_title = None;
}
if self
.station
.as_ref()
.is_some_and(|s| s.kind == super::stations::Kind::Merchant)
{
self.station = None;
}
// The client's menu has no level access: what it holds is the server's.
self.station = None;
self.craft_size = 2;
if let Some(key) = self.container.take() {
// Server containers stay renderable but lose their copied slots.
@@ -4021,6 +4372,27 @@ impl Game<'_> {
.as_ref()
.and_then(|r| r.use_target)
.map(|t| (t[0], t[1], t[2]));
if menu == "minecraft:lectern" {
// LecternScreen: the book and page come in the menu's content and data.
if let Some(r) = self.remote.as_mut() {
r.menu = Some((p.container, menu));
}
self.remote_open_lectern(target.unwrap_or_default());
return;
}
if let Some(kind) = Self::remote_station_kind(&menu) {
let title = plain(
&p.title,
&self
.remote
.as_ref()
.map(|r| r.lang.clone())
.unwrap_or_default(),
);
let pos = target.map_or([0, 0, 0], |t| [t.0, t.1, t.2]);
self.remote_open_station(p.container, menu, kind, title, pos);
return;
}
if menu == "minecraft:merchant" {
// A trading window: its offers follow in a MerchantOffers packet.
let title = plain(
@@ -4060,6 +4432,8 @@ impl Game<'_> {
horizon_client::brewing::BrewingStand::new(),
))),
"minecraft:generic_3x3" => Some(BlockEntity::Chest(vec![None; 9])),
// CrafterMenu: the disabled slots and triggered come in ContainerSetData.
"minecraft:crafter_3x3" => Some(BlockEntity::Crafter(Default::default())),
m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => {
let rows = m
.strip_prefix("minecraft:generic_9x")
@@ -4353,7 +4727,7 @@ pub(super) fn input_ordinal(input: Input) -> i32 {
/// The client's world for a guess at what a click does: reads go to the
/// world, writes stay here and are dropped.
struct DryLevel<'w> {
world: &'w horizon_client::world::World,
base: &'w dyn horizon_world::level::LevelAccess,
changed: HashMap<horizon_core::position::BlockPos, BlockStateId>,
random: horizon_core::random::LegacyRandom,
/// The sounds the use plays (a door's creak).
@@ -4383,6 +4757,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 {
@@ -4399,7 +4784,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,
@@ -4411,13 +4796,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()
}
}
@@ -4533,6 +4936,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<BlockStateId> {
panic!("preview must not write to the live level");
}
fn is_loaded(&self, _: BlockPos) -> bool {
self.loaded
}
fn max_y(&self) -> i32 {
self.ceiling
}
fn is_unobstructed(&self, pos: BlockPos, _: BlockStateId) -> bool {
assert_eq!(pos, BlockPos::new(0, 1, 0));
!self.obstructed
}
fn random(&mut self) -> &mut LegacyRandom {
panic!("preview must not advance the live level's random source");
}
fn game_time(&self) -> i64 {
0
}
}
// As with the LAN tests, prepared game resources are optional locally.
let resources = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
if !resources.join("block-behaviours.json").exists() {
return;
}
let registry = load_registry(&resources).unwrap();
let behaviours = Behaviours::load(&registry, &resources).unwrap();
let mut base = Level {
air: registry.default_state("minecraft:air").unwrap(),
stone: registry.default_state("minecraft:stone").unwrap(),
obstructed: false,
loaded: true,
ceiling: 320,
};
for item in [
"minecraft:stone",
"minecraft:oak_slab",
"minecraft:oak_door",
// GrowingPlantHeadBlock.getStateForPlacement draws a random age.
"minecraft:twisting_vines",
] {
let ctx = PlaceContext {
clicked_pos: BlockPos::new(0, 0, 0),
face: horizon_core::geometry::Direction::Up,
hit: horizon_core::geometry::Vec3::new(0.5, 1.0, 0.5),
inside: false,
yaw: 0.0,
pitch: 45.0,
sneaking: false,
item: item.into(),
can_use_game_master_blocks: false,
};
for (obstructed, loaded, ceiling) in [
(false, true, 320),
(true, true, 320),
(false, false, 320),
(false, true, 1),
] {
base.obstructed = obstructed;
base.loaded = loaded;
base.ceiling = ceiling;
let valid = !obstructed && loaded && ceiling > 1;
let mut preview = DryLevel::new(&base);
let outcome = behaviours.place_block(&mut preview, &mut Ticks::default(), &ctx);
assert_eq!(
matches!(outcome, PlaceOutcome::Placed { .. }),
valid,
"{item}, obstructed={obstructed}, loaded={loaded}, ceiling={ceiling}"
);
assert_eq!(preview.changed.is_empty(), !valid);
assert_eq!(base.block_state(BlockPos::new(0, 1, 0)), base.air);
}
}
}
#[test]
fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() {
// InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand.
@@ -123,6 +123,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)) => {
@@ -0,0 +1,156 @@
//! A server's workstation menus on this client: the server opens the menu
//! (`ClientboundOpenScreenPacket` with the station's `MenuType`), the
//! station screen draws it, and its clicks and buttons are predicted on the
//! menu engine (`Game::menu_session`) and sent, as
//! `MultiPlayerGameMode.handleContainerInput` and `handleInventoryButtonClick`
//! do. The menu's client-side `slotsChanged` follows the server's slots, and
//! its data slots come in `ClientboundContainerSetDataPacket`.
use super::{
Game, Screen,
stations::{Kind, Station},
};
use horizon_protocol::packets::play::{self, Serverbound as S};
impl Game<'_> {
/// The server opened workstation menu `menu` in window `container`.
pub(super) fn remote_open_station(
&mut self,
container: i32,
menu: String,
kind: Kind,
title: String,
pos: [i32; 3],
) {
if let Some(r) = self.remote.as_mut() {
r.menu = Some((container, menu));
r.menu_title = Some(title);
}
self.craft_size = 2;
self.container = None;
self.station = Some(Station::new_kind(kind, pos));
self.screen = Screen::Inventory;
self.capture(false);
}
/// Window `container` is the server's workstation menu, open here.
pub(super) fn remote_station_open(&self, container: i32) -> bool {
self.station.is_some()
&& self
.remote
.as_ref()
.and_then(|r| r.menu.as_ref())
.is_some_and(|(id, name)| {
*id == container && Self::remote_station_kind(name).is_some()
})
}
/// The server set station slot `internal`: the client menu's
/// `Slot.set` runs its container's `setChanged`, so the loom lists the
/// patterns its inputs allow and the stonecutter the recipes of its input.
pub(super) fn remote_station_slot_changed(&mut self, internal: usize) {
if !self.station.as_ref().is_some_and(|s| {
matches!(
s.kind,
Kind::Loom
| Kind::Stonecutter
| Kind::Grindstone
| Kind::Anvil
| Kind::Smithing
| Kind::Cartography
)
}) {
return;
}
self.menu_session(|menu, env, to_menu| {
let i = to_menu(internal)?;
let stack = menu.slot(i).cloned();
menu.set_slot(env, i, stack);
Some(true)
});
// AnvilScreen.slotChanged: the box shows the new input's name, which
// its responder sends.
self.remote_anvil_rename();
}
/// `AbstractContainerMenu.setData` from the server.
pub(super) fn remote_station_data(&mut self, id: usize, value: i16) {
let Some(s) = self.station.as_mut() else {
return;
};
match (s.kind, id) {
// LoomMenu.selectedBannerPatternIndex.
(Kind::Loom, 0) => s.loom.selected = usize::try_from(value).ok(),
// StonecutterMenu.selectedRecipeIndex.
(Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(),
// AnvilMenu.cost.
(Kind::Anvil, 0) => s.anvil.cost = i32::from(value),
// EnchantmentMenu: costs, the seed (the screen's glyph names),
// the clues' enchantments and levels.
(Kind::Enchanting, 0..3) => s.offers.costs[id] = i32::from(value),
(Kind::Enchanting, 3) => self.level.xp_seed = i32::from(value),
(Kind::Enchanting, 4..7) => {
let name = self.remote.as_ref().and_then(|r| {
r.registries
.name("minecraft:enchantment", i32::from(value))
.map(std::sync::Arc::<str>::from)
});
let level = s.offers.clues[id - 4].as_ref().map_or(1, |(_, l)| *l);
s.offers.clues[id - 4] = name.map(|n| (n, level));
}
(Kind::Enchanting, 7..10) => {
if let Some((_, level)) = s.offers.clues[id - 7].as_mut() {
*level = value.max(0) as u32;
}
}
// BeaconMenu: the levels, then the powers (BeaconScreen's
// dataChanged shows the menu's).
(Kind::Beacon, 0) => s.beacon_levels = Some(i32::from(value)),
(Kind::Beacon, 1 | 2) => {
let effect = self.remote_effect_id(i32::from(value) - 1);
let index =
effect.and_then(|e| super::beacon::EFFECTS.iter().position(|(n, _)| *n == e));
if let Some(s) = self.station.as_mut() {
s.beacon[id - 1] = index;
}
}
_ => {}
}
}
/// `AnvilScreen.onNameChanged` on a server: the rename box's text (blank
/// when it is the input's own name) goes to the server when the menu's
/// `setItemName` takes it.
pub(super) fn remote_anvil_rename(&mut self) {
if self.remote.is_none() {
return;
}
let Some(s) = self
.station
.as_ref()
.filter(|s| s.kind == Kind::Anvil && s.inputs[0].is_some())
else {
return;
};
let name = self.anvil_item_name(s);
if s.anvil_sent.as_deref() == Some(&name) {
return;
}
if let Some(s) = self.station.as_mut() {
s.anvil_sent = Some(name.clone());
}
self.send(S::RenameItem(play::RenameItem { name }));
}
/// `MultiPlayerGameMode.handleInventoryButtonClick`: the screen already
/// ran `clickMenuButton` on its own menu.
pub(super) fn remote_station_button(&self, button: i32) {
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref())
&& self.remote_station_open(*container)
{
self.send(S::ContainerButtonClick(play::ContainerButtonClick {
container: *container,
button,
}));
}
}
}
+8 -5
View File
@@ -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() {
+46 -1
View File
@@ -7,6 +7,24 @@ 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 => 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)> {
@@ -334,7 +352,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() {
+6 -1
View File
@@ -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<u64>,
// Keyed by mob ids the server gives out: the fast hasher is safe.
steps: FxHashMap<Who, Steps>,
damaged: FxHashMap<u32, i64>,
@@ -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 {
@@ -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<u32, String> = HashMap::new();
let mut sources: Vec<u32> = Vec::new();
@@ -10,6 +10,7 @@ pub(super) const HELP: &[&str] = &[
"use X Y Z open the block's menu as if right-clicked",
"click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)",
"click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner",
"book [next|back|take|done] the open book or lectern: its page, or press one of its buttons",
"type TEXT | type-back type into the anvil name box / delete one character",
"enchant ID LEVEL enchant the held item (books store the enchantment)",
"potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)",
@@ -136,6 +137,7 @@ impl Game<'_> {
self.apply_equipment();
ok()
}
"book" => Ok(Some(self.book_control(words.get(1).copied())?)),
"potion" => {
let stack = ItemStack::new(&id(arg(1)?), 1).with_potion(&id(arg(2)?));
let rest = self.give(stack);
+173 -401
View File
@@ -13,7 +13,6 @@ use horizon_client::{
stations::{self, AnvilResult, EnchantOffers},
};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::sync::Arc;
/// Slot ids of the open station: inputs from 600, the result at 650.
pub(super) const INPUT: usize = 600;
@@ -36,7 +35,7 @@ pub(super) enum Kind {
Loom,
}
impl Kind {
fn from_block(name: &str) -> Option<Self> {
pub(super) fn from_block(name: &str) -> Option<Self> {
Some(match name {
"minecraft:enchanting_table" => Self::Enchanting,
"minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => {
@@ -51,7 +50,7 @@ impl Kind {
_ => return None,
})
}
fn inputs(self) -> usize {
pub(super) fn inputs(self) -> usize {
match self {
Self::Smithing | Self::Loom => 3,
Self::Stonecutter | Self::Beacon => 1,
@@ -71,7 +70,7 @@ impl Kind {
Self::Loom => "gui/container/loom",
}
}
fn title_key(self) -> &'static str {
pub(super) fn title_key(self) -> &'static str {
match self {
Self::Enchanting => "container.enchant",
Self::Anvil => "container.repair",
@@ -108,6 +107,10 @@ impl Kind {
};
table[i.min(table.len() - 1)]
}
/// Whether the menu has a result slot after its inputs.
pub(super) fn has_result(self) -> bool {
self.result_pos().is_some()
}
fn result_pos(self) -> Option<(f32, f32)> {
match self {
Self::Enchanting => None,
@@ -128,18 +131,20 @@ pub(super) struct Station {
pub(super) pos: [i32; 3],
pub(super) inputs: Vec<Option<ItemStack>>,
pub(super) result: Option<ItemStack>,
offers: EnchantOffers,
pub(super) offers: EnchantOffers,
bookcases: i32,
anvil: AnvilResult,
pub(super) anvil: AnvilResult,
/// Anvil rename box text.
pub(super) name: String,
/// Stonecutter: recipe indices for the input, selection and first shown index.
recipes: Vec<usize>,
selected: Option<usize>,
/// Stonecutter: the menu's recipe list (horizon_client::menu), its
/// `selectedRecipeIndex` and the screen's first shown index.
pub(super) stone: horizon_client::menu::Stonecutter,
pub(super) selected: Option<usize>,
start: usize,
input_item: Option<Arc<str>>,
/// Anvil: the input the rename box was last filled from.
anvil_last: Option<ItemStack>,
/// Anvil on a server: the name last sent (the client menu's `itemName`).
pub(super) anvil_sent: Option<String>,
/// When the screen opened: the rename box has the focus from then.
opened: std::time::Instant,
pub(super) last_sound: u64,
@@ -147,6 +152,8 @@ pub(super) struct Station {
pub(super) merchant: Option<Box<super::trading::MerchantState>>,
/// Beacon menu: the selected primary and secondary power (EFFECTS index).
pub(super) beacon: [Option<usize>; 2],
/// A server's beacon menu: the pyramid's levels (its data slot 0).
pub(super) beacon_levels: Option<i32>,
/// The loom's patterns, selection and scroller (game/loom.rs).
pub(super) loom: super::loom::LoomState,
}
@@ -161,21 +168,29 @@ impl Station {
bookcases: 0,
anvil: AnvilResult::default(),
name: String::new(),
recipes: Vec::new(),
stone: Default::default(),
selected: None,
start: 0,
input_item: None,
anvil_last: None,
anvil_sent: None,
opened: std::time::Instant::now(),
last_sound: 0,
merchant: None,
beacon: [None; 2],
beacon_levels: None,
loom: Default::default(),
}
}
pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self {
Self::new(kind, pos)
}
/// `StonecutterScreen.containerChanged`: without recipes to show, the
/// list scrolls back to the top.
pub(super) fn stonecutter_changed(&mut self) {
if self.inputs[0].is_none() || self.stone.recipes.is_empty() {
self.start = 0;
}
}
}
/// The 108x19 enchantment button `i` (relative to the GUI origin).
@@ -323,6 +338,10 @@ impl Game<'_> {
let Some(mut station) = self.station.take() else {
return;
};
if self.remote.is_some() && station.kind != Kind::Merchant {
// A server's workstation: its removed() gives the inputs back.
return;
}
if let Some(m) = station.merchant.as_mut() {
self.merchant_closed(m);
}
@@ -375,7 +394,7 @@ impl Game<'_> {
_ => &mut self.scratch_slot,
}
}
fn count_bookshelves(&self, pos: [i32; 3]) -> i32 {
pub(super) fn count_bookshelves(&self, pos: [i32; 3]) -> i32 {
let tags = &self.res.items().block_tags;
let is = |p: [i32; 3], tag: &str| {
let name = &self
@@ -399,7 +418,7 @@ impl Game<'_> {
.count() as i32
}
/// The anvil name the menu works with (`AnvilScreen.onNameChanged`).
fn anvil_item_name(&self, s: &Station) -> String {
pub(super) fn anvil_item_name(&self, s: &Station) -> String {
match &s.inputs[0] {
Some(input)
if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) =>
@@ -419,6 +438,16 @@ impl Game<'_> {
let data = self.res.stations();
let items = self.res.items();
match s.kind {
// A server's table: its data slots carry the offers, and its
// client menu only clears them without an enchantable item.
Kind::Enchanting if self.remote.is_some() => {
let enchantable = s.inputs[0].as_ref().is_some_and(|i| {
data.enchantments.enchantable(&i.item) > 0 && i.enchantments().is_empty()
});
if !enchantable {
s.offers = Default::default();
}
}
Kind::Enchanting => {
s.bookcases = self.count_bookshelves(s.pos);
s.offers = stations::enchant_offers(
@@ -465,35 +494,9 @@ impl Game<'_> {
// The menu engine keeps the merchant's result (Game::menu_session).
Kind::Merchant => {}
Kind::Beacon => {}
Kind::Cartography => s.result = self.cartography_result(&s),
// The menu engine keeps the loom's state (Game::menu_session).
Kind::Loom => {}
Kind::Stonecutter => {
let item = s.inputs[0].as_ref().map(|i| i.item.clone());
if item != s.input_item {
s.input_item = item;
s.selected = None;
s.start = 0;
s.recipes = match &s.inputs[0] {
Some(input) => data
.recipes
.stonecutting
.iter()
.enumerate()
.filter(|(_, r)| r.input.test(input))
.map(|(i, _)| i)
.collect(),
None => Vec::new(),
};
}
s.result = match (s.selected, &s.inputs[0]) {
(Some(i), Some(_)) => s
.recipes
.get(i)
.map(|&r| data.recipes.stonecutting[r].result.clone()),
_ => None,
};
}
// The menu engine keeps the cartography table's, the loom's and
// the stonecutter's state (Game::menu_session).
Kind::Cartography | Kind::Loom | Kind::Stonecutter => {}
}
self.station = Some(s);
}
@@ -505,7 +508,6 @@ impl Game<'_> {
}
/// `Slot.mayPlace` and `getMaxStackSize` for station slots.
fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) {
let data = self.data();
if slot >= super::mount_menu::SADDLE {
return self.mount_slot_rules(slot, stack);
}
@@ -528,24 +530,7 @@ impl Game<'_> {
if slot == RESULT {
return (false, 64);
}
let i = slot - INPUT;
match s.kind {
Kind::Enchanting if i == 0 => (true, 1),
Kind::Beacon => (super::beacon::is_payment(&stack.item), 1),
Kind::Loom => (false, 64),
Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64),
Kind::Cartography => (
matches!(
&*stack.item,
"minecraft:paper" | "minecraft:map" | "minecraft:glass_pane"
),
64,
),
Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64),
Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64),
Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64),
_ => (true, 64),
}
(s.kind != Kind::Loom, 64)
}
/// `AbstractContainerMenu.doClick` PICKUP on a filtered slot.
pub(super) fn click_filtered(&mut self, slot: usize, right: bool) {
@@ -644,112 +629,80 @@ impl Game<'_> {
}
stack.count != start
}
/// The player inventory in menu order: main rows, then the hotbar.
fn player_slots() -> Vec<usize> {
(9..36).chain(0..9).collect()
/// After an anvil or smithing click on the menu engine: the anvil's cost
/// and state back into the station and the rename box following the
/// input (`AnvilScreen.slotChanged`), then the rest of a taken result's
/// `onTake` (the levels, the anvil's wear, the use sound) unless a
/// server does it.
pub(super) fn combiner_session_end(
&mut self,
menu: &horizon_client::menu::Menu,
predicting: bool,
) {
let Some(s) = self.station.as_mut() else {
return;
};
let (pos, kind) = (s.pos, s.kind);
if kind == Kind::Anvil {
s.anvil.cost = menu.data[0];
s.anvil.repair_item_count_cost = menu.anvil.repair_count;
s.anvil.only_renaming = menu.anvil.only_renaming;
s.anvil.result = s.result.clone();
}
self.station_after_input();
if !menu.combined || predicting {
return;
}
if kind == Kind::Smithing {
self.level_event_at(1044, pos, 0);
return;
}
self.give_levels(menu.level_change);
if self.anvil_used(pos, self.creative) {
self.close_station();
self.screen = Screen::Playing;
self.capture(true);
}
}
/// A shift-click: `AbstractContainerMenu.doClick`'s QUICK_MOVE repeats
/// `quickMoveStack` while it moves something and the slot still holds the
/// same item.
fn quick_move(&mut self, slot: usize) {
while let Some(item) = self.slot_mut(slot).as_ref().map(|s| s.item.clone())
&& self.quick_move_once(slot)
&& self.slot_mut(slot).as_ref().is_some_and(|s| s.item == item)
{}
}
/// The station menu's `quickMoveStack` for one slot (`EnchantmentMenu`,
/// `BeaconMenu`, `GrindstoneMenu`, `StonecutterMenu`,
/// `CartographyTableMenu`, and `ItemCombinerMenu` with `SmithingMenu`'s
/// `canMoveIntoInputSlots`); whether the stack's count changed. Each
/// rule that names its target slots moves nowhere else when they are full.
fn quick_move_once(&mut self, slot: usize) -> bool {
let Some(kind) = self.station.as_ref().map(|s| s.kind) else {
return false;
};
let Some(mut stack) = self.slot_mut(slot).take() else {
return false;
};
let start = stack.count;
let empty = |game: &mut Self, i: usize| game.station_slot_mut(INPUT + i).is_none();
// The other half of the inventory: main rows to the hotbar and back.
let halves: Vec<usize> = if slot < 9 {
(9..36).collect()
} else {
(0..9).collect()
};
if slot >= INPUT {
// An input slot: into the inventory, the hotbar's last slot first
// where vanilla moves in reverse.
let reverse = matches!(kind, Kind::Enchanting | Kind::Beacon);
self.move_to(&mut stack, &Self::player_slots(), reverse);
} else {
match kind {
Kind::Enchanting => {
if &*stack.item == "minecraft:lapis_lazuli" {
self.move_to(&mut stack, &[INPUT + 1], true);
} else if empty(self, 0) {
*self.station_slot_mut(INPUT) = Some(ItemStack {
count: 1,
..stack.clone()
});
stack.count -= 1;
}
/// `AnvilMenu.onTake`'s level part: out of creative a 12% chance
/// (`AnvilBlock.damage`) to wear the anvil a stage, or break a damaged one
/// (level event 1029); otherwise level event 1030. True when it broke.
pub(super) fn anvil_used(&mut self, pos: [i32; 3], creative: bool) -> bool {
let state = self.world.block(pos[0], pos[1], pos[2]);
let name = self.res.facts().get(state).name.clone();
let anvil = matches!(
&*name,
"minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil"
);
if !creative && anvil && self.world.random.next_float() < 0.12 {
match &*name {
"minecraft:anvil" => {
let _ = self.set_state_named(pos, "minecraft:chipped_anvil", &["facing"]);
}
Kind::Beacon => {
if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1
{
self.move_to(&mut stack, &[INPUT], false);
} else {
self.move_to(&mut stack, &halves, false);
}
"minecraft:chipped_anvil" => {
let _ = self.set_state_named(pos, "minecraft:damaged_anvil", &["facing"]);
}
Kind::Grindstone => {
if empty(self, 0) || empty(self, 1) {
self.move_to(&mut stack, &[INPUT, INPUT + 1], false);
} else {
self.move_to(&mut stack, &halves, false);
}
_ => {
let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air);
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
self.level_event_at(1029, pos, 0);
return true;
}
Kind::Stonecutter => {
if self.data().recipes.stonecutter(&stack).is_empty() {
self.move_to(&mut stack, &halves, false);
} else {
self.move_to(&mut stack, &[INPUT], false);
}
}
Kind::Cartography => {
if super::maps::map_id(&stack).is_some() {
self.move_to(&mut stack, &[INPUT], false);
} else if matches!(
&*stack.item,
"minecraft:paper" | "minecraft:map" | "minecraft:glass_pane"
) {
self.move_to(&mut stack, &[INPUT + 1], false);
} else {
self.move_to(&mut stack, &halves, false);
}
}
Kind::Anvil | Kind::Smithing => {
let inputs: Vec<usize> = (0..kind.inputs()).map(|i| INPUT + i).collect();
// ItemCombinerMenu.canMoveIntoInputSlots: always for the
// anvil; the smithing table needs an empty slot whose
// ingredient test takes the stack.
let into_inputs = kind == Kind::Anvil
|| (0..3).any(|i| {
empty(self, i) && self.data().recipes.smithing_accepts(i, &stack)
});
let targets = if into_inputs { &inputs } else { &halves };
self.move_to(&mut stack, targets, false);
}
// Their clicks run on the menu engine.
Kind::Merchant | Kind::Loom => {}
}
}
let moved = stack.count != start;
if stack.count > 0 {
*self.slot_mut(slot) = Some(stack);
self.level_event_at(1030, pos, 0);
false
}
/// The grindstone result's `onTake` with a level (`amount`: the menu's
/// `getExperienceAmount` sum): the orbs at the block's centre
/// (`ExperienceOrb.award`), then level event 1042, the grindstone's sound
/// for everyone around.
pub(super) fn grindstone_taken(&mut self, pos: [i32; 3], amount: i32) {
let xp = stations::grindstone_xp_roll(amount, &mut self.world.random);
if xp > 0 {
self.spawn_orbs(pos.map(|v| f64::from(v) + 0.5), xp);
}
moved
self.level_event_at(1042, pos, 0);
}
fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) {
let at = [
@@ -788,185 +741,6 @@ impl Game<'_> {
_ => true,
}
}
/// The result slot's `onTake`.
fn take_result(&mut self) {
let Some(mut s) = self.station.take() else {
return;
};
let pos = s.pos;
match s.kind {
Kind::Anvil => {
let cost = s.anvil.cost;
let repair = s.anvil.repair_item_count_cost;
if repair > 0 {
if let Some(a) = s.inputs[1].as_mut()
&& a.count > repair
{
a.count -= repair;
} else {
s.inputs[1] = None;
}
} else if !s.anvil.only_renaming {
s.inputs[1] = None;
}
s.inputs[0] = None;
s.name.clear();
if !self.creative {
self.give_levels(-cost);
}
let pitch = self.world.random.next_float() * 0.1 + 0.9;
if !self.creative && self.world.random.next_float() < 0.12 {
// AnvilBlock.damage
let state = self.world.block(pos[0], pos[1], pos[2]);
let name = self.res.facts().get(state).name.clone();
let next = match &*name {
"minecraft:anvil" => Some("minecraft:chipped_anvil"),
"minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"),
_ => None,
};
match next {
Some(next) => {
let _ = self.set_state_named(pos, next, &["facing"]);
self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch);
}
None => {
let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air);
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
self.play_at("minecraft:block.anvil.destroy", pos, 1.0, pitch);
self.station = Some(s);
self.close_station();
self.screen = Screen::Playing;
self.capture(true);
return;
}
}
} else {
self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch);
}
}
Kind::Grindstone => {
let (a, b) = (s.inputs[0].take(), s.inputs[1].take());
let mut random = LegacyRandom::new(self.world.random.next_long());
let xp = stations::grindstone_experience(
&self.res.stations().enchantments,
&mut random,
a.as_ref(),
b.as_ref(),
);
if xp > 0 {
self.spawn_orbs(
[
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
],
xp,
);
}
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch);
}
Kind::Smithing => {
for slot in s.inputs.iter_mut() {
if let Some(x) = slot.as_mut() {
x.count -= 1;
if x.count == 0 {
*slot = None;
}
}
}
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch);
}
Kind::Stonecutter => {
if let Some(x) = s.inputs[0].as_mut() {
x.count -= 1;
if x.count == 0 {
s.inputs[0] = None;
}
}
if s.last_sound != self.ticks {
s.last_sound = self.ticks;
self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0);
}
}
Kind::Merchant => {}
Kind::Beacon => {}
Kind::Cartography => {
for slot in &mut s.inputs {
if let Some(x) = slot.as_mut() {
x.count -= 1;
if x.count == 0 {
*slot = None;
}
}
}
if s.last_sound != self.ticks {
s.last_sound = self.ticks;
self.cartography_taken(pos);
}
}
Kind::Loom => {}
Kind::Enchanting => {}
}
self.station = Some(s);
self.station_changed();
}
fn click_result(&mut self, shift: bool) {
loop {
let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else {
return;
};
if !self.may_take_result() {
return;
}
let result = if self
.station
.as_ref()
.is_some_and(|s| s.kind == Kind::Cartography)
{
self.cartography_post(result)
} else {
result
};
if shift {
let mut stack = result.clone();
let player = Self::player_slots();
// Simulate first so nothing is lost when the inventory is full.
let saved: Vec<Option<ItemStack>> = self.inventory.clone();
self.move_to(&mut stack, &player, true);
if stack.count > 0 {
self.inventory = saved;
return;
}
} else {
match &mut self.carried {
None => self.carried = Some(result.clone()),
Some(c)
if c.same_item_same_components(&result)
&& c.count + result.count
<= self.res.items().get(&c.item).map_or(64, |i| i.max_stack) =>
{
c.count += result.count
}
_ => return,
}
}
if let Some(s) = self.station.as_mut() {
s.result = None;
}
self.take_result();
let again = shift
&& self
.station
.as_ref()
.and_then(|s| s.result.as_ref())
.is_some_and(|r| r.item == result.item);
if !again {
return;
}
}
}
/// `EnchantmentMenu.clickMenuButton`.
fn click_enchant(&mut self, button: usize) {
let Some(s) = self.station.as_ref() else {
@@ -987,6 +761,11 @@ impl Game<'_> {
{
return;
}
if self.remote.is_some() {
// EnchantmentScreen.mouseClicked: the client menu took it, the server enchants.
self.remote_station_button(button as i32);
return;
}
let Some(enchanted) = stations::apply_enchantment(
&self.res.stations().enchantments,
self.res.items(),
@@ -1036,7 +815,7 @@ impl Game<'_> {
})
.collect(),
Kind::Stonecutter if s.inputs[0].is_some() => (s.start
..(s.start + 12).min(s.recipes.len()))
..(s.start + 12).min(s.stone.recipes.len()))
.map(|index| {
let p = index - s.start;
[
@@ -1089,64 +868,21 @@ impl Game<'_> {
}
}
}
if kind == Kind::Stonecutter
&& let Some(s) = self.station.as_ref()
&& s.inputs[0].is_some()
{
for index in s.start..(s.start + 12).min(s.recipes.len()) {
let p = index - s.start;
let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0);
if inside(local, x, y, 16.0, 18.0) {
if s.selected != Some(index) {
if let Some(st) = self.station.as_mut() {
st.selected = Some(index);
}
self.audio.play(
"minecraft:ui.stonecutter.select_recipe",
None,
1.0,
1.0,
);
self.station_changed();
}
return true;
}
}
if kind == Kind::Stonecutter && self.stonecutter_click(local) {
return true;
}
}
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
return true;
};
if self
.station
.as_ref()
.is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant))
{
// LoomMenu, MerchantMenu and the brewing stand's BrewingStandMenu
// clicks run on the verified menu engine.
let input = if shift {
horizon_client::menu::Input::QuickMove
} else {
horizon_client::menu::Input::Pickup
};
self.menu_click(Some(slot), i32::from(right), input);
return true;
}
if slot == RESULT {
self.click_result(shift);
return true;
}
if shift {
self.quick_move(slot);
} else if slot >= INPUT {
self.click_filtered(slot, right);
// Every station's clicks (and the brewing stand's) run on the
// verified menu engine.
let input = if shift {
horizon_client::menu::Input::QuickMove
} else {
return false;
}
if let Some(key) = self.container {
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
}
self.station_after_input();
horizon_client::menu::Input::Pickup
};
self.menu_click(Some(slot), i32::from(right), input);
true
}
/// Recompute after slot changes; the anvil box follows its input item.
@@ -1164,16 +900,49 @@ impl Game<'_> {
}
self.station_changed();
}
/// `StonecutterScreen.mouseClicked` on its recipe grid: `clickMenuButton`
/// with the cell's index (an empty cell's too), and the select sound when
/// the menu took it.
fn stonecutter_click(&mut self, local: (f32, f32)) -> bool {
let Some(start) = self
.station
.as_ref()
.filter(|s| s.inputs[0].is_some() && !s.stone.recipes.is_empty())
.map(|s| s.start)
else {
return false;
};
for index in start..start + 12 {
let p = index - start;
let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0);
if !inside(local, x, y, 16.0, 18.0) {
continue;
}
let mut taken = false;
let flag = &mut taken;
self.menu_session(|menu, env, _| {
*flag = menu.button(env, index as i32);
Some(*flag)
});
if taken {
self.audio
.play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0);
self.remote_station_button(index as i32);
return true;
}
}
false
}
pub(super) fn station_scroll(&mut self, d: f32) {
self.merchant_scroll(d);
self.loom_scroll(d);
let Some(s) = self.station.as_mut() else {
return;
};
if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 {
if s.kind != Kind::Stonecutter || s.stone.recipes.len() <= 12 {
return;
}
let rows = s.recipes.len().div_ceil(4) - 3;
let rows = s.stone.recipes.len().div_ceil(4) - 3;
let first_row = (s.start / 4) as i32 - d.signum() as i32;
s.start = first_row.clamp(0, rows as i32) as usize * 4;
}
@@ -1207,6 +976,7 @@ impl Game<'_> {
}
}
self.station_changed();
self.remote_anvil_rename();
}
/// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the
/// recipe book's search box.
@@ -1227,6 +997,7 @@ impl Game<'_> {
ANVIL_NAME_CHARS,
) {
self.station_changed();
self.remote_anvil_rename();
}
}
@@ -1740,9 +1511,9 @@ impl Game<'_> {
}
Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {}
Kind::Stonecutter => {
let display = s.inputs[0].is_some() && !s.recipes.is_empty();
let active = display && s.recipes.len() > 12;
let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1);
let display = s.inputs[0].is_some() && !s.stone.recipes.is_empty();
let active = display && s.stone.recipes.len() > 12;
let rows = s.stone.recipes.len().div_ceil(4).saturating_sub(3).max(1);
let offs = if active {
(s.start / 4) as f32 / rows as f32
} else {
@@ -1763,13 +1534,14 @@ impl Game<'_> {
let (start, selected) = (s.start, s.selected);
// graphics.item: the icon only, without the count.
let shown: Vec<(usize, ItemStack)> = (start
..(start + 12).min(s.recipes.len()))
..(start + 12).min(s.stone.recipes.len()))
.map(|i| {
(
i,
ItemStack {
count: 1,
..self.res.stations().recipes.stonecutting[s.recipes[i]]
..self.res.stations().recipes.stonecutting
[s.stone.recipes[i]]
.result
.clone()
},
@@ -2082,7 +1854,7 @@ impl Game<'_> {
"bookcases": s.bookcases,
"anvil_cost": s.anvil.cost,
"result": s.result.as_ref().map(|r| format!("{} x{}", r.item, r.count)),
"recipes": s.recipes.iter().map(|&i| recipes[i].id.clone()).collect::<Vec<_>>(),
"recipes": s.stone.recipes.iter().map(|&i| recipes[i].id.clone()).collect::<Vec<_>>(),
"selected": s.selected,
})
}
+35
View File
@@ -122,6 +122,38 @@ impl Game<'_> {
let sky = self.world.light(x, y + 1, z) >> 4 == 15;
water || (self.world.weather.raining && sky)
}
/// The living entities a spinning player can touch this tick, for
/// `LivingEntity.checkAutoSpinAttack` (none when not spinning).
pub(super) fn spin_targets(&self) -> Vec<(u32, Aabb)> {
let Some(p) = self
.player
.as_ref()
.filter(|p| p.auto_spin_attack_ticks > 0)
else {
return Vec::new();
};
// A spin moves a few blocks a tick at most.
let near = p.bounds().inflate(Vec3::new(16.0, 16.0, 16.0));
self.mobs
.iter()
.filter(|m| m.alive() && m.bounds().intersects(near))
.map(|m| (m.id, m.bounds()))
.collect()
}
/// `Player.doAutoAttackOnTouch`: the touched entity takes `Player.attack`
/// with the spin's damage; once the spin is over its damage is cleared.
pub(super) fn end_spin_attack(&mut self, hit: Option<u32>) {
if let Some(id) = hit
&& let Some(index) = self.mobs.iter().position(|m| m.id == id)
{
self.attack_mob(index);
}
if let Some(p) = self.player.as_mut()
&& p.auto_spin_attack_ticks <= 0
{
p.auto_spin_attack_dmg = 0.0;
}
}
/// `TridentItem.releaseUsing`.
pub(super) fn release_trident(&mut self, ticks: u32) {
if ticks < 10 {
@@ -152,6 +184,9 @@ impl Game<'_> {
p.velocity.y + d[1] * f64::from(strength),
p.velocity.z + d[2] * f64::from(strength),
);
// Player.startAutoSpinAttack(20, 8, stack).
p.auto_spin_attack_ticks = 20;
p.auto_spin_attack_dmg = 8.0;
if p.ground.on_ground {
p.position.y += 1.2;
}
@@ -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();
+110 -14
View File
@@ -61,8 +61,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 +165,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],
@@ -193,12 +197,14 @@ pub struct Frame<'a> {
pub dynamic_lights: &'a [[f32; 4]],
/// Cloud mesh inputs; geometry and GPU storage are retained by the renderer.
pub clouds: Option<crate::clouds::Input<'a>>,
/// 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
@@ -334,9 +340,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.
@@ -1664,8 +1673,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 +1727,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"),
@@ -2110,9 +2138,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,
@@ -3279,6 +3310,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 +3348,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 +3359,13 @@ 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
});
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 +3556,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() {
@@ -3622,6 +3673,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 +3898,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
@@ -3875,12 +3942,13 @@ impl Renderer {
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);
@@ -4167,6 +4235,34 @@ mod tests {
);
assert_eq!(surface_format(&[Rgba16Float], Bgra8UnormSrgb), Rgba16Float);
}
/// A Wayland surface on a compositor with colour management, as wgpu lists it (Mesa 26.2
/// ANV on an Intel HD 620 under weston 16): wide formats first. The pre-#1075 choice,
/// the first non-sRGB format, took `Rgba16Float` and the window looked washed out, as if
/// under a white overlay (#1007); XWayland lists no such format, which is why it looked fine.
#[test]
fn a_colour_managed_wayland_surface_still_gets_8_bit() {
use super::surface_format;
use wgpu::TextureFormat::*;
let wayland = [
Rgba16Float,
Rgba16Unorm,
Rgb10a2Unorm,
Bgra8UnormSrgb,
Bgra8Unorm,
Rgba8UnormSrgb,
Rgba8Unorm,
];
assert_eq!(surface_format(&wayland, Bgra8UnormSrgb), Bgra8Unorm);
// Without Bgra8: Rgba8, still not a 16- or 10-bit format.
let without_bgra = [
Rgba16Float,
Rgba16Unorm,
Rgb10a2Unorm,
Rgba8UnormSrgb,
Rgba8Unorm,
];
assert_eq!(surface_format(&without_bgra, Rgba8UnormSrgb), Rgba8Unorm);
}
#[test]
fn special_material_batches_preserve_quad_order_and_offsets() {
let quad = |layer, id| {
+84
View File
@@ -0,0 +1,84 @@
//! The End sky's six tiled faces, retained for the lifetime of the renderer's atlas.
use crate::mesher::Vertex;
use wgpu::util::DeviceExt;
const VERTICES: u32 = 6 * 16 * 16 * 4;
#[derive(Default)]
pub(super) struct EndSky {
mesh: Option<([f32; 4], wgpu::Buffer)>,
}
impl EndSky {
/// Called only when the End sky is enabled. Rebuild on atlas UV changes;
/// resource reload and device recreation also replace the owning renderer.
pub(super) fn prepare(&mut self, device: &wgpu::Device, uv: Option<[f32; 4]>) {
let Some(uv) = uv else {
self.mesh = None;
return;
};
if self.mesh.as_ref().is_some_and(|(old, _)| *old == uv) {
return;
}
let vertices = vertices(uv);
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("End sky vertices"),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
self.mesh = Some((uv, buffer));
}
/// The celestial pipeline, atlas bind group and quad indices are already bound.
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {
if let Some((_, buffer)) = &self.mesh {
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw_indexed(0..VERTICES / 4 * 6, 0, 0..1);
}
}
}
/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times,
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
fn vertices(uv: [f32; 4]) -> Vec<Vertex> {
let mut out = Vec::with_capacity(VERTICES as usize);
use std::f32::consts::FRAC_PI_2;
let faces = [
glam::Mat4::IDENTITY,
glam::Mat4::from_rotation_x(FRAC_PI_2),
glam::Mat4::from_rotation_x(-FRAC_PI_2),
glam::Mat4::from_rotation_x(std::f32::consts::PI),
glam::Mat4::from_rotation_z(FRAC_PI_2),
glam::Mat4::from_rotation_z(-FRAC_PI_2),
];
let step = 200.0 / 16.0;
for pose in faces {
for a in 0..16 {
for b in 0..16 {
let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32);
let (x1, z1) = (x0 + step, z0 + step);
let corners = [
(x0, z0, [uv[0], uv[1]]),
(x0, z1, [uv[0], uv[3]]),
(x1, z1, [uv[2], uv[3]]),
(x1, z0, [uv[2], uv[1]]),
];
for (x, z, uv) in corners {
let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z));
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 2,
color: 0xFF28_2828,
light: 0,
});
}
}
}
}
out
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,330 @@
use super::*;
use crate::gfx::{Globals, Renderer};
use bytemuck::Zeroable;
use glam::Mat4;
#[test]
fn geometry_matches_pre_residency_vertex_snapshots() {
use sha2::{Digest, Sha256};
// Captured from game/end.rs at 34c3c1cf for full, tiled and non-binary UVs.
// Quantize positions only, avoiding platform sin/cos rounding differences;
// quad order, UVs, tint, material and light retain their exact byte values.
for (uv, expected) in [
(
[0.0, 0.0, 1.0, 1.0],
"f7ee23457fc557b33ecf09c9afaf858f3d8907e108abf06055f627523f733536",
),
(
[0.125, 0.25, 0.375, 0.5],
"f74c4b8d23ec2b7c11b5752821d0733851bf11358f1b26f9448226ff62a6a318",
),
(
[0.13, 0.27, 0.41, 0.59],
"f0aaa39c5b22168bdc7c6c329acb4d3598a2feb61ff7b6f2850b644682749b39",
),
] {
let mut mesh = vertices(uv);
assert_eq!(mesh.len(), VERTICES as usize);
for vertex in &mut mesh {
vertex.pos = vertex.pos.map(|x| {
let n = (x * 1024.0).round() / 1024.0;
if n == 0.0 { 0.0 } else { n }
});
}
assert_eq!(
format!("{:x}", Sha256::digest(bytemuck::cast_slice(&mesh))),
expected
);
}
}
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
eprintln!("End sky test adapter: {:?}", adapter.get_info());
pollster::block_on(adapter.request_device(&Default::default())).ok()
}
#[test]
fn resident_buffer_survives_frames_and_refreshes_with_the_atlas() {
let Some((device, _)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
let mut sky = EndSky::default();
let uv = [0.125, 0.25, 0.375, 0.5];
sky.prepare(&device, Some(uv));
let first = sky.mesh.as_ref().unwrap().1.clone();
assert_eq!(
first.size(),
u64::from(VERTICES) * size_of::<Vertex>() as u64
);
// Immutable: steady-state frames cannot upload into this buffer.
assert_eq!(first.usage(), wgpu::BufferUsages::VERTEX);
for _ in 0..600 {
sky.prepare(&device, Some(uv));
assert_eq!(sky.mesh.as_ref().unwrap().1, first);
}
let moved = [0.5, 0.5, 0.75, 0.75];
sky.prepare(&device, Some(moved));
assert_ne!(sky.mesh.as_ref().unwrap().1, first);
assert_eq!(sky.mesh.as_ref().unwrap().0, moved);
sky.prepare(&device, None);
assert!(sky.mesh.is_none());
sky.prepare(&device, Some(uv));
assert_ne!(sky.mesh.as_ref().unwrap().1, first);
// A resource reload/device recreation starts a new renderer-owned cache,
// even if the replacement atlas happens to use exactly the same UVs.
let mut replacement = EndSky::default();
replacement.prepare(&device, Some(uv));
assert_ne!(
replacement.mesh.as_ref().unwrap().1,
sky.mesh.as_ref().unwrap().1
);
}
/// The actual entity shader and celestial blend, comparing the old combined
/// vertex stream with a resident sky draw followed by a separate flash draw.
#[test]
fn separate_draws_match_combined_celestial_pixels() {
let Some((device, queue)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("End sky differential shader"),
source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()),
});
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("End sky differential pipeline"),
layout: None,
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_entity"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_celestial"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba8Unorm,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::OVER,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let texture = |pixels: &[u8], width, height| {
device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
pixels,
)
};
// Asymmetric, translucent texels expose UV/winding and blend-order errors.
let pixels: Vec<u8> = (0..16 * 16)
.flat_map(|i| {
[
(i * 17) as u8,
(i * 31) as u8,
(i * 7) as u8,
(80 + i % 176) as u8,
]
})
.collect();
let atlas = texture(&pixels, 16, 16).create_view(&Default::default());
let lightmap = texture(&[255; 4], 1, 1).create_view(&Default::default());
let sampler = device.create_sampler(&Default::default());
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let indices = Renderer::quad_indices(&device, VERTICES / 4 + 1);
let mut resident = EndSky::default();
let uv = [0.125, 0.25, 0.375, 0.5];
resident.prepare(&device, Some(uv));
let first = resident.mesh.as_ref().unwrap().1.clone();
let render = |sky: &EndSky, flash: &[Vertex], combined: bool| {
let target = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 64,
height: 64,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&Default::default());
let mut vertices = if combined { vertices(uv) } else { Vec::new() };
vertices.extend_from_slice(flash);
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 64 * 64 * 4,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &group, &[]);
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
if !combined {
sky.draw(&mut pass);
}
if !vertices.is_empty() {
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw_indexed(0..vertices.len() as u32 / 4 * 6, 0, 0..1);
}
}
encoder.copy_texture_to_buffer(
target.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(256),
rows_per_image: Some(64),
},
},
target.size(),
);
queue.submit([encoder.finish()]);
readback
.slice(..)
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
readback.slice(..).get_mapped_range().unwrap().to_vec()
};
let mut cases = 0;
let mut visible_flash_cases = 0;
for yaw in [0.0_f32, 45.0, 90.0, 180.0, 270.0] {
for pitch in [-85.0_f32, -30.0, 0.0, 45.0, 85.0] {
let mut globals = Globals::zeroed();
globals.view_proj = (Mat4::perspective_rh(90_f32.to_radians(), 1.0, 0.05, 1024.0)
* Mat4::from_rotation_x(pitch.to_radians())
* Mat4::from_rotation_y(yaw.to_radians()))
.to_cols_array_2d();
queue.write_buffer(&uniform, 0, bytemuck::bytes_of(&globals));
let no_flash = render(&resident, &[], true);
for level in [0_u32, 1, 127, 255] {
let flash: Vec<_> = if level == 0 {
Vec::new()
} else {
// Same flash size/height, with an arbitrary EndFlashState pose.
let pose = Mat4::from_rotation_y(1.3) * Mat4::from_rotation_x(-1.6);
[(-60.0, -60.0), (60.0, -60.0), (60.0, 60.0), (-60.0, 60.0)]
.map(|(x, z)| Vertex {
pos: pose.transform_point3(glam::vec3(x, 100.0, z)).to_array(),
uv: [0.75 + x / 480.0, 0.75 + z / 480.0],
layer: 2,
color: level * 0x01010101,
light: 0,
normal: [0; 4],
})
.to_vec()
};
resident.prepare(&device, Some(uv));
let expected = render(&resident, &flash, true);
let actual = render(&resident, &flash, false);
visible_flash_cases += usize::from(expected != no_flash);
assert_eq!(actual, expected, "yaw={yaw} pitch={pitch} flash={level}");
assert!(
actual.as_chunks::<4>().0.iter().any(|p| p[..3] != [0; 3]),
"empty frame"
);
assert_eq!(resident.mesh.as_ref().unwrap().1, first);
cases += 1;
}
}
}
assert!(
visible_flash_cases > 0,
"the flash must affect the comparison"
);
eprintln!("{cases} combined/resident framebuffer cases matched exactly");
}
+211
View File
@@ -0,0 +1,211 @@
//! Seeded, bolt-local lightning meshes retained until their last active bolt disappears.
use crate::{gfx::upload::Uploads, mesher::Vertex};
use glam::DVec3;
use horizon_core::random::{LegacyRandom, RandomSource};
use std::collections::HashMap;
use wgpu::util::DeviceExt;
/// A bolt's render state. Simulation lifetime and flashes stay in the game.
#[derive(Clone, Copy)]
pub struct Bolt {
pub at: [f64; 3],
pub seed: i64,
}
#[derive(Default)]
pub struct Input<'a> {
pub bolts: &'a [Bolt],
/// Current atlas white texel; a changed rect invalidates retained vertices.
pub uv: [f32; 2],
}
// Four layers, fourteen segments (eight trunk, two branches of three), four quads.
pub(super) const QUADS: u32 = 4 * 14 * 4;
/// `LightningBoltRenderer.submit`: keep random draws, layers and quad order unchanged.
fn geometry(seed: i64, uv: [f32; 2]) -> Vec<Vertex> {
let mut out = Vec::with_capacity(QUADS as usize * 4);
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
let mut random = LegacyRandom::new(seed);
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
let (mut x_off, mut z_off) = (0f32, 0f32);
for i in (0..8).rev() {
xs[i] = x_off;
zs[i] = z_off;
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
}
for layer in 0..4 {
let mut random = LegacyRandom::new(seed);
for branch in 0..3 {
let trunk = branch == 0;
let start = 7 - branch;
let end = if trunk { 0 } else { start - 3 + 1 };
let mut sx = xs[start] - x_off;
let mut sz = zs[start] - z_off;
for segment in (end..=start).rev() {
let (ex, ez) = (sx, sz);
let spread = if trunk { 11 } else { 31 };
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
let mut top = 0.1 + layer as f32 * 0.2;
let mut bottom = top;
if trunk {
top *= segment as f32 * 0.1 + 1.0;
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
}
for (rx, rz, lx, lz) in [
(false, false, true, false),
(true, false, true, true),
(true, true, false, true),
(false, true, false, false),
] {
let s = |p: bool, r: f32| if p { r } else { -r };
let y0 = segment as f32 * 16.0;
let corners = [
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
];
for c in corners {
out.push(Vertex {
normal: [0; 4],
pos: c,
uv,
layer: 2,
color,
light: 240 | 240 << 8,
});
}
}
}
}
}
out
}
struct Cached<T> {
mesh: T,
used: bool,
}
/// Shared seeds use the same mesh; storage is bounded by active unique seeds,
/// including after seed changes, removals, dimension switches and disconnects.
struct Cache<T> {
uv: Option<[f32; 2]>,
meshes: HashMap<i64, Cached<T>>,
}
impl<T> Cache<T> {
fn new() -> Self {
Self {
uv: None,
meshes: HashMap::new(),
}
}
fn prepare(&mut self, input: &Input<'_>, mut build: impl FnMut(i64, [f32; 2]) -> T) {
if self.uv != Some(input.uv) {
self.meshes.clear();
self.uv = Some(input.uv);
}
for cached in self.meshes.values_mut() {
cached.used = false;
}
for bolt in input.bolts {
self.meshes
.entry(bolt.seed)
.or_insert_with(|| Cached {
mesh: build(bolt.seed, input.uv),
used: true,
})
.used = true;
}
self.meshes.retain(|_, cached| cached.used);
// HashMap::retain keeps its allocation. Release historical peak capacity
// as well as meshes once the storm (or connection) is gone.
if self.meshes.is_empty() {
self.meshes = HashMap::new();
} else if self.meshes.capacity() > self.meshes.len() * 4 {
self.meshes.shrink_to_fit();
}
}
}
fn offset(bolt: &Bolt, camera: DVec3) -> [f32; 3] {
(DVec3::from_array(bolt.at) - camera).as_vec3().to_array()
}
pub(super) struct Renderer {
cache: Cache<wgpu::Buffer>,
instances: Option<wgpu::Buffer>,
capacity: usize,
}
impl Renderer {
pub(super) fn new() -> Self {
Self {
cache: Cache::new(),
instances: None,
capacity: 0,
}
}
pub(super) fn prepare(
&mut self,
device: &wgpu::Device,
uploads: &mut Uploads,
encoder: &mut wgpu::CommandEncoder,
input: &Input<'_>,
camera: DVec3,
) {
self.cache.prepare(input, |seed, uv| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Lightning vertices"),
contents: bytemuck::cast_slice(&geometry(seed, uv)),
usage: wgpu::BufferUsages::VERTEX,
})
});
if input.bolts.is_empty() {
self.instances = None;
self.capacity = 0;
return;
}
if input.bolts.len() > self.capacity || input.bolts.len() < self.capacity / 4 {
self.capacity = input.bolts.len().next_power_of_two();
self.instances = Some(device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Lightning offsets"),
size: (self.capacity * std::mem::size_of::<[f32; 3]>()) as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}));
}
let offsets: Vec<_> = input
.bolts
.iter()
.map(|bolt| offset(bolt, camera))
.collect();
uploads.buffer(
encoder,
self.instances.as_ref().unwrap(),
0,
bytemuck::cast_slice(&offsets),
);
}
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, input: &Input<'_>) {
let Some(instances) = &self.instances else {
return;
};
pass.set_vertex_buffer(1, instances.slice(..));
// Follow simulation order, including repeated seeds; HashMap order must
// never change additive accumulation or the order before dragon rays.
for (i, bolt) in input.bolts.iter().enumerate() {
pass.set_vertex_buffer(0, self.cache.meshes[&bolt.seed].mesh.slice(..));
pass.draw_indexed(0..QUADS * 6, 0, i as u32..i as u32 + 1);
}
}
}
#[cfg(test)]
mod tests;
@@ -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<Vertex> {
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<i64> {
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::<Vertex>() 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<Vec<u8>> = 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");
}
}
+74
View File
@@ -0,0 +1,74 @@
//! The anonymous "I'm playing" ping (`horizon_telemetry::live`, docs/telemetry.md) behind the
//! launcher's "N playing now". While the game runs, a thread of its own sends a random session
//! ID made here and kept only in memory, the version, the platform and whether a LAN or
//! play-with-friends world is open, every minute and at once when that last one changes.
//! It sends nothing when there is no server (`HORIZON_TELEMETRY_URL`, none by default) or
//! with `HORIZON_NO_HEARTBEAT=1` (automated runs).
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::Thread;
use std::time::Duration;
use horizon_telemetry::live::{self, Ping};
/// A world is open to LAN or to friends.
static LAN: AtomicBool = AtomicBool::new(false);
static PINGER: OnceLock<Thread> = OnceLock::new();
/// After a failure the next ping waits longer, doubling up to this.
const MAX_WAIT: Duration = Duration::from_secs(600);
/// Starts the pings, once. Call when the game itself starts (not a dedicated server, not a
/// benchmark or an automated run).
pub fn start() {
if PINGER.get().is_some() || std::env::var_os("HORIZON_NO_HEARTBEAT").is_some() {
return;
}
let Some(endpoint) = horizon_telemetry::endpoint() else {
return;
};
let spawned = std::thread::Builder::new()
.name("Heartbeat".into())
.spawn(move || run(&endpoint));
match spawned {
Ok(handle) => {
let _ = PINGER.set(handle.thread().clone());
}
Err(e) => log::warn!("Horizon: no live count ping: {e}"),
}
}
/// Whether a world is open to LAN or friends; a change is sent at once.
pub fn set_lan(open: bool) {
if LAN.swap(open, Ordering::Relaxed) != open
&& let Some(pinger) = PINGER.get()
{
pinger.unpark();
}
}
fn run(endpoint: &str) {
let session = live::session_id();
let version = crate::telemetry::version();
let mut wait = live::INTERVAL;
let mut failed = false;
loop {
let ping = Ping::new(&session, &version, LAN.load(Ordering::Relaxed));
match live::send(endpoint, &ping) {
Ok(()) => {
wait = live::INTERVAL;
failed = false;
}
Err(e) => {
// Said once, not every minute the server is away.
if !failed {
log::info!("Horizon: the live count ping failed ({e}); trying again later");
}
failed = true;
wait = (wait * 2).min(MAX_WAIT);
}
}
// Woken early by `set_lan`; a spurious wake only sends one ping more.
std::thread::park_timeout(wait);
}
}
+64 -4
View File
@@ -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/<sha1>`), 64x64 each.
@@ -365,6 +367,8 @@ pub struct HudBatch {
pub blends: Vec<(std::ops::Range<u32>, Blend)>,
/// The textures and time of the `Blend::EndPortal` runs.
pub end_portal: EndPortalFill,
/// 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)]
@@ -414,6 +418,7 @@ impl HudBatch {
patches: Vec::new(),
blends: Vec::new(),
end_portal: EndPortalFill::default(),
blur_at: 0,
}
}
/// Draw the vertices added since `start` with the inverting blend.
@@ -466,6 +471,14 @@ impl HudBatch {
}
out
}
fn runs_in(&self, vertices: std::ops::Range<u32>) -> Vec<(std::ops::Range<u32>, 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) {
(
@@ -1143,7 +1156,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<u32>,
) {
if vertices.is_empty() || size.contains(&0) {
return;
}
let attachments = [Some(wgpu::RenderPassColorAttachment {
@@ -1155,7 +1187,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 {
@@ -1416,6 +1448,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.
@@ -1428,6 +1487,7 @@ mod tests {
patches: Vec::new(),
blends: Vec::new(),
end_portal: EndPortalFill::default(),
blur_at: 0,
};
for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] {
assert_eq!(
+26 -7
View File
@@ -302,7 +302,10 @@ fn filterable_text(t: &Tag) -> Option<String> {
fn read_text(t: &Tag) -> Option<String> {
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,
}
}
@@ -594,12 +597,8 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
),
));
}
if let Some(mode) = d.map_post_processing {
entries.push((
"minecraft:map_post_processing",
Tag::String(if mode == 0 { "lock" } else { "scale" }.into()),
));
}
// minecraft:map_post_processing is transient: ItemStack.CODEC never
// saves it (only the network carries it).
if !d.charged.is_empty() {
entries.push((
"minecraft:charged_projectiles",
@@ -864,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);
+77
View File
@@ -486,10 +486,28 @@ pub fn lines(
translate: &dyn Fn(&str) -> Option<String>,
) -> Vec<String> {
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<String> {
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");
+1 -1
View File
@@ -778,7 +778,7 @@ fn play(c: Connection, shared: &Arc<Shared>, parts: Parts, address: std::net::So
std::thread::Builder::new()
.name(format!("horizon-lan-out-{conn_id}"))
.spawn(move || {
// A dedicated server's tick comes first (horizon_threads).
// Ticks and frames come first (horizon_threads).
horizon_threads::behind_server();
write_loop(writer, rx, alive, latency, pending)
})
+16 -4
View File
@@ -455,18 +455,30 @@ impl Hub {
let Slots::Block(pos) = m.slots else {
return;
};
// AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess.
// AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess,
// CrafterBlockEntity.containerData.
let data = match world.block_entities.get(&pos) {
Some(BlockEntity::Furnace(f)) => [
Some(BlockEntity::Furnace(f)) => vec![
f.lit_remaining,
f.lit_total,
f.cooking_timer,
f.cooking_total,
],
Some(BlockEntity::Brewing(b)) => [b.brew_time, b.fuel, b.total_brew_time, b.total_fuel],
Some(BlockEntity::Brewing(b)) => {
vec![b.brew_time, b.fuel, b.total_brew_time, b.total_fuel]
}
// CrafterBlockEntity.containerData: the disabled slots, then triggered.
Some(BlockEntity::Crafter(c)) => c
.disabled
.iter()
.chain([&c.triggered])
.map(|&d| i32::from(d))
.collect(),
_ => return,
}
.map(|v| v as i16);
.into_iter()
.map(|v| v as i16)
.collect::<Vec<i16>>();
m.sent_data.resize(data.len(), i16::MIN);
let window = m.window;
let changed: Vec<(usize, i16)> = data
+92 -1
View File
@@ -34,7 +34,7 @@ pub fn changed_attributes(
}
/// What the game says about one entity this tick.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EntityState {
pub id: i32,
pub uuid: u128,
@@ -61,6 +61,72 @@ pub struct EntityState {
pub precise: bool,
}
impl EntityState {
/// The entity `id` of type `kind` as a fresh state has it: at the origin,
/// at rest, with no data, equipment or attributes. Keeps the allocations
/// of the strings and vectors it held.
pub fn reset(&mut self, id: i32, uuid: u128, kind: &str) {
self.id = id;
self.uuid = uuid;
self.kind.clear();
self.kind.push_str(kind);
self.position = [0.0; 3];
(self.yaw, self.pitch, self.head_yaw) = (0.0, 0.0, 0.0);
self.on_ground = false;
self.velocity = [0.0; 3];
self.data = 0;
self.meta.clear();
self.equipment.clear();
self.attributes.clear();
self.precise = false;
}
}
/// The states a level describes its entities with, kept from tick to tick:
/// each tick's are written over the last tick's in place, so the strings and
/// vectors in them are reused instead of being made and freed again for every
/// entity on every tick.
#[derive(Default)]
pub struct States {
list: Vec<EntityState>,
len: usize,
}
impl States {
/// Start a new tick's states.
pub fn clear(&mut self) {
self.len = 0;
}
/// The next entity's state, reset (`EntityState::reset`).
pub fn add(&mut self, id: i32, uuid: u128, kind: &str) -> &mut EntityState {
if self.len == self.list.len() {
self.list.push(EntityState::default());
}
let e = &mut self.list[self.len];
self.len += 1;
e.reset(id, uuid, kind);
e
}
pub fn push(&mut self, e: EntityState) {
match self.list.get_mut(self.len) {
Some(slot) => *slot = e,
None => self.list.push(e),
}
self.len += 1;
}
pub fn as_slice(&self) -> &[EntityState] {
&self.list[..self.len]
}
}
impl Extend<EntityState> for States {
fn extend<I: IntoIterator<Item = EntityState>>(&mut self, states: I) {
for e in states {
self.push(e);
}
}
}
/// `AbstractArrow`: every update sends its position and rotation.
fn is_arrow(kind: &str) -> bool {
matches!(
@@ -792,6 +858,31 @@ mod tests {
}
}
#[test]
fn states_are_written_over_last_ticks_in_place() {
let mut states = States::default();
let e = states.add(1, 1, "minecraft:zombie");
e.position = [1.0, 2.0, 3.0];
e.meta.push((9, serializer::FLOAT, Value::Float(20.0)));
e.equipment.push((0, None));
let (kind, meta) = (e.kind.as_ptr(), e.meta.as_ptr());
states.push(state(2.0));
states.clear();
let e = states.add(3, 3, "minecraft:husk");
// Nothing of the last tick's state is left, but its allocations are.
let fresh = EntityState {
id: 3,
uuid: 3,
kind: "minecraft:husk".into(),
..EntityState::default()
};
assert_eq!(*e, fresh);
assert_eq!((e.kind.as_ptr(), e.meta.as_ptr()), (kind, meta));
assert_eq!(states.as_slice(), std::slice::from_ref(&fresh));
states.extend([state(5.0), state(6.0)]);
assert_eq!(states.as_slice(), [fresh, state(5.0), state(6.0)]);
}
/// The entity as added this tick, then its updates (one a tick).
fn added(e: &EntityState) -> ServerEntity {
ServerEntity::new(e, Some(100), &Riding::default())
+40
View File
@@ -147,6 +147,8 @@ pub struct Guest {
pub xp_level: i32,
pub xp_progress: f32,
pub xp_total: i32,
/// `Player.enchantmentSeed` (the enchanting table's offers).
pub xp_seed: i32,
/// Active status effects (`LivingEntity.activeEffects`).
pub effects: crate::effects::PlayerEffects,
/// What the client was told of each effect: id, amplifier, flags, and
@@ -273,6 +275,7 @@ impl Guest {
xp_level: 0,
xp_progress: 0.0,
xp_total: 0,
xp_seed: 0,
effects: Default::default(),
sent_effects: Vec::new(),
menu_sent: vec![None; 46],
@@ -418,6 +421,43 @@ pub fn stack_to_network(
horizon_protocol::item::Component::Int(id),
));
}
if d.repair_cost > 0 {
stack.added.push((
horizon_protocol::item::component::REPAIR_COST,
horizon_protocol::item::Component::Int(d.repair_cost as i32),
));
}
if let Some(mode) = d.map_post_processing {
stack.added.push((
horizon_protocol::item::component::MAP_POST_PROCESSING,
horizon_protocol::item::Component::Int(i32::from(mode)),
));
}
// The books a lectern shows and a guest reads.
if !d.writable_pages.is_empty() {
stack.added.push((
horizon_protocol::item::component::WRITABLE_BOOK_CONTENT,
horizon_protocol::item::Component::WritableBook(d.writable_pages.clone()),
));
}
if let Some(w) = &d.written {
stack.added.push((
horizon_protocol::item::component::WRITTEN_BOOK_CONTENT,
horizon_protocol::item::Component::WrittenBook(
horizon_protocol::item::WrittenBook {
title: w.title.clone(),
author: w.author.clone(),
generation: i32::from(w.generation),
pages: w
.pages
.iter()
.map(|p| horizon_protocol::text::literal(p))
.collect(),
resolved: true,
},
),
));
}
}
if let Some(name) = s.custom_name() {
stack.added.push((
+103 -14
View File
@@ -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 {
@@ -311,6 +335,11 @@ impl Hub {
self.sync.id(registry, name)
}
/// The name of a network id in a built-in registry.
pub fn registry_name(&self, registry: &str, id: i32) -> Option<&str> {
self.sync.builtin.get(registry)?.name(id)
}
pub fn item_id(&mut self, item: &Arc<str>) -> i32 {
if let Some(id) = self.item_ids.get(item) {
return *id;
@@ -1290,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,
@@ -2480,3 +2496,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()
);
}
}
}
}
@@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.xp_level = level.xp_level;
guest.xp_progress = level.xp_progress;
guest.xp_total = level.xp_total;
guest.xp_seed = level.xp_seed;
guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects);
guest.game_mode = level.mode();
guest.flying = level.flying;
@@ -127,6 +128,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
level.xp_level = guest.xp_level;
level.xp_progress = guest.xp_progress;
level.xp_total = guest.xp_total;
level.xp_seed = guest.xp_seed;
level.active_effects = guest.effects.saved();
level.game_mode = guest.game_mode;
level.creative = guest.game_mode == 1;
+1
View File
@@ -80,6 +80,7 @@ pub mod graphics;
pub mod graphics_style;
pub mod graphics_ui;
pub mod health;
pub mod heartbeat;
pub mod hotbar;
pub mod hud;
pub mod hud_layout;
File diff suppressed because it is too large Load Diff
+576 -23
View File
@@ -690,6 +690,8 @@ pub struct Extra {
pub blocking: bool,
pub fall_flying: bool,
pub fall_fly_ticks: i32,
/// `LivingEntity.isAutoSpinAttack` (Riptide).
pub auto_spin_attack: bool,
pub main_hand_left: bool,
pub elytra: ElytraAnimation,
pub swim: SwimAnimation,
@@ -805,7 +807,11 @@ pub struct Mob {
pub persistent: bool,
/// `CustomName` (plain text) and `CustomNameVisible`.
pub custom_name: Option<String>,
/// The styled `CustomName`, when it came from a component.
pub custom_name_text: Option<crate::text::Text>,
pub name_visible: bool,
/// `Entity.DATA_SHARED_FLAGS_ID` bit 0x20: the model is hidden.
pub invisible: bool,
pub random: LegacyRandom,
pub ai: Box<ai::Ai>,
pub extra: Extra,
@@ -844,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<MobEvent>,
/// The skin texture of a player mob (`PlayerInfo.getSkin`), which
/// replaces the type's default when its download is ready.
pub skin: Option<String>,
}
/// Events a mob tick asks the game to act on.
#[derive(Clone, Debug)]
@@ -1308,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<MobEvent>, 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<MobEvent>, 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<u32, Vec<Vec3>>,
}
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
@@ -1404,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,
@@ -1418,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<u32, u32>>,
pub daylight: bool,
pub game_time: i64,
pub day_time: i64,
@@ -1436,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<Teams<'a>>,
/// 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<crate::scoreboard::Team>,
pub mobs: HashMap<u32, crate::scoreboard::Team>,
pub struct Teams<'a> {
pub player: Option<&'a crate::scoreboard::Team>,
pub mobs: HashMap<u32, &'a crate::scoreboard::Team>,
}
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(),
}
}
}
@@ -1513,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,
@@ -2137,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<u32, [i32; 4]>) {
let mut board = Scoreboard::default();
board.add_team("red");
board.add_to_team("Steve", "red");
let uuids: HashMap<u32, [i32; 4]> = (0..mobs)
.map(|id| (id, [id as i32, 7, -(id as i32), 11]))
.collect();
for (id, uuid) in &uuids {
if id % 2 == 0 {
board.add_to_team(&uuid_text(*uuid), "red");
}
}
(board, uuids)
}
/// `Game::mob_teams` as built for each mob before: owned clones of the teams.
fn owned(board: &Scoreboard, uuids: &HashMap<u32, [i32; 4]>) -> HashMap<u32, Team> {
uuids
.iter()
.filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?.clone())))
.collect()
}
fn borrowed<'a>(board: &'a Scoreboard, uuids: &HashMap<u32, [i32; 4]>) -> Teams<'a> {
Teams {
player: board.players_team("Steve"),
mobs: uuids
.iter()
.filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?)))
.collect(),
}
}
#[test]
fn borrowed_teams_answer_as_the_clones() {
let (board, uuids) = board(40);
let teams = borrowed(&board, &uuids);
let old = owned(&board, &uuids);
for id in 0..41 {
assert_eq!(teams.of(Who::Mob(id)), old.get(&id), "mob {id}");
}
assert_eq!(teams.of(Who::Player).map(|t| t.name.as_str()), Some("red"));
}
/// One tick's worth of team building: once per mob (before) against once.
#[test]
#[ignore]
fn teams_cost() {
for mobs in [100u32, 250, 500] {
let (board, uuids) = board(mobs);
let t = std::time::Instant::now();
for _ in 0..mobs {
std::hint::black_box(owned(&board, &uuids));
}
let before = t.elapsed();
let t = std::time::Instant::now();
let reps = 20;
for _ in 0..reps {
std::hint::black_box(borrowed(&board, &uuids));
}
let after = t.elapsed() / reps;
println!(
"{mobs} mobs, half on a team: per tick {:.3} ms -> {:.3} ms",
before.as_secs_f64() * 1e3,
after.as_secs_f64() * 1e3
);
}
}
}
#[cfg(test)]
mod sensor_scan_tests {
use super::*;
use horizon_core::geometry::Vec3;
use serde_json::json;
fn kind() -> Arc<MobType> {
Arc::new(MobType {
id: "minecraft:cow".into(),
species: Species::Cow,
width: 0.9,
height: 1.4,
eye_height: 1.3,
category: "creature".into(),
max_health: 10.0,
speed: 0.2,
flying_speed: 0.4,
attack_damage: 0.0,
attack_knockback: 0.0,
follow_range: 16.0,
step_height: 0.6,
armor: 0.0,
armor_toughness: 0.0,
knockback_resistance: 0.0,
jump_strength: 0.42,
attributes: Arc::default(),
gravity: 0.08,
safe_fall_distance: 3.0,
fall_damage_multiplier: 1.0,
water_efficiency: 0.0,
water_slowdown: 0.8,
air_speed: 0.02,
baby_scale: 0.5,
head_rot_speed: 10.0,
max_head_x_rot: 40.0,
max_head_y_rot: 75.0,
ambient_interval: 120,
flags: Flags {
animal: true,
..Default::default()
},
model: Arc::new(Part::parse("root", &json!({}))),
layers: HashMap::new(),
texture: String::new(),
brain: Brain::Passive,
anim: Anim::Rabbit,
sounds: [""; 3],
step_sound: None,
food: Arc::default(),
tempt: Arc::default(),
})
}
/// `n` mobs in pens of 20 spread over a square of `side` blocks, as on a
/// server's farms; their snapshot and its grid.
fn herd(n: u32, side: f64) -> (Vec<Seen>, seen_grid::SeenGrid) {
let kind = kind();
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
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 pen = Vec3::ZERO;
let seen: Vec<Seen> = (0..n)
.map(|id| {
if id % 20 == 0 {
pen = Vec3::new(next(side), 64.0, next(side));
}
let at = Vec3::new(pen.x + next(8.0), 64.0, pen.z + next(8.0));
Mob::new(id, kind.clone(), at, 0.0).seen(None)
})
.collect();
let grid = seen_grid::SeenGrid::new(seen.iter().map(|s| s.bounds));
(seen, grid)
}
/// `NearestLivingEntitySensor` over every mob, as the brains ran it.
fn scan(seen: &[Seen], me: &Seen, area: Aabb) -> Vec<u32> {
seen.iter()
.filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area))
.map(|o| o.id)
.collect()
}
fn indexed(seen: &[Seen], grid: &seen_grid::SeenGrid, me: &Seen, area: Aabb) -> Vec<u32> {
let mut near = Vec::new();
assert!(grid.candidates(area, &mut near));
near.iter()
.map(|&i| &seen[i as usize])
.filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area))
.map(|o| o.id)
.collect()
}
#[test]
fn the_grid_finds_what_the_scan_finds() {
let (seen, grid) = herd(600, 160.0);
for me in &seen {
let area = me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0));
assert_eq!(indexed(&seen, &grid, me, area), scan(&seen, me, area));
}
}
/// `MobWorld::seen` once per mob (a target, a breeding partner...), by
/// scan as before and by the tick's id index.
#[test]
#[ignore]
fn lookup_cost() {
for n in [500u32, 1000, 2000] {
let (seen, _) = herd(n, 256.0);
let index: crate::fast_hash::FxHashMap<u32, u32> = seen
.iter()
.enumerate()
.map(|(i, s)| (s.id, i as u32))
.collect();
let wanted: Vec<u32> = (0..n).map(|i| (i * 7919) % n).collect();
let t = std::time::Instant::now();
let a: usize = wanted
.iter()
.filter_map(|&id| seen.iter().find(|s| s.id == id))
.map(|s| s.id as usize)
.sum();
let before = t.elapsed().as_secs_f64() * 1e3;
let t = std::time::Instant::now();
let b: usize = wanted
.iter()
.filter_map(|&id| index.get(&id).map(|&i| &seen[i as usize]))
.map(|s| s.id as usize)
.sum();
let after = t.elapsed().as_secs_f64() * 1e3;
assert_eq!(a, b);
println!(
"{n} lookups over {n} mobs ({} B each): {before:.3} ms -> {after:.3} ms",
std::mem::size_of::<Seen>()
);
}
}
/// Natural spawning's `isUnobstructed` box test against every mob (real
/// `Mob`s), by scan and by a grid built once for the pass.
#[test]
#[ignore]
fn spawn_box_cost() {
let kind = kind();
for n in [500u32, 1000, 2000] {
let (seen, _) = herd(n, 384.0);
let mobs: Vec<Mob> = seen
.iter()
.map(|s| Mob::new(s.id, kind.clone(), s.position, 0.0))
.collect();
let mut seed = 7u64;
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 queries: Vec<Aabb> = (0..100)
.map(|_| {
let (x, z) = (next(384.0), next(384.0));
Aabb::new(Vec3::new(x, 64.0, z), Vec3::new(x + 0.9, 65.4, z + 0.9))
})
.collect();
let t = std::time::Instant::now();
let a: Vec<bool> = queries
.iter()
.map(|&q| {
mobs.iter()
.any(|m| m.alive() && !m.removed && m.bounds().intersects(q))
})
.collect();
let before = t.elapsed().as_secs_f64() * 1e3;
let t = std::time::Instant::now();
let boxes: Vec<Aabb> = mobs.iter().map(|m| m.bounds()).collect();
let grid = seen_grid::SeenGrid::new(boxes.iter().copied());
let build = t.elapsed().as_secs_f64() * 1e3;
let mut near = Vec::new();
let b: Vec<bool> = queries
.iter()
.map(|&q| {
assert!(grid.candidates(q, &mut near));
near.iter().any(|&i| boxes[i as usize].intersects(q))
})
.collect();
let after = t.elapsed().as_secs_f64() * 1e3;
assert_eq!(a, b);
println!(
"{n} mobs, 100 spawn box tests: {before:.3} ms -> {after:.3} ms (grid build {build:.3} ms included)"
);
}
}
/// One tick of sensing: a twentieth of the mobs fire their sensor.
#[test]
#[ignore]
fn sensor_cost() {
for (n, side) in [(500u32, 256.0), (1000, 384.0), (2000, 512.0)] {
let (seen, grid) = herd(n, side);
let time = |f: &dyn Fn(&Seen, Aabb) -> usize| {
let t = std::time::Instant::now();
let mut found = 0;
for me in &seen {
found += f(me, me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0)));
}
(t.elapsed().as_secs_f64() * 1e3 / 20.0, found)
};
let (before, a) = time(&|me, area| scan(&seen, me, area).len());
let (after, b) = time(&|me, area| indexed(&seen, &grid, me, area).len());
assert_eq!(a, b);
println!("{n} mobs: per tick {before:.3} ms -> {after:.3} ms");
}
}
}
#[cfg(test)]
mod push_tests {
use super::*;
use horizon_core::geometry::Vec3;
use serde_json::json;
fn kind() -> Arc<MobType> {
Arc::new(MobType {
id: "minecraft:cow".into(),
species: Species::Cow,
width: 0.9,
height: 1.4,
eye_height: 1.3,
category: "creature".into(),
max_health: 10.0,
speed: 0.2,
flying_speed: 0.4,
attack_damage: 0.0,
attack_knockback: 0.0,
follow_range: 16.0,
step_height: 0.6,
armor: 0.0,
armor_toughness: 0.0,
knockback_resistance: 0.0,
jump_strength: 0.42,
attributes: Arc::default(),
gravity: 0.08,
safe_fall_distance: 3.0,
fall_damage_multiplier: 1.0,
water_efficiency: 0.0,
water_slowdown: 0.8,
air_speed: 0.02,
baby_scale: 0.5,
head_rot_speed: 10.0,
max_head_x_rot: 40.0,
max_head_y_rot: 75.0,
ambient_interval: 120,
flags: Flags {
animal: true,
..Default::default()
},
model: Arc::new(Part::parse("root", &json!({}))),
layers: HashMap::new(),
texture: String::new(),
brain: Brain::Passive,
anim: Anim::Rabbit,
sounds: [""; 3],
step_sound: None,
food: Arc::default(),
tempt: Arc::default(),
})
}
/// The pending pushes as one list, scanned for each mob, as before.
fn take_old(events: &mut Vec<MobEvent>, from: usize, pending: &mut Vec<(u32, Vec3)>) {
let mut i = from;
while i < 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);
} else {
i += 1;
}
}
}
fn apply_old(velocity: &mut Vec3, id: u32, pending: &mut Vec<(u32, Vec3)>) {
pending.retain(|(to, v)| {
if *to != id {
return true;
}
*velocity = Vec3::new(velocity.x + v.x, velocity.y + v.y, velocity.z + v.z);
false
});
}
fn mobs(n: u32) -> Vec<Mob> {
let kind = kind();
(0..n)
.map(|id| Mob::new(id, kind.clone(), Vec3::ZERO, 0.0))
.collect()
}
/// A crowd tick: each mob takes its pushes, then pushes every other
/// mob (and the player, and hisses now and then); then all take theirs.
fn crowd_tick(
n: u32,
tick: u32,
mut on_push: impl FnMut(&mut Vec<MobEvent>, usize),
mut on_apply: impl FnMut(u32),
) -> Vec<MobEvent> {
let mut events = Vec::new();
for i in 0..n {
on_apply(i);
let from = events.len();
for j in 0..n {
if j != i && !(i * 31 + j * 17 + tick).is_multiple_of(5) {
let f = f64::from(i * 7 + j + tick) * 0.001;
events.push(MobEvent::Push {
target: Who::Mob(j),
velocity: [f, -f * 0.5, f * 0.25],
});
}
if j.is_multiple_of(9) {
events.push(MobEvent::Hiss { mob: j });
}
}
events.push(MobEvent::Push {
target: Who::Player,
velocity: [0.1, 0.0, 0.1],
});
on_push(&mut events, from);
}
for i in 0..n {
on_apply(i);
}
events
}
#[test]
fn pushes_land_as_with_the_list() {
for n in [1u32, 3, 8, 20, 60] {
let mut new_mobs = mobs(n);
let mut old_v = vec![Vec3::ZERO; n as usize];
let mut pending = PendingPushes::default();
let mut old_pending = Vec::new();
for tick in 0..4 {
let new_events = {
let pending = std::cell::RefCell::new(&mut pending);
let mobs = std::cell::RefCell::new(&mut new_mobs);
crowd_tick(
n,
tick,
|e, from| take_mob_pushes(e, from, &mut pending.borrow_mut()),
|i| {
apply_mob_pushes(
&mut mobs.borrow_mut()[i as usize],
&mut pending.borrow_mut(),
)
},
)
};
let old_events = {
let pending = std::cell::RefCell::new(&mut old_pending);
let v = std::cell::RefCell::new(&mut old_v);
crowd_tick(
n,
tick,
|e, from| take_old(e, from, &mut pending.borrow_mut()),
|i| {
apply_old(
&mut v.borrow_mut()[i as usize],
i,
&mut pending.borrow_mut(),
)
},
)
};
assert_eq!(format!("{new_events:?}"), format!("{old_events:?}"));
for i in 0..n as usize {
let (a, b) = (new_mobs[i].velocity, old_v[i]);
assert_eq!(
(a.x.to_bits(), a.y.to_bits(), a.z.to_bits()),
(b.x.to_bits(), b.y.to_bits(), b.z.to_bits()),
"{n} mobs, tick {tick}, mob {i}"
);
}
}
}
}
/// One tick of a pen of `n` mobs pushing each other.
#[test]
#[ignore]
fn push_cost() {
for n in [10u32, 30, 100, 200] {
let mut ms = mobs(n);
let mut v = vec![Vec3::ZERO; n as usize];
let t = std::time::Instant::now();
{
let pending = std::cell::RefCell::new(Vec::new());
let v = std::cell::RefCell::new(&mut v);
crowd_tick(
n,
0,
|e, from| take_old(e, from, &mut pending.borrow_mut()),
|i| {
apply_old(
&mut v.borrow_mut()[i as usize],
i,
&mut pending.borrow_mut(),
)
},
);
}
let before = t.elapsed().as_secs_f64() * 1e3;
let t = std::time::Instant::now();
{
let pending = std::cell::RefCell::new(PendingPushes::default());
let ms = std::cell::RefCell::new(&mut ms);
crowd_tick(
n,
0,
|e, from| take_mob_pushes(e, from, &mut pending.borrow_mut()),
|i| {
apply_mob_pushes(
&mut ms.borrow_mut()[i as usize],
&mut pending.borrow_mut(),
)
},
);
}
let after = t.elapsed().as_secs_f64() * 1e3;
println!("{n} mobs pushing each other: {before:.3} ms -> {after:.3} ms");
}
}
}
@@ -606,7 +606,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) {
let r = m.attrs.follow_range;
let area = m.bounds().inflate(Vec3::new(r, r, r));
let mut found: Vec<(Who, f64)> = Vec::new();
for o in w.others {
for o in w.others_near(area) {
if o.id != m.id && o.alive && o.bounds.intersects(area) {
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
}
+1 -1
View File
@@ -441,7 +441,7 @@ impl Goal for PufferfishPuff {
.as_ref()
.is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds));
// TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive.
let mob = cx.w.others.iter().any(|s| {
let mob = cx.w.others_near(area).any(|s| {
s.id != m.id
&& s.alive
&& !matches!(
+5 -6
View File
@@ -391,12 +391,11 @@ impl Goal for LeaveBlock {
let target = cx.w.world.block(x, y, z);
let below = cx.w.world.block(x, y - 1, z);
let bf = cx.w.facts.get(below);
let free = !cx.w.others.iter().any(|s| {
s.bounds.intersects(Aabb::new(
Vec3::new(f64::from(x), f64::from(y), f64::from(z)),
Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)),
))
});
let block = Aabb::new(
Vec3::new(f64::from(x), f64::from(y), f64::from(z)),
Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)),
);
let free = !cx.w.others_near(block).any(|s| s.bounds.intersects(block));
if cx.w.facts.is_air(target)
&& !cx.w.facts.is_air(below)
&& &*bf.name != "minecraft:bedrock"
+12 -4
View File
@@ -1,7 +1,11 @@
//! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags,
//! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`.
use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo};
use horizon_core::{geometry::Vec3, jmath, random::RandomSource};
use horizon_core::{
geometry::{Aabb, Vec3},
jmath,
random::RandomSource,
};
use std::sync::Arc;
pub const MOVE: u8 = 1;
@@ -970,8 +974,7 @@ impl Goal for LookAtPlayer {
let (id, only) = (m.id, self.only);
let at = Vec3::new(m.position.x, m.eye_y(), m.position.z);
let candidates: Vec<(u32, Vec3)> =
cx.w.others
.iter()
cx.w.others_near(area)
.filter(|s| s.id != id && s.alive && s.bounds.intersects(area))
.filter(|s| only.is_none_or(|o| s.species == o))
.map(|s| (s.id, s.position))
@@ -1902,7 +1905,12 @@ impl Goal for FollowParent {
let species = m.species();
let pos = m.position;
let mut best: Option<(u32, f64)> = None;
for s in cx.w.others.iter().filter(|s| {
// Every position in range puts the box's bottom face in this area.
let area = Aabb::new(
Vec3::new(pos.x - 9.0, pos.y - 5.0, pos.z - 9.0),
Vec3::new(pos.x + 9.0, pos.y + 5.0, pos.z + 9.0),
);
for s in cx.w.others_near(area).filter(|s| {
s.alive
&& s.species == species
&& !s.baby
+4 -1
View File
@@ -68,7 +68,10 @@ impl Goal for DefendVillage {
if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 {
return false;
}
let bad = cx.w.others.iter().any(|s| {
// A position inside `b` puts the box's bottom face there (one block
// wider, as the box test is strict).
let near = b.inflate(Vec3::new(1.0, 1.0, 1.0));
let bad = cx.w.others_near(near).any(|s| {
s.species == Species::Villager
&& s.alive
&& s.player_rep <= -100
@@ -299,7 +299,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) {
let r = m.attrs.follow_range;
let area = m.bounds().inflate(Vec3::new(r, r, r));
let mut found: Vec<(Who, f64)> = Vec::new();
for o in w.others {
for o in w.others_near(area) {
if o.id != m.id && o.alive && o.bounds.intersects(area) {
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
}
+1 -1
View File
@@ -177,7 +177,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
velocity: fling(p.position),
});
}
for s in w.others.iter() {
for s in w.others_near(area) {
if s.id == m.id || !s.alive || s.species == Species::Ravager || !s.bounds.intersects(area) {
continue;
}
+12 -2
View File
@@ -104,7 +104,10 @@ pub fn body(m: &Mob) -> (String, String) {
}
};
if &*m.kind.id == "minecraft:player" {
return ("main".into(), m.kind.texture.to_string());
return (
"main".into(),
m.skin.clone().unwrap_or_else(|| m.kind.texture.clone()),
);
}
match m.species() {
S::Llama | S::TraderLlama => {
@@ -771,6 +774,11 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4
.sqrt()
.min(1.0);
base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians());
} else if m.extra.auto_spin_attack {
// Riptide: lying along the look direction, spinning 75 degrees a tick.
let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha;
base *= glam::Mat4::from_rotation_x((-90.0 - pitch).to_radians())
* glam::Mat4::from_rotation_y(((m.age as f32 + alpha) * -75.0).to_radians());
} else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) {
// isEntityUpsideDown
base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0))
@@ -781,7 +789,9 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4
let ticks = m.extra.fall_fly_ticks as f32 + alpha;
let scale = (ticks * ticks / 100.0).min(1.0);
let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha;
base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians());
if !m.extra.auto_spin_attack {
base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians());
}
let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha;
let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos());
let v = m.velocity;
@@ -691,33 +691,37 @@ pub struct StructureAt {
}
/// `NetherFortressStructure.FORTRESS_ENEMIES`.
pub fn fortress_enemies() -> Vec<SpawnEntry> {
let e = |entity: &str, weight, min, max, constant| SpawnEntry {
entity: entity.to_owned(),
weight,
min,
max,
constant,
};
vec![
e("minecraft:blaze", 10, 2, 3, false),
e("minecraft:zombified_piglin", 5, 4, 4, true),
e("minecraft:wither_skeleton", 8, 5, 5, true),
e("minecraft:skeleton", 2, 5, 5, true),
e("minecraft:magma_cube", 3, 4, 4, true),
]
pub fn fortress_enemies() -> &'static [SpawnEntry] {
static ENEMIES: std::sync::LazyLock<Vec<SpawnEntry>> = std::sync::LazyLock::new(|| {
let e = |entity: &str, weight, min, max, constant| SpawnEntry {
entity: entity.to_owned(),
weight,
min,
max,
constant,
};
vec![
e("minecraft:blaze", 10, 2, 3, false),
e("minecraft:zombified_piglin", 5, 4, 4, true),
e("minecraft:wither_skeleton", 8, 5, 5, true),
e("minecraft:skeleton", 2, 5, 5, true),
e("minecraft:magma_cube", 3, 4, 4, true),
]
});
&ENEMIES
}
/// `NaturalSpawner.mobsAt`: the fortress bounds on nether bricks, then
/// `ChunkGenerator.getMobsAt` (the first referenced structure whose override
/// for the category holds the position), else the biome's list.
/// for the category holds the position), else the biome's list. Borrowed from
/// the level: a spawn attempt looks it up up to twice.
pub fn mobs_at<L: NaturalLevel>(
l: &L,
category: Category,
x: i32,
y: i32,
z: i32,
) -> Vec<SpawnEntry> {
) -> &[SpawnEntry] {
// Only a fortress or a structure overriding this category's spawns can
// change the list, so only theirs are looked up (the references reaching
// most chunks are mineshafts, which override nothing).
@@ -738,13 +742,12 @@ pub fn mobs_at<L: NaturalLevel>(
if let Some(o) = overrides.get(&s.id, category.name())
&& (if o.piece { s.in_piece } else { s.in_bounds })
{
return o.spawns.clone();
return &o.spawns;
}
}
l.biome_spawns(x, y, z)
.and_then(|b| b.get(category.name()))
.cloned()
.unwrap_or_default()
.map_or(&[], Vec::as_slice)
}
/// `WeightedList.getRandom`.
@@ -1103,7 +1106,7 @@ pub fn spawn_category_for_position<L: NaturalLevel, R: RandomSource>(
{
None
} else {
weighted_pick(&mobs_at(l, category, x, y, z), random)
weighted_pick(mobs_at(l, category, x, y, z), random)
};
let Some(entry) = list else {
break;
@@ -568,7 +568,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) {
let r = m.attrs.follow_range;
let area = m.bounds().inflate(Vec3::new(r, r, r));
let mut found: Vec<(Who, f64)> = Vec::new();
for o in w.others {
for o in w.others_near(area) {
if o.id != m.id && o.alive && o.bounds.intersects(area) {
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
}
@@ -898,8 +898,9 @@ fn poi_matches(m: &Mob, f: PoiFilter, p: Poi) -> bool {
_ => false,
}
}
/// Tickets taken on a POI: by this villager's memories and by others'.
fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize {
/// Tickets taken on a POI: by this villager's memories and by others'
/// (counted once per search by [`others_tickets`]).
fn tickets(m: &Mob, others: &crate::fast_hash::FxHashMap<[i32; 3], usize>, p: [i32; 3]) -> usize {
let mut n = 0;
if let Some(mm) = mem_ref(m) {
for s in [
@@ -913,16 +914,22 @@ fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize {
}
}
}
n + others.get(&p).copied().unwrap_or(0)
}
/// The tickets the other living villagers' POIs take, by POI.
fn others_tickets(m: &Mob, w: &MobWorld) -> crate::fast_hash::FxHashMap<[i32; 3], usize> {
let mut taken = crate::fast_hash::FxHashMap::default();
for o in w.others {
if o.id != m.id && o.alive && o.species == Species::Villager {
for q in [o.job, o.bed, o.potential_job, o.meeting] {
if q == Some(p) {
n += 1;
}
for q in [o.job, o.bed, o.potential_job, o.meeting]
.into_iter()
.flatten()
{
*taken.entry(q).or_insert(0) += 1;
}
}
}
n
taken
}
/// The POIs of chunk `(qx, qz)` from `y0` to `y1` (within the world), in
/// scan order: y, then z, then x. Only the indexed POI blocks of the sections
@@ -962,6 +969,8 @@ fn pois_in_range(
) -> Vec<(Poi, [i32; 3])> {
let c = block_of(m.position);
let mut found = Vec::new();
// Every candidate asks how taken it is: count the others' once.
let mut taken = None;
let r2 = i64::from(radius) * i64::from(radius);
let (cx, cz) = (c[0] >> 4, c[2] >> 4);
let chunks = radius.div_euclid(16) + 1;
@@ -974,7 +983,8 @@ fn pois_in_range(
|| (p[2] - c[2]).abs() > radius
|| dist_sqr(p, c) > r2
|| !poi_matches(m, f, poi)
|| tickets(m, w, p) >= poi.max_tickets()
|| tickets(m, taken.get_or_insert_with(|| others_tickets(m, w)), p)
>= poi.max_tickets()
{
return;
}
@@ -492,7 +492,7 @@ fn sense_entities(m: &mut Mob, w: &MobWorld) {
let r = m.attrs.follow_range;
let area = m.bounds().inflate(Vec3::new(r, r, r));
let mut found: Vec<(Who, f64)> = Vec::new();
for o in w.others {
for o in w.others_near(area) {
if o.id != m.id && o.alive && o.bounds.intersects(area) {
found.push((Who::Mob(o.id), m.distance_sqr(o.position)));
}
+15 -3
View File
@@ -226,7 +226,13 @@ impl MobWorld<'_> {
.chain(all.into_iter().flatten())
}
pub fn seen(&self, id: u32) -> Option<&Seen> {
self.others.iter().find(|s| s.id == id)
match self.others_index {
Some(index) => index
.get(&id)
.and_then(|&i| self.others.get(i as usize))
.filter(|s| s.id == id),
None => self.others.iter().find(|s| s.id == id),
}
}
/// Living mobs of the given species within `range` of `from`, nearest first.
pub fn nearby<'s>(
@@ -235,9 +241,15 @@ impl MobWorld<'_> {
range: f64,
pred: impl Fn(&Seen) -> bool + 's,
) -> impl Iterator<Item = &'s Seen> + 's {
// A position within `range` puts the box's bottom face in this area
// (one block wider, as the box test is strict).
let r = range + 1.0;
let area = Aabb::new(
Vec3::new(from.x - r, from.y - r, from.z - r),
Vec3::new(from.x + r, from.y + r, from.z + r),
);
let mut v: Vec<&Seen> = self
.others
.iter()
.others_near(area)
.filter(|s| {
s.alive
&& (s.position.x - from.x).abs() <= range
+81 -1
View File
@@ -247,6 +247,14 @@ pub struct PlayerMotion {
pub glide_ending: bool,
/// Glider durability to take this tick (updateFallFlying).
pub glider_wear: u32,
/// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's
/// spin. The damage stays until the game has dealt the hit.
pub auto_spin_attack_ticks: i32,
pub auto_spin_attack_dmg: f32,
/// The living entities the game put near a spinning player (id, box).
pub spin_targets: Vec<(u32, Aabb)>,
/// The entity the spin touched this tick (`doAutoAttackOnTouch`).
pub spin_hit: Option<u32>,
pub sprinting: bool,
pub sprint_input: crate::sprint::SprintState,
pub shift_key_down: bool,
@@ -262,6 +270,10 @@ pub struct PlayerMotion {
pub steps: MovementDistances,
pub needs_sync: bool,
pub sync_position: bool,
/// Moved by an ender pearl (`ServerPlayer.teleport`): a server sends the
/// position packet even when the player lands where they stood. The
/// server takes it at the end of a guest's turn.
pub teleported: bool,
pub events: Vec<MotionEvent>,
pub attributes: LiveAttributes<Box<dyn FnMut() -> i32>>,
pub impulse: ImpulseContext,
@@ -409,6 +421,10 @@ impl PlayerMotion {
fall_fly_ticks: 0,
glide_ending: false,
glider_wear: 0,
auto_spin_attack_ticks: 0,
auto_spin_attack_dmg: 0.0,
spin_targets: Vec::new(),
spin_hit: None,
sprinting: false,
sprint_input: crate::sprint::SprintState::default(),
shift_key_down: false,
@@ -428,6 +444,7 @@ impl PlayerMotion {
},
needs_sync: false,
sync_position: false,
teleported: false,
events: Vec::new(),
attributes,
fluids: PlayerFluids::default(),
@@ -699,7 +716,8 @@ impl MotionWorld<'_, '_, '_> {
supporting_block: self.player.ground.supporting_block,
}
}
fn climbable(&mut self) -> Result<bool> {
/// `LivingEntity.onClimbable` at the player's feet (it remembers the block).
pub fn climbable(&mut self) -> Result<bool> {
if self.player.spectator {
return Ok(false);
}
@@ -919,6 +937,7 @@ impl MotionWorld<'_, '_, '_> {
input.z = 0.0;
}
self.jump_phase()?;
let before_travel = self.player.bounds();
// Player.travel: swim steering, then LivingEntity.travel (fluids
// first, then gliding, then air), keeping 0.6 of the vertical speed
// while flying.
@@ -973,8 +992,26 @@ impl MotionWorld<'_, '_, '_> {
{
self.freeze_damage()?;
}
if self.player.auto_spin_attack_ticks > 0 {
self.player.auto_spin_attack_ticks -= 1;
self.check_auto_spin_attack(before_travel);
}
Ok(())
}
/// `LivingEntity.checkAutoSpinAttack`: the first living entity in the
/// box swept this tick takes the hit and ends the spin, bouncing the
/// player back at a fifth of its speed; a wall ends it too.
fn check_auto_spin_attack(&mut self, before: Aabb) {
let swept = before.union_bounds(self.player.bounds());
let p = &mut self.player;
if let Some(&(id, _)) = p.spin_targets.iter().find(|(_, b)| b.intersects(swept)) {
p.spin_hit = Some(id);
p.auto_spin_attack_ticks = 0;
p.velocity = p.velocity.scale(-0.2);
} else if p.collision.horizontal {
p.auto_spin_attack_ticks = 0;
}
}
/// `hurtServer(damageSources().freeze(), 1)` for a fully frozen player.
fn freeze_damage(&mut self) -> Result<()> {
let id = self
@@ -2659,6 +2696,49 @@ mod tests {
}
}
#[test]
fn a_riptide_spin_lies_flat_and_ends_on_the_first_entity_it_touches() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let render = assets.reload(&root).unwrap();
let binding = crate::collisions::load(&root, assets.registry).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
let mut scene = World::test_scene(&assets, &render, 2).unwrap();
let ahead = Aabb::new(Vec3::new(20.2, 9.0, 21.5), Vec3::new(20.8, 11.0, 22.1));
for target in [None, Some(ahead)] {
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 10.0, 20.5)).unwrap();
player.auto_spin_attack_ticks = 20;
player.auto_spin_attack_dmg = 8.0;
player.velocity = Vec3::new(0.0, 0.0, 1.0);
player.spin_targets = target.map(|b| (7, b)).into_iter().collect();
let mut w = MotionWorld {
entities: &[],
player: &mut player,
scene: &mut scene,
assets: &assets,
collision_binding: &binding,
resources: &resources,
};
w.simulation_tick([0.0, 0.0], false).unwrap();
if target.is_some() {
// Touched: the hit, no more spin, bounced back at a fifth.
assert_eq!(w.player.spin_hit, Some(7));
assert_eq!(w.player.auto_spin_attack_ticks, 0);
assert!(w.player.velocity.z < 0.0, "{:?}", w.player.velocity);
assert_eq!(w.player.pose, crate::pose::Pose::Standing);
} else {
assert_eq!(w.player.spin_hit, None);
assert_eq!(w.player.auto_spin_attack_ticks, 19);
assert_eq!(w.player.pose, crate::pose::Pose::SpinAttack);
assert_eq!(w.player.dimensions.height, 0.6);
}
}
}
#[test]
fn a_landing_glide_lasts_a_tick_so_a_jump_keeps_its_speed() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
+6 -2
View File
@@ -14,6 +14,7 @@ pub enum Pose {
Crouching,
Swimming,
FallFlying,
SpinAttack,
}
impl Pose {
pub fn name(self) -> &'static str {
@@ -22,13 +23,14 @@ impl Pose {
Self::Crouching => "CROUCHING",
Self::Swimming => "SWIMMING",
Self::FallFlying => "FALL_FLYING",
Self::SpinAttack => "SPIN_ATTACK",
}
}
pub fn dimensions(self, scale: f32) -> Dimensions {
let (height, eye_height) = match self {
Self::Standing => (1.8, 1.62),
Self::Crouching => (1.5, 1.27),
Self::Swimming | Self::FallFlying => (0.6, 0.4),
Self::Swimming | Self::FallFlying | Self::SpinAttack => (0.6, 0.4),
};
Dimensions {
width: 0.6 * scale,
@@ -98,11 +100,13 @@ impl MotionWorld<'_, '_, '_> {
if !self.can_fit_pose(Pose::Swimming)? {
return Ok(());
}
// Player.getDesiredPose: swimming before gliding.
// Player.getDesiredPose: swimming, gliding, Riptide's spin.
let desired = if self.player.swimming {
Pose::Swimming
} else if self.player.fall_flying {
Pose::FallFlying
} else if self.player.auto_spin_attack_ticks > 0 {
Pose::SpinAttack
} else if self.player.shift_key_down && !self.player.flying {
Pose::Crouching
} else {
+212 -2
View File
@@ -1305,8 +1305,73 @@ pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) {
};
layers[si as usize] = (layer("SkyLight"), layer("BlockLight"));
}
let above = [if sky_light { 15 } else { 0 }; 256];
crate::light::light_from_layers(chunk, &layers, above, sky_light);
// Uniform saved layers need no expanded allocation. Both nibbles of
// each byte must match, not merely the bytes across the layer.
let uniform_layer = |layer: &[u8]| {
let first = layer[0];
(first & 15 == first >> 4 && layer.iter().all(|&v| v == first)).then_some(first & 15)
};
let mut above = [if sky_light { 15 } else { 0 }; 256];
for (si, (sky, block)) in layers.into_iter().enumerate().rev() {
let sky = sky.filter(|_| sky_light);
let sky_uniform = sky.map_or_else(
|| above.iter().all(|&v| v == above[0]).then_some(above[0]),
uniform_layer,
);
let block_uniform = block.map_or(Some(0), uniform_layer);
let section = Arc::make_mut(&mut chunk.sections[si]);
if let (Some(s), Some(b)) = (sky_uniform, block_uniform) {
section.light = Light::Uniform(s << 4 | b);
above.fill(s);
} else {
let mut data = Box::new([0u8; 4096]);
match (sky, block) {
(Some(sky), Some(block)) => {
for ((pair, &s), &b) in
data.as_chunks_mut::<2>().0.iter_mut().zip(sky).zip(block)
{
pair[0] = s << 4 | (b & 15);
pair[1] = (s & 0xf0) | (b >> 4);
}
}
(Some(sky), None) => {
for (pair, &s) in data.as_chunks_mut::<2>().0.iter_mut().zip(sky) {
pair[0] = s << 4;
pair[1] = s & 0xf0;
}
}
(None, Some(block)) => {
for (i, (pair, &b)) in data
.as_chunks_mut::<2>()
.0
.iter_mut()
.zip(block)
.enumerate()
{
pair[0] = above[(i * 2) & 255] << 4 | (b & 15);
pair[1] = above[(i * 2 + 1) & 255] << 4 | (b >> 4);
}
}
(None, None) => {
for layer in data.as_chunks_mut::<256>().0 {
for (v, &s) in layer.iter_mut().zip(&above) {
*v = s << 4;
}
}
}
}
if let Some(sky) = sky {
for (pair, &s) in above.as_chunks_mut::<2>().0.iter_mut().zip(sky) {
pair[0] = s & 15;
pair[1] = s >> 4;
}
}
section.light = Light::Full(data);
}
section.compact();
}
chunk.lit = true;
chunk.light_loaded = true;
}
type RegionCache = Mutex<HashMap<(i32, i32), Option<Arc<Mutex<RegionFile>>>>>;
@@ -3896,6 +3961,151 @@ mod tests {
assert!(!unlit.lit && !unlit.light_loaded);
}
#[test]
fn saved_light_matches_reference_for_layers_and_metadata() {
fn reference(tag: &Tag, chunk: &mut Chunk, sky_light: bool) {
if tag.get("isLightOn") != Some(&Tag::Byte(1)) {
return;
}
let Some(Tag::List(sections)) = tag.get("sections") else {
return;
};
let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS];
for section in sections {
let Some(y) = number(section.get("Y")) else {
continue;
};
let si = y as i32 - (MIN_Y >> 4);
if !(0..SECTIONS as i32).contains(&si) {
continue;
}
let layer = |name: &str| match section.get(name) {
Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]),
_ => None,
};
layers[si as usize] = (layer("SkyLight"), layer("BlockLight"));
}
let above = [if sky_light { 15 } else { 0 }; 256];
crate::light::light_from_layers(chunk, &layers, above, sky_light);
}
let section = |y: Tag, sky: Option<Tag>, block: Option<Tag>| {
let mut entries = vec![("Y", y)];
if let Some(v) = sky {
entries.push(("SkyLight", v));
}
if let Some(v) = block {
entries.push(("BlockLight", v));
}
Tag::compound(entries)
};
let root = |sections| {
Tag::compound([
("isLightOn", Tag::Byte(1)),
("sections", Tag::List(sections)),
])
};
let check = |tag: &Tag| {
for sky_light in [false, true] {
let mut expected = Chunk::empty(-3, 5);
let s = Arc::make_mut(&mut expected.sections[0]);
s.light = Light::Full(Box::new([0xab; 4096]));
s.blocks.set(0, 1);
s.blocks.set(0, 0);
s.biomes.set(0, 1);
s.biomes.set(0, 0);
let mut actual = expected.clone();
reference(tag, &mut expected, sky_light);
load_light(tag, &mut actual, sky_light);
assert_eq!(
(actual.lit, actual.light_loaded),
(expected.lit, expected.light_loaded)
);
for (a, b) in actual.sections.iter().zip(&expected.sections) {
assert_eq!(
std::mem::discriminant(&a.light),
std::mem::discriminant(&b.light)
);
assert_eq!(
format!("{:?}", a.blocks.to_wire()),
format!("{:?}", b.blocks.to_wire())
);
assert_eq!(
format!("{:?}", a.biomes.to_wire()),
format!("{:?}", b.biomes.to_wire())
);
for i in 0..4096 {
assert_eq!(a.light(i), b.light(i), "index {i}, sky {sky_light}");
}
}
}
};
for tag in [
Tag::compound(Vec::<(&str, Tag)>::new()),
Tag::compound([("isLightOn", Tag::Byte(0))]),
Tag::compound([("isLightOn", Tag::Byte(2))]),
Tag::compound([("isLightOn", Tag::Int(1)), ("sections", Tag::List(vec![]))]),
Tag::compound([("isLightOn", Tag::Byte(1)), ("sections", Tag::Int(0))]),
root(vec![]),
] {
check(&tag);
}
// Cover every repeated byte, including 0xF0/0x0F: a uniform byte
// array need not hold uniform nibbles.
for byte in 0..=255u8 {
check(&root(vec![section(
Tag::Byte(19),
Some(Tag::ByteArray(vec![byte; 2048])),
Some(Tag::ByteArray(vec![255 - byte; 2048])),
)]));
}
// Every pair of uniform sky/block nibble values, with missing
// sections below inheriting the stored bottom row.
for sky in 0..16u8 {
for block in 0..16u8 {
check(&root(vec![section(
Tag::Byte(1),
Some(Tag::ByteArray(vec![sky * 17; 2048])),
Some(Tag::ByteArray(vec![block * 17; 2048])),
)]));
}
}
for length in [0, 1, 2047, 2048, 2049] {
for invalid in [
Tag::Int(1),
Tag::List(vec![]),
Tag::ByteArray(vec![0xf0; length]),
] {
check(&root(vec![section(
Tag::Byte(-4),
Some(invalid.clone()),
Some(invalid),
)]));
}
}
let varied: Vec<u8> = (0..2048)
.map(|i| (i as u8).wrapping_mul(73).wrapping_add(31))
.collect();
check(&root(vec![
section(Tag::Byte(-5), Some(Tag::ByteArray(varied.clone())), None),
section(Tag::Byte(20), Some(Tag::ByteArray(varied.clone())), None),
section(
Tag::String("19".into()),
Some(Tag::ByteArray(varied.clone())),
None,
),
section(Tag::Byte(19), Some(Tag::ByteArray(varied.clone())), None),
section(Tag::Byte(17), None, Some(Tag::ByteArray(varied.clone()))),
section(Tag::Byte(-4), Some(Tag::ByteArray(varied.clone())), None),
// Last duplicate wins, even when its arrays have wrong types.
section(
Tag::Byte(-4),
Some(Tag::Int(15)),
Some(Tag::ByteArray(vec![7; 2047])),
),
section(Tag::Byte(0), None, Some(Tag::ByteArray(varied))),
]));
}
#[test]
fn level_round_trips_through_the_vanilla_files() {
let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
+33
View File
@@ -112,6 +112,24 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture
out
}
/// The skin URL of a `minecraft:profile` component's property list. Player
/// heads and mannequins read their profile this way, and `SkinManager` lets
/// those textures be unsigned (`getInsecureSkinInformation`).
pub fn profile_skin_url(profile: &serde_json::Value) -> Option<String> {
let value = profile
.get("properties")?
.as_array()?
.iter()
.find_map(|p| {
if p.get("name")?.as_str()? == "textures" {
p.get("value")?.as_str()
} else {
None
}
})?;
unpack(value, Signature::Unsigned, &TEXTURE_URIS).skin
}
/// `MinecraftProfileTexture.getHash`: the base name of the URL's path.
pub fn texture_hash(url: &str) -> Option<String> {
let rest = url.split_once("://")?.1;
@@ -393,6 +411,21 @@ pub fn sha1(data: &[u8]) -> [u8; 20] {
#[cfg(test)]
mod tests {
#[test]
fn profile_components_supply_unsigned_head_skins() {
let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0=";
let profile = serde_json::json!({"properties": [{"name": "textures", "value": value}]});
assert_eq!(
super::profile_skin_url(&profile).as_deref(),
Some("https://textures.minecraft.net/texture/abc123")
);
let other = serde_json::json!({"properties": [{"name": "other", "value": value}]});
assert_eq!(super::profile_skin_url(&other), None);
let bad = serde_json::json!({"properties": [{"name": "textures", "value": "not base64"}]});
assert_eq!(super::profile_skin_url(&bad), None);
assert_eq!(super::profile_skin_url(&serde_json::json!({})), None);
}
/// Textures come over plain HTTP too (a local server here; https is the
/// same request through rustls), and only 2xx answers count.
#[test]
+88 -12
View File
@@ -1,8 +1,10 @@
//! Named timings within a frame, for finding what makes a frame slow:
//! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time
//! exceeds MS milliseconds, and of every server tick (dedicated or
//! integrated) longer than MS. Costs one clock read per span when enabled
//! and a relaxed load otherwise.
//! integrated) longer than MS. Each span keeps its wall time and the
//! thread's CPU time inside it, so a span that waited (for a lock, the GPU
//! or a core on a busy machine) shows apart from one that worked. Costs two
//! clock reads per span when enabled and a relaxed load otherwise.
use std::{
cell::RefCell,
sync::atomic::{AtomicBool, Ordering},
@@ -11,7 +13,15 @@ use std::{
static ENABLED: AtomicBool = AtomicBool::new(false);
thread_local! {
static SPANS: RefCell<Vec<(&'static str, f32)>> = const { RefCell::new(Vec::new()) };
static SPANS: RefCell<Vec<Span>> = const { RefCell::new(Vec::new()) };
}
/// A named timing: wall milliseconds and the thread's CPU milliseconds in it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Span {
pub name: &'static str,
pub ms: f32,
pub cpu_ms: f32,
}
pub fn enable(on: bool) {
@@ -23,10 +33,13 @@ pub fn time<T>(name: &'static str, f: impl FnOnce() -> T) -> T {
if !ENABLED.load(Ordering::Relaxed) {
return f();
}
let started = Instant::now();
let (started, cpu) = (Instant::now(), thread_cpu());
let out = f();
let ms = started.elapsed().as_secs_f32() * 1000.0;
SPANS.with(|s| s.borrow_mut().push((name, ms)));
let cpu_ms = thread_cpu()
.zip(cpu)
.map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0);
SPANS.with(|s| s.borrow_mut().push(Span { name, ms, cpu_ms }));
out
}
/// The CPU time this thread has used, where the platform tells it: a tick
@@ -42,21 +55,84 @@ pub fn thread_cpu() -> Option<Duration> {
None
}
/// The frame's spans, summed by name, slowest first; clears them.
pub fn take() -> Vec<(&'static str, f32)> {
pub fn take() -> Vec<Span> {
let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut()));
let mut sums: Vec<(&'static str, f32)> = Vec::new();
for (name, ms) in spans {
match sums.iter_mut().find(|(n, _)| *n == name) {
Some(entry) => entry.1 += ms,
None => sums.push((name, ms)),
let mut sums: Vec<Span> = Vec::new();
for span in spans {
match sums.iter_mut().find(|s| s.name == span.name) {
Some(sum) => {
sum.ms += span.ms;
sum.cpu_ms += span.cpu_ms;
}
None => sums.push(span),
}
}
sums.sort_by(|a, b| b.1.total_cmp(&a.1));
sums.sort_by(|a, b| b.ms.total_cmp(&a.ms));
sums
}
/// `name wall` for spans of at least 0.5 ms, with `/cpu` when the thread
/// worked for less than nine tenths of it: the slow-frame and slow-tick lines.
pub fn describe(spans: &[Span]) -> String {
let list: Vec<String> = spans
.iter()
.filter(|s| s.ms >= 0.5)
.map(|s| {
if s.cpu_ms < s.ms * 0.9 {
format!("{} {:.1}/{:.1}", s.name, s.ms, s.cpu_ms)
} else {
format!("{} {:.1}", s.name, s.ms)
}
})
.collect();
list.join(", ")
}
#[cfg(test)]
mod tests {
use super::Span;
/// Spans of one name add up; a span the thread spent mostly waiting
/// shows its CPU time after the wall time, short ones are left out.
#[test]
fn spans_sum_by_name_and_show_waits() {
super::SPANS.with(|s| {
s.borrow_mut().extend([
Span {
name: "tick",
ms: 2.0,
cpu_ms: 2.0,
},
Span {
name: "submit",
ms: 30.0,
cpu_ms: 0.2,
},
Span {
name: "tick",
ms: 3.0,
cpu_ms: 2.9,
},
Span {
name: "hud",
ms: 0.3,
cpu_ms: 0.3,
},
]);
});
let spans = super::take();
assert_eq!(
spans[0],
Span {
name: "submit",
ms: 30.0,
cpu_ms: 0.2
}
);
assert_eq!((spans[1].name, spans[1].ms), ("tick", 5.0));
assert_eq!(super::describe(&spans), "submit 30.0/0.2, tick 5.0");
assert!(super::take().is_empty());
}
/// The thread's CPU clock moves with work done on it, not with time
/// spent asleep.
#[cfg(unix)]
+22 -7
View File
@@ -198,8 +198,10 @@ pub fn anvil_result(
let mut repair_item_count_cost = 0;
let mut naming_cost = 0;
if let Some(addition) = addition {
// addition.has(STORED_ENCHANTMENTS): only enchanted books carry that component.
let using_book = &*addition.item == "minecraft:enchanted_book";
// addition.has(STORED_ENCHANTMENTS): an enchanted book (its default
// component), or any item given stored enchantments.
let using_book = &*addition.item == "minecraft:enchanted_book"
|| !addition.stored_enchantments().is_empty();
if is_damageable(items, &result) && is_valid_repair_item(e, items, input, addition) {
let max = max_damage(items, &result);
let mut repair = (result.damage as i32).min(max / 4);
@@ -401,13 +403,13 @@ pub fn grindstone_result(
(None, None) => None,
}
}
/// Experience from the grindstone result slot's `getExperienceAmount`.
pub fn grindstone_experience(
/// The grindstone result slot's `getExperienceAmount` before its roll: the
/// minimum costs of the inputs' non-curse enchantments.
pub fn grindstone_xp_base(
e: &Enchantments,
random: &mut LegacyRandom,
input: Option<&ItemStack>,
additional: Option<&ItemStack>,
) -> u32 {
) -> i32 {
let from = |s: Option<&ItemStack>| -> i32 {
s.map_or(0, |s| {
s.crafting_enchantments()
@@ -417,7 +419,10 @@ pub fn grindstone_experience(
.sum()
})
};
let amount = from(input) + from(additional);
from(input) + from(additional)
}
/// `getExperienceAmount`'s roll of the sum: `half + nextInt(half)`.
pub fn grindstone_xp_roll(amount: i32, random: &mut LegacyRandom) -> u32 {
if amount > 0 {
let half = (f64::from(amount) / 2.0).ceil() as i32;
(half + random.next_int_bound(half).unwrap_or(0)) as u32
@@ -425,6 +430,15 @@ pub fn grindstone_experience(
0
}
}
/// Experience from the grindstone result slot's `getExperienceAmount`.
pub fn grindstone_experience(
e: &Enchantments,
random: &mut LegacyRandom,
input: Option<&ItemStack>,
additional: Option<&ItemStack>,
) -> u32 {
grindstone_xp_roll(grindstone_xp_base(e, input, additional), random)
}
// ---------------------------------------------------------------- smithing & stonecutting
@@ -450,6 +464,7 @@ pub struct Stonecutting {
pub input: Ingredient,
pub result: ItemStack,
}
#[derive(Default)]
pub struct StationRecipes {
pub smithing: Vec<Smithing>,
/// Sorted by recipe id, the registry order vanilla lists them in.
+239 -1
View File
@@ -276,6 +276,8 @@ pub struct Streaming {
/// chunks finish out to `radius + 1` (Chebyshev) and generation reaches
/// past that as around the player. They are generated and kept but not meshed.
pub extra: Vec<((i32, i32), i32)>,
/// `extra`'s squares as a grid, made again when `extra` changes.
cover: Option<ExtraCover>,
/// Mesh the sections for drawing (false on a server thread).
pub mesh: bool,
}
@@ -391,6 +393,7 @@ impl GenerationScan {
radius: input.ranges.radius,
extra: input.ranges.extra,
forced: input.ranges.forced,
cover: input.ranges.cover,
};
self.remember(ranges, input.world);
} else {
@@ -436,7 +439,7 @@ impl Streaming {
thread::Builder::new()
.name(format!("horizon-worker-{i}"))
.spawn(move || {
// A dedicated server's tick comes first (horizon_threads).
// Ticks and frames come first (horizon_threads).
horizon_threads::behind_server();
let mut worker = generator.worker();
// The face visibility table and its occlusion cache stay with
@@ -562,6 +565,7 @@ impl Streaming {
meshed_total: 0,
remote: false,
extra: Vec::new(),
cover: None,
mesh: true,
}
}
@@ -808,6 +812,7 @@ impl Streaming {
if self.paused {
return (uploads, Vec::new());
}
ExtraCover::refresh(&mut self.cover, &self.extra);
self.relight_edits(world);
let deferred = std::mem::take(&mut self.deferred);
let received = std::iter::from_fn(|| self.results.try_recv().ok());
@@ -982,6 +987,7 @@ impl Streaming {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: ExtraCover::matching(&self.cover, &self.extra),
};
let (protos, generating) = (&self.protos, &self.generating);
self.decoration_order.retain(|x, z| {
@@ -1109,6 +1115,7 @@ impl Streaming {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: ExtraCover::matching(&self.cover, &self.extra),
};
self.waiting.retain(|&(x, sy, z)| {
let back = ranges.in_view(x, z);
@@ -1185,6 +1192,7 @@ impl Streaming {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: ExtraCover::matching(&self.cover, &self.extra),
},
world,
generating: &self.generating,
@@ -1280,6 +1288,7 @@ impl Streaming {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: ExtraCover::matching(&self.cover, &self.extra),
}
}
fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool {
@@ -1365,6 +1374,100 @@ struct Ranges<'a> {
radius: i32,
extra: &'a [((i32, i32), i32)],
forced: &'a HashSet<(i32, i32)>,
/// `extra` as a grid, when one was made for it: `in_extra` without a
/// scan of every area.
cover: Option<&'a ExtraCover>,
}
/// For every column near the extra areas, how far it lies outside the
/// nearest one's square (Chebyshev distance less its radius; 0 inside). A server has an area per player, and streaming asks of every
/// loaded and wanted column whether one reaches it, several times a tick:
/// with fifty players, a scan of fifty squares per question.
struct ExtraCover {
extra: Vec<((i32, i32), i32)>,
x0: i32,
z0: i32,
width: u32,
depth: u32,
cells: Box<[i8]>,
}
impl ExtraCover {
/// The largest margin the grid answers for; beyond it (and outside the
/// grid) a column is further than that from every square.
const REACH: i32 = 4;
/// The largest grid, in columns (a mebibyte).
const CELLS: u64 = 1 << 20;
fn matching<'a>(
cover: &'a Option<ExtraCover>,
extra: &[((i32, i32), i32)],
) -> Option<&'a ExtraCover> {
cover.as_ref().filter(|c| c.extra == extra)
}
/// Make the grid again if `extra` changed; none for one area or none
/// (a scan is as quick), or areas too far apart.
fn refresh(cover: &mut Option<ExtraCover>, extra: &[((i32, i32), i32)]) {
if cover.as_ref().is_some_and(|c| c.extra == extra) {
return;
}
*cover = Self::new(extra);
}
fn new(extra: &[((i32, i32), i32)]) -> Option<Self> {
if extra.len() < 2 || extra.iter().any(|&(_, r)| !(0..=64).contains(&r)) {
return None;
}
let k = i64::from(Self::REACH);
let (mut x0, mut z0, mut x1, mut z1) = (i64::MAX, i64::MAX, i64::MIN, i64::MIN);
for &((x, z), r) in extra {
let (x, z, r) = (i64::from(x), i64::from(z), i64::from(r) + k);
(x0, z0, x1, z1) = (x0.min(x - r), z0.min(z - r), x1.max(x + r), z1.max(z + r));
}
let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64);
let fits = |lo: i64, hi: i64| lo >= i64::from(i32::MIN) && hi <= i64::from(i32::MAX);
if width * depth > Self::CELLS || !fits(x0, x1) || !fits(z0, z1) {
return None;
}
let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32);
let mut cells = vec![(Self::REACH + 1) as i8; (width * depth) as usize].into_boxed_slice();
// Inside a square counts as 0: no margin asked for is below it. Each
// row of a square is a run of one value with a slope at either end.
let lower = |run: &mut [i8], v: i8| run.iter_mut().for_each(|c| *c = (*c).min(v));
for &((cx, cz), r) in extra {
let reach = r + Self::REACH;
for dz in -reach..=reach {
let start = (cz + dz - z0) as usize * width as usize + (cx - x0) as usize;
let row = &mut cells[start - reach as usize..=start + reach as usize];
let flat = dz.abs().max(r);
let centre = reach as usize;
lower(
&mut row[centre - flat as usize..=centre + flat as usize],
(flat - r) as i8,
);
for d in flat + 1..=reach {
let v = (d - r) as i8;
lower(&mut row[centre - d as usize..=centre - d as usize], v);
lower(&mut row[centre + d as usize..=centre + d as usize], v);
}
}
}
Some(Self {
extra: extra.to_vec(),
x0,
z0,
width,
depth,
cells,
})
}
/// Whether (x, z) is within `margin` of an area's square, for a
/// `margin` up to `REACH`.
fn within(&self, x: i32, z: i32, margin: i32) -> bool {
let (dx, dz) = (
x.wrapping_sub(self.x0) as u32,
z.wrapping_sub(self.z0) as u32,
);
dx < self.width
&& dz < self.depth
&& i32::from(self.cells[(dz * self.width + dx) as usize]) <= margin
}
}
impl Ranges<'_> {
/// `distance`, or `rings` while the level loading screen is up.
@@ -1441,6 +1544,11 @@ impl Ranges<'_> {
/// Within `margin` of an extra area's square (Chebyshev distance, as
/// vanilla's ticket levels spread).
fn in_extra(&self, x: i32, z: i32, margin: i32) -> bool {
if let Some(cover) = self.cover
&& (0..=ExtraCover::REACH).contains(&margin)
{
return cover.within(x, z, margin);
}
self.extra
.iter()
.any(|&(c, radius)| (x - c.0).abs().max((z - c.1).abs()) <= radius + margin)
@@ -1554,6 +1662,7 @@ mod tests {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: None,
},
world: &self.world,
generating: &self.generating,
@@ -1866,6 +1975,7 @@ mod tests {
radius,
extra: &[],
forced: &forced,
cover: None,
};
let square = |x: i32, z: i32, n: i32| {
(-n..=n).flat_map(move |dz| (-n..=n).map(move |dx| (x + dx, z + dz)))
@@ -1920,6 +2030,7 @@ mod tests {
radius: 12,
extra: &[],
forced: &forced,
cover: None,
};
let at = |dx: i32, dz: i32| (2 + dx, -1 + dz);
let key = |(x, z): (i32, i32), loading| r.priority(x, z, loading);
@@ -1945,6 +2056,7 @@ mod tests {
radius,
extra: &[((radius * 2 + 9, 3), 4)],
forced: &forced,
cover: None,
};
let span = radius * 3 + 20;
for x in -span..=span {
@@ -1984,6 +2096,7 @@ mod tests {
radius: 2,
extra: &extra,
forced: &forced,
cover: None,
};
let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0);
for x in 40 - view - 8..=40 + view + 8 {
@@ -2021,3 +2134,128 @@ mod tests {
}
}
}
#[cfg(test)]
mod cover_tests {
use super::*;
fn areas(seed: &mut u64, n: usize, spread: i32) -> Vec<((i32, i32), i32)> {
let mut next = |m: i32| {
*seed ^= *seed << 13;
*seed ^= *seed >> 7;
*seed ^= *seed << 17;
(*seed % (2 * m as u64 + 1)) as i32 - m
};
(0..n)
.map(|_| ((next(spread), next(spread)), 2 + next(14).abs()))
.collect()
}
/// Every question streaming asks gets the same answer with the grid.
#[test]
fn the_grid_answers_as_the_scan() {
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let forced: HashSet<(i32, i32)> = [(40, -40)].into();
for case in 0..60 {
let extra = areas(&mut seed, 2 + case % 20, [4, 30, 120][case % 3]);
let cover = ExtraCover::new(&extra).expect("a grid");
let ranges = |cover| Ranges {
center: (3, -2),
radius: 10,
extra: &extra,
forced: &forced,
cover,
};
let (scan, grid) = (ranges(None), ranges(Some(&cover)));
let span = [4, 30, 120][case % 3] + 40;
for z in -span..=span {
for x in -span..=span {
for m in 0..=ExtraCover::REACH + 2 {
assert_eq!(
scan.in_extra(x, z, m),
grid.in_extra(x, z, m),
"case {case} ({x}, {z}) {m}"
);
}
for d in [false, true] {
assert_eq!(scan.unloaded(x, z, d), grid.unloaded(x, z, d));
assert_eq!(scan.requested(x, z, d), grid.requested(x, z, d));
assert_eq!(scan.chunk_kept(x, z, d), grid.chunk_kept(x, z, d));
}
}
}
}
}
#[test]
fn a_stale_or_impossible_grid_is_not_used() {
let mut cover = None;
ExtraCover::refresh(&mut cover, &[((0, 0), 11), ((5, 5), 11)]);
assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 5), 11)]).is_some());
assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 6), 11)]).is_none());
// Too far apart for a mebibyte of grid, and one area alone: scans.
assert!(ExtraCover::new(&[((0, 0), 11), ((100_000, 0), 11)]).is_none());
assert!(ExtraCover::new(&[((0, 0), 11)]).is_none());
assert!(ExtraCover::new(&[((i32::MAX - 1, 0), 11), ((i32::MAX - 3, 0), 11)]).is_none());
assert!(ExtraCover::new(&[((0, i32::MAX - 1), 11), ((0, i32::MAX - 3), 11)]).is_none());
assert!(ExtraCover::new(&[((0, i32::MIN + 1), 11), ((0, i32::MIN + 3), 11)]).is_none());
}
/// cargo test --release -p horizon-client --lib cover_tests::cover_cost -- --ignored --nocapture
#[test]
#[ignore]
fn cover_cost() {
let forced = HashSet::new();
for players in [10usize, 25, 50] {
// The benchmark's bots: most near spawn, a fifth flying outwards.
let extra: Vec<_> = (0..players)
.map(|i| {
let a = i as f64 * 2.399;
let d = if i % 5 == 0 { 30.0 } else { 3.0 };
(((a.cos() * d) as i32, (a.sin() * d) as i32), 11)
})
.collect();
let cover = ExtraCover::new(&extra).unwrap();
let ranges = |cover| Ranges {
center: (0, 0),
radius: 10,
extra: &extra,
forced: &forced,
cover,
};
// The columns streaming asks about: everything kept, and the
// generation scan's ring past it.
let columns: Vec<(i32, i32)> = (-60..=60)
.flat_map(|z| (-60..=60).map(move |x| (x, z)))
.filter(|&(x, z)| {
ranges(None).requested(x, z, true) || !ranges(None).unloaded(x, z, true)
})
.collect();
let rounds = 100;
let time = |r: &Ranges| {
let t = std::time::Instant::now();
let mut n = 0usize;
for _ in 0..rounds {
for &(x, z) in &columns {
n += usize::from(r.unloaded(x, z, true));
n += usize::from(r.requested(x, z, true));
n += usize::from(r.in_range(x, z, 1));
}
}
std::hint::black_box(n);
t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds)
};
let t = std::time::Instant::now();
for _ in 0..rounds {
std::hint::black_box(ExtraCover::new(std::hint::black_box(&extra)));
}
let build = t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds);
println!(
"{players} players, {} columns, 3 questions each: scan {:.3} ms, grid {:.3} ms (+ {build:.3} ms to build)",
columns.len(),
time(&ranges(None)),
time(&ranges(Some(&cover))),
);
}
}
}

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