Merge origin/main into feat/wide-block-states

The LAN chunk encoder's section cache (#623) and dimension range (#668)
are kept; a cached section's wire bytes use the registry's palette width,
set once per process before any encoder exists, so the cache stays keyed
on the section alone. The sculk scan's palette check takes the u32 state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 15:02:53 +02:00
104 changed files with 9403 additions and 859 deletions
+1
View File
@@ -28,5 +28,6 @@
/horizon-player.txt
/servers.dat
/screenshots/
/.horizon-cache/
/crash-reports/
/debug/
Generated
+4
View File
@@ -1573,6 +1573,7 @@ dependencies = [
"horizon-protocol",
"horizon-world",
"log",
"ureq",
]
[[package]]
@@ -1608,7 +1609,10 @@ dependencies = [
"horizon-core",
"libm",
"lz4_flex",
"postcard",
"serde",
"serde_json",
"sha2",
"xxhash-rust",
]
@@ -1,7 +1,10 @@
#![forbid(unsafe_code)]
//! Loads and saves option files like `Options.load`/`save`, for the
//! differential harness (tools/test_options_parity.py).
use horizon_client::{Result, keybinds, options_file::OptionsFile};
use horizon_client::{
Result, keybinds,
options_file::{OptionsFile, V},
};
use std::{fs, io::Write};
fn main() -> Result<()> {
@@ -14,11 +17,16 @@ fn main() -> Result<()> {
let mut first = true;
for path in names {
let name = path.file_name().unwrap().to_string_lossy().into_owned();
let file = if name == "absent.txt" {
let mut file = if name == "absent.txt" {
OptionsFile::default()
} else {
OptionsFile::parse(&String::from_utf8_lossy(&fs::read(&path)?))
};
// Horizon extends the slider to 64; vanilla rejects 33..64 to its default.
// Compare that deliberate extension as vanilla would serialize it.
if file.int("renderDistance") > 32 {
file.set("renderDistance", V::Int(12));
}
write!(out, "== {name}\n{}", file.serialize())?;
if first {
first = false;
+58
View File
@@ -175,6 +175,53 @@ fn parse(id: &str, v: &Value) -> Option<Advancement> {
})
}
/// `CriterionProgress`'s date as saved, "yyyy-MM-dd HH:mm:ss Z", in UTC.
pub fn date_text(unix_secs: i64) -> String {
let days = unix_secs.div_euclid(86400);
let rem = unix_secs.rem_euclid(86400);
// Civil from days (Howard Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!(
"{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +0000",
rem / 3600,
rem % 3600 / 60,
rem % 60
)
}
/// A saved date back to milliseconds since the epoch (the network form of
/// `CriterionProgress`), the zone offset applied.
pub fn date_millis(text: &str) -> Option<i64> {
let (date, rest) = text.trim().split_once(' ')?;
let (time, zone) = rest.split_once(' ').unwrap_or((rest, "+0000"));
let mut d = date.split('-').map(|v| v.parse::<i64>().ok());
let (y, m, day) = (d.next()??, d.next()??, d.next()??);
let mut t = time.split(':').map(|v| v.parse::<i64>().ok());
let (h, min, sec) = (t.next()??, t.next()??, t.next()??);
let sign = if zone.starts_with('-') { -1 } else { 1 };
let zone = zone.trim_start_matches(['+', '-']);
let offset =
zone.get(0..2)?.parse::<i64>().ok()? * 3600 + zone.get(2..4)?.parse::<i64>().ok()? * 60;
// Days from civil (Howard Hinnant's algorithm).
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (m + 9) % 12;
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
Some((days * 86400 + h * 3600 + min * 60 + sec - sign * offset) * 1000)
}
/// The player's progress: advancement -> criterion -> obtained date.
#[derive(Default, Clone)]
pub struct Progress {
@@ -1059,4 +1106,15 @@ mod tests {
assert_eq!(l[4], Some((1, 2.0)));
assert_eq!(l[1], Some((2, 2.0)));
}
#[test]
fn saved_dates_read_back_to_their_instant() {
for secs in [0, 951_782_400, 1_792_216_800, 4_107_542_399] {
assert_eq!(date_millis(&date_text(secs)), Some(secs * 1000));
}
assert_eq!(
date_millis("2026-10-17 07:30:00 +0200"),
date_millis("2026-10-17 05:30:00 +0000")
);
assert_eq!(date_millis("not a date"), None);
}
}
+52 -2
View File
@@ -44,6 +44,7 @@ struct Mixer {
channels: HashMap<ChannelId, Channel>,
listener: [f64; 3],
listener_yaw: f32,
limiter_peak: f32,
}
/// A sound the player could have heard (`SoundEventListener.onPlaySound`):
/// what the subtitle overlay needs.
@@ -397,8 +398,17 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
c.position += step;
}
}
for s in data.iter_mut() {
*s = s.clamp(-1.0, 1.0);
// Limit the whole buffer together, preserving waveform and stereo balance
// instead of flattening each overloaded sample; release over 50 ms.
let peak = data.iter().fold(1.0f32, |peak, s| peak.max(s.abs()));
mixer.limiter_peak = mixer.limiter_peak.max(peak);
let release = (-1.0 / (0.05 * rate as f32)).exp();
for frame in data.chunks_mut(channels) {
let gain = mixer.limiter_peak.recip();
for s in frame {
*s *= gain;
}
mixer.limiter_peak = (mixer.limiter_peak * release).max(peak);
}
}
/// Why the game should not open an output, if it should not:
@@ -862,6 +872,46 @@ mod tests {
assert_eq!(distance_gain(Some(16.0), 40.0), 0.0);
}
#[test]
fn overlapping_voices_are_limited_without_flattening_or_changing_stereo_balance() {
let mut m = Mixer::default();
let wave = vec![0.25, 0.5, 0.75, 1.0, -1.0, -0.75, -0.5, -0.25, 0.0];
for id in 1..=4 {
m.channels
.insert(id, channel(wave.clone(), None, [-1.0, 0.0, 0.0], false));
}
let mut data = [0.0; 16];
mix(&mut m, &mut data, 2, 48_000);
for (frame, sample) in data.as_chunks::<2>().0.iter().zip(wave) {
assert!((frame[0] - sample * 0.4).abs() < 1e-6, "{frame:?}");
assert!((frame[1] - sample).abs() < 1e-6, "{frame:?}");
}
assert!(data.iter().all(|s| s.abs() <= 1.0));
}
#[test]
fn limiter_leaves_quiet_audio_alone_and_recovers_across_callbacks() {
let mut m = Mixer::default();
m.channels
.insert(1, channel(vec![0.25; 2], None, [0.0; 3], true));
let mut data = [0.0; 16];
mix(&mut m, &mut data, 2, 48_000);
assert_eq!(data, [0.25; 16]);
for id in 2..=5 {
m.channels
.insert(id, channel(vec![1.0; 2], None, [0.0; 3], true));
}
mix(&mut m, &mut data, 2, 48_000);
assert!(data.iter().all(|s| s.abs() <= 1.0));
m.channels.retain(|&id, _| id == 1);
let mut recovery = vec![0.0; 2 * 48_000];
mix(&mut m, &mut recovery, 2, 48_000);
assert!(recovery[0] > 0.0 && recovery[0] < 0.1);
assert!(recovery.windows(2).all(|w| w[1] >= w[0]));
assert_eq!(*recovery.last().unwrap(), 0.25);
}
#[test]
fn sources_play_attenuated_then_stop_or_loop() {
let mut m = Mixer::default();
+95
View File
@@ -232,6 +232,87 @@ pub fn join_server(session: &AuthSession, server_hash: &str) -> Result<(), JoinE
}
}
/// What the session service says about a player joining this server
/// (MinecraftServicesSessionService.hasJoinedServer).
#[derive(Clone, Debug, PartialEq)]
pub struct JoinedProfile {
pub uuid: u128,
pub properties: Vec<horizon_protocol::packets::login::Property>,
}
/// HttpDiscoveryService.buildQuery: `URLEncoder.encode(value, UTF-8)`.
fn url_encode(text: &str) -> String {
let mut out = String::new();
for b in text.bytes() {
match b {
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'-' | b'*' | b'_' => {
out.push(char::from(b));
}
b' ' => out.push('+'),
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
/// The session service's verify endpoint, asked by an online-mode server
/// whether `name` joined with `server_hash` (and from `ip`, when the server
/// prevents proxy connections). `Ok(None)`: it didn't, or the service said
/// no; `Err(Unavailable)`: no answer.
pub fn has_joined(
name: &str,
server_hash: &str,
ip: Option<std::net::IpAddr>,
) -> Result<Option<JoinedProfile>, JoinError> {
let doc = discovery()?;
let url = endpoint(&doc, "session", "verify").ok_or(JoinError::Unavailable)?;
let mut query = format!(
"username={}&serverId={}",
url_encode(name),
url_encode(server_hash)
);
if let Some(ip) = ip {
query.push_str(&format!("&ip={}", url_encode(&ip.to_string())));
}
let separator = if url.contains('?') { '&' } else { '?' };
let body = match agent().get(&format!("{url}{separator}{query}")).call() {
Ok(response) => response.into_string().unwrap_or_default(),
Err(ureq::Error::Status(status, response)) => {
let error =
JoinError::from_response(status, &response.into_string().unwrap_or_default());
return match error {
JoinError::Unavailable => Err(error),
_ => Ok(None),
};
}
Err(ureq::Error::Transport(_)) => return Err(JoinError::Unavailable),
};
Ok(parse_joined(&body))
}
/// HasJoinedMinecraftServerResponse: `id` and `properties`; no id is no profile.
pub fn parse_joined(body: &str) -> Option<JoinedProfile> {
let v: serde_json::Value = serde_json::from_str(body).ok()?;
let uuid = parse_uuid(v.get("id")?.as_str()?)?;
let properties = v
.get("properties")
.and_then(|p| p.as_array())
.into_iter()
.flatten()
.filter_map(|p| {
Some(horizon_protocol::packets::login::Property {
name: p.get("name")?.as_str()?.to_owned(),
value: p.get("value")?.as_str()?.to_owned(),
signature: p
.get("signature")
.and_then(|s| s.as_str())
.map(str::to_owned),
})
})
.collect();
Some(JoinedProfile { uuid, properties })
}
#[cfg(test)]
mod tests {
use super::*;
@@ -250,6 +331,20 @@ mod tests {
path
}
#[test]
fn verify_answers() {
assert_eq!(url_encode("Tester_1"), "Tester_1");
assert_eq!(url_encode("-5a f"), "-5a+f");
assert_eq!(url_encode("::1"), "%3A%3A1");
let body = r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch","properties":[{"name":"textures","value":"e30=","signature":"c2ln"}]}"#;
let p = parse_joined(body).unwrap();
assert_eq!(p.uuid, UUID);
assert_eq!(p.properties.len(), 1);
assert_eq!(p.properties[0].signature.as_deref(), Some("c2ln"));
assert_eq!(parse_joined(""), None);
assert_eq!(parse_joined(r#"{"name":"Notch"}"#), None);
}
#[test]
fn session_files_are_read_once_and_must_be_private() {
let dir = std::env::temp_dir().join(format!("horizon-auth-test-{}", std::process::id()));
+39 -1
View File
@@ -298,6 +298,9 @@ pub struct FixedStep {
tick_times: [i64; SAMPLES],
aggregated: i64,
tick_count: i64,
/// A server's client: its level's tick rate only slows the timer down
/// (`Minecraft.getTickTargetMillis`), since the server runs the ticks.
client: bool,
}
impl Default for FixedStep {
@@ -312,11 +315,20 @@ impl Default for FixedStep {
tick_times: [0; SAMPLES],
aggregated: 0,
tick_count: 0,
client: false,
}
}
}
impl FixedStep {
/// The clock of a client connected to a server: the `ClientLevel`'s
/// `TickRateManager`, set by the server's ticking packets.
pub fn client() -> Self {
Self {
client: true,
..Self::default()
}
}
fn now_ms(&self) -> i64 {
self.now.as_millis() as i64
}
@@ -341,9 +353,14 @@ impl FixedStep {
}
let runs = self.manager.base.runs_normally();
let mspt = self.manager.base.milliseconds_per_tick();
let client = self.client;
let ticks = self
.timer
.advance_game_time(now_ms, |default| if runs { mspt } else { default });
.advance_game_time(now_ms, |default| match (runs, client) {
(true, true) => default.max(mspt),
(true, false) => mspt,
(false, _) => default,
});
ticks.clamp(0, 10) as u32
}
/// Restart pacing from now (after loading, so no backlog replays).
@@ -400,6 +417,10 @@ impl FixedStep {
pub fn set_frozen(&mut self, frozen: bool) {
self.manager.base.set_frozen(frozen);
}
/// `TickRateManager.setFrozenTicksToRun` (ClientboundTickingStepPacket).
pub fn set_frozen_ticks_to_run(&mut self, ticks: i32) {
self.manager.base.set_frozen_ticks_to_run(ticks);
}
pub fn sprinting(&self) -> bool {
self.manager.is_sprinting()
}
@@ -484,4 +505,21 @@ mod tests {
m.base.tick();
assert!(!m.base.runs_normally());
}
#[test]
fn a_servers_tick_rate_only_slows_its_client_down() {
let quarter = std::time::Duration::from_millis(250);
let mut client = FixedStep::client();
client.set_rate(40.0);
assert_eq!(client.advance(quarter), 5, "still 20 a second");
let mut slow = FixedStep::client();
slow.set_rate(10.0);
assert_eq!(slow.advance(quarter * 2), 5, "10 a second");
let mut local = FixedStep::default();
local.set_rate(40.0);
assert_eq!(
local.advance(quarter),
10,
"the integrated loop runs at the rate"
);
}
}
+170 -32
View File
@@ -68,6 +68,7 @@ mod lan_mobs;
mod lan_pvp;
mod lan_screen;
mod lan_trading;
mod lan_waypoints;
mod leads;
mod level_particles;
mod lightning;
@@ -112,6 +113,7 @@ mod scoreboard;
mod screens;
mod sculk;
mod sculk_fixture;
mod server_travel;
mod shader_packs;
mod shield;
mod sign_edit;
@@ -966,12 +968,15 @@ struct Game<'a> {
/// `ClientAvatarState`: walked distance and view bob.
avatar: horizon_client::camera::AvatarBob,
flash: u32,
/// Sleeping in a bed: (bed head position, ticks asleep).
sleeping: Option<([i32; 3], u32)>,
/// The head of the bed while sleeping; the visual timer also survives waking.
sleeping: Option<[i32; 3]>,
sleep_timer: u32,
dim: Dim,
world_root: PathBuf,
/// A player carried through a portal, re-placed once the destination loads.
travelling: Option<(PlayerMotion, Vec3)>,
/// A server's lone player on its way to another level.
server_trip: Option<server_travel::Trip>,
/// Nether portals: the player's, items' and mobs' (game/nether_portal.rs).
portals: nether_portal::Portals,
/// The pending travel goes through an End portal (EndPortalBlock destinations).
@@ -3179,7 +3184,7 @@ impl Game<'_> {
if !self.streaming.is_lit(cx, cz) {
return Ok(());
}
let playing = self.screen == Screen::Playing;
let playing = self.screen == Screen::Playing && self.sleeping.is_none();
let held = |k| playing && self.keys.contains(&k);
let keys = Keys {
forward: held(KeyCode::KeyW),
@@ -3273,7 +3278,12 @@ impl Game<'_> {
let feet = [player.position.x, player.position.y, player.position.z];
let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z];
self.previous_eye = self.eye;
self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5;
let eye_height = if self.sleeping.is_some() {
0.2
} else {
player.dimensions.eye_height
};
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.record_combat(&events);
@@ -3536,7 +3546,11 @@ impl Game<'_> {
});
horizon_client::spans::time("tick_particles", || self.tick_particles());
}
if self.right && self.use_delay == 0 && self.screen == Screen::Playing {
if self.right
&& self.use_delay == 0
&& self.screen == Screen::Playing
&& self.sleeping.is_none()
{
self.use_with_hand()?;
self.use_delay = 4;
}
@@ -3919,15 +3933,7 @@ impl Game<'_> {
self.draw_boss_bars(&mut batch);
self.draw_extras(&mut batch);
}
// Hud.extractSleepOverlay, under the sidebar, titles and chat.
if let Some((_, ticks)) = self.sleeping {
let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32);
hud_layout::paint(&mut batch, &self.atlas, &draws);
}
if show_hud {
self.draw_titles(&mut batch);
self.draw_scoreboard(&mut batch);
self.draw_subtitles(&mut batch);
// The mount's hearts (and the jump bar that replaces the experience bar).
let (vehicle_hearts, jump_bar) = if spectator {
(0, false)
@@ -3999,6 +4005,14 @@ impl Game<'_> {
self.draw_selected_name(&mut batch, !self.creative);
}
}
// Hud.extractSleepOverlay: over all health/food bars, under titles and chat.
let draws = hud_overlays::sleep_overlay(wi, hi, self.sleep_timer as i32);
hud_layout::paint(&mut batch, &self.atlas, &draws);
if show_hud {
self.draw_titles(&mut batch);
self.draw_scoreboard(&mut batch);
self.draw_subtitles(&mut batch);
}
let atlas = &self.atlas;
if show_hud
&& let Some((text, at)) = &self.message
@@ -5856,6 +5870,38 @@ impl Game<'_> {
let delay = 20.0 / (4.0 + speed).max(0.1);
((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0)
}
/// `Player.isSweepAttack`: a charged, grounded sword hit below the movement limit.
pub(super) fn sweep_attack_position(&self, scale: f32, crit: bool) -> Option<[f64; 3]> {
let p = self.player.as_ref()?;
let sword = self.held().is_some_and(|s| {
self.res
.items
.item_tags
.get("minecraft:swords")
.is_some_and(|tag| tag.contains(&*s.item))
});
if !p.is_sweep_attack(scale, crit, sword) {
return None;
}
let yaw = f64::from(self.yaw.to_radians());
Some([
p.position.x - yaw.sin(),
p.position.y + f64::from(p.dimensions.height) * 0.5,
p.position.z + yaw.cos(),
])
}
/// The visual and sound part of `Player.doSweepAttack` after a successful hit.
pub(super) fn sweep_attack(&mut self, at: [f64; 3], from: Option<[f64; 3]>) {
self.particles.add(
&horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::SweepAttack,
),
at,
[0.0; 3],
);
self.audio
.play("minecraft:entity.player.attack.sweep", from, 1.0, 1.0);
}
/// `Player.attack`'s sounds when a vehicle takes the hit (it always does,
/// and can't be hit critically): knockback when sprinting at full
/// strength, then strong or weak. Before `swing_arm` resets the charge.
@@ -5872,7 +5918,11 @@ impl Game<'_> {
} else {
"minecraft:entity.player.attack.weak"
};
self.audio.play(sound, from, 1.0, 1.0);
if let Some(at) = self.sweep_attack_position(self.attack_strength_scale(), false) {
self.sweep_attack(at, from);
} else {
self.audio.play(sound, from, 1.0, 1.0);
}
}
/// Player.attack with the attack-strength charge, crits and knockback.
fn attack(&mut self) -> bool {
@@ -5924,6 +5974,7 @@ impl Game<'_> {
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);
let sweep = self.sweep_attack_position(scale, crit);
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
@@ -5983,7 +6034,11 @@ impl Game<'_> {
"minecraft:entity.player.attack.weak"
};
// Player.playServerSideSound: at the player.
self.audio.play(sound, from, 1.0, 1.0);
if let Some(at) = sweep {
self.sweep_attack(at, from);
} else {
self.audio.play(sound, from, 1.0, 1.0);
}
// The hurt or death sound the mob raised (getHurtSound / getDeathSound,
// its voice pitch from its own random).
let queued = std::mem::take(&mut self.mobs[index].outbox);
@@ -6324,6 +6379,8 @@ impl Game<'_> {
self.clear_entities();
self.travelling = None;
self.player = None;
self.sleeping = None;
self.sleep_timer = 0;
self.spawn = None;
self.respawn_travel = None;
self.respawn_config =
@@ -6450,6 +6507,17 @@ impl Game<'_> {
let Some(player) = self.player.take() else {
return Ok(());
};
let from = self.dim;
let destination = self.switch_level(target, player.position)?;
self.trigger_dimension(from, target);
self.travelling = Some((player, destination));
self.end_travel = (target == Dim::End || from == Dim::End) && self.end_portal_travel;
Ok(())
}
/// The level swap under a dimension change: save the departing level,
/// open `target`'s, and return where a player leaving from `from` goes
/// (scaled coordinates, or the End portal's fixed destination).
pub(super) fn switch_level(&mut self, target: Dim, from: Vec3) -> Result<Vec3> {
// Save the departing dimension's changed chunks.
self.streaming.save(&mut self.world, true);
let keys: Vec<_> = self.world.modified.drain().collect();
@@ -6465,11 +6533,10 @@ impl Game<'_> {
_ => 1.0,
};
let destination = self.end_destination(target).unwrap_or(Vec3::new(
player.position.x * scale,
player.position.y,
player.position.z * scale,
from.x * scale,
from.y,
from.z * scale,
));
let from_end = self.dim == Dim::End;
let (streaming, save) =
self.make_streaming(&self.world_root.clone(), target, self.level.seed)?;
let mut world = World::new(self.res.facts.air, self.level.seed);
@@ -6477,12 +6544,14 @@ impl Game<'_> {
world.game_time = self.world.game_time;
world.day_time = self.world.day_time;
world.weather = self.world.weather;
// An open hub keeps hearing the new level's block changes.
world.block_log = self.world.block_log.as_ref().map(|_| Vec::new());
// The sculk tables' watched blocks are built once per game.
world.watched = std::mem::take(&mut self.world.watched);
self.streaming = streaming;
self.world = world;
self.save = save;
let from = self.dim;
self.dim = target;
self.trigger_dimension(from, target);
self.level.dimension = target.id().to_owned();
self.block_ticks = Ticks::new(self.level.seed as i32);
self.tick_chunks.clear();
@@ -6495,13 +6564,11 @@ impl Game<'_> {
self.pickups.clear();
self.orbs.clear();
self.mining = None;
self.travelling = Some((player, destination));
self.end_travel = (target == Dim::End || from_end) && self.end_portal_travel;
if let Some(r) = self.renderer.as_mut() {
r.clear_sections();
}
self.apply_settings();
Ok(())
Ok(destination)
}
/// PortalShape: an obsidian frame around 2..=21 by 3..=21 empty blocks.
fn portal_shape(&self, start: [i32; 3], x_axis: bool) -> Option<([i32; 3], i32, i32)> {
@@ -6671,6 +6738,8 @@ impl Game<'_> {
self.streaming.paused = true;
self.world = World::new(self.res.facts.air, 0);
self.player = None;
self.sleeping = None;
self.sleep_timer = 0;
self.clear_entities();
self.screen = Screen::Playing;
if let Some(r) = self.renderer.as_mut() {
@@ -7500,6 +7569,7 @@ impl Game<'_> {
// GameRenderer.renderItemInHand: F1 hides the hand with the HUD.
if self.spectator()
|| self.ui.hide_gui
|| self.sleeping.is_some()
|| !self.camera_type.first_person()
|| self
.player
@@ -7975,13 +8045,23 @@ impl Game<'_> {
return;
}
self.message = Some(("Respawn point set".into(), Instant::now()));
self.sleeping = Some((head, 0));
self.stop_mining();
self.left = false;
self.right = false;
self.using = None;
self.sleeping = Some(head);
self.sleep_timer = 0;
self.stats.custom("sleep_in_bed", 1);
self.trigger_player("minecraft:slept_in_bed");
self.stats.reset("custom", "minecraft:time_since_rest");
}
fn wake_up(&mut self) {
self.sleeping = None;
self.sleep_timer = 100;
}
fn tick_sleep(&mut self) {
let Some((head, ticks)) = self.sleeping else {
self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some());
let Some(head) = self.sleeping else {
return;
};
if self.keys.contains(&KeyCode::ShiftLeft)
@@ -7990,7 +8070,7 @@ impl Game<'_> {
.as_ref()
.is_none_or(|p| p.health.dead_or_dying())
{
self.sleeping = None;
self.wake_up();
return;
}
if let Some(p) = self.player.as_mut() {
@@ -8001,18 +8081,15 @@ impl Game<'_> {
);
p.velocity = Vec3::ZERO;
}
let ticks = ticks + 1;
// ServerLevel: once everyone has slept 100 ticks, skip to morning and clear weather.
if ticks >= 100 {
if self.sleep_timer >= 100 {
let t = self.world.day_time;
self.world.day_time = t + 24000 - t.rem_euclid(24000);
self.world.weather.raining = false;
self.world.weather.thundering = false;
self.world.weather.rain_time = 0;
self.world.weather.thunder_time = 0;
self.sleeping = None;
} else {
self.sleeping = Some((head, ticks));
self.wake_up();
}
}
fn creative_origin(batch: &HudBatch) -> (f32, f32) {
@@ -8820,6 +8897,18 @@ impl Game<'_> {
}
/// A key press while a world is open (keyboard or control socket).
fn key_pressed(&mut self, key: KeyCode) -> Result<()> {
if self.sleeping.is_some()
&& self.screen == Screen::Playing
&& !matches!(
key,
KeyCode::F1 | KeyCode::F2 | KeyCode::F11 | KeyCode::KeyT | KeyCode::Slash
)
{
if matches!(key, KeyCode::Escape | KeyCode::ShiftLeft) {
self.wake_up();
}
return Ok(());
}
if self.sort_key_press(key) {
return Ok(());
}
@@ -8950,6 +9039,9 @@ impl Game<'_> {
}
/// A mouse button while playing (window or control socket).
fn play_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
if self.sleeping.is_some() {
return Ok(());
}
if self.remote.is_some() {
return self.remote_mouse(button, pressed);
}
@@ -9279,6 +9371,7 @@ impl ApplicationHandler for Game<'_> {
title.scroll_worlds(d, self.cursor, (batch.width, batch.height));
}
if self.screen == Screen::Playing
&& self.sleeping.is_none()
&& self.player.is_some()
&& !self.extras_scroll(d)
&& let Some((wheel, _)) =
@@ -10070,9 +10163,11 @@ impl<'a> Game<'a> {
avatar: Default::default(),
flash: 0,
sleeping: None,
sleep_timer: 0,
dim: Dim::Overworld,
world_root: PathBuf::new(),
travelling: None,
server_trip: None,
portals: Default::default(),
end_travel: false,
respawn_config: None,
@@ -10215,6 +10310,9 @@ pub fn run() -> Result<()> {
horizon_client::spans::enable(options.spikes.is_some());
let vanilla_root = options.resources.clone();
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
// Snapshots of derived tables live in the game folder, never beside the
// shared resources.
Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache"));
let mut pack_error = None;
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs)
.unwrap_or_else(|e| {
@@ -10464,6 +10562,17 @@ pub fn run() -> Result<()> {
Ok(())
}
// Player.tick: cap the sleeping fade at 100, then fade out over 10 waking ticks.
fn tick_sleep_timer(timer: u32, sleeping: bool) -> u32 {
if sleeping {
(timer + 1).min(100)
} else if (1..109).contains(&timer) {
timer + 1
} else {
0
}
}
fn reset_world_progress(adv: &mut advancements::AdvState, stats: &mut stats::Stats) {
*adv = Default::default();
*stats = Default::default();
@@ -10498,6 +10607,35 @@ mod tests {
use horizon_client::container_screen::{Button, Clicks, Release, Target};
use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys};
#[test]
fn sleep_fade_lasts_ten_ticks_after_waking() {
let alpha = |timer| match hud_overlays::sleep_overlay(320, 240, timer).first() {
Some(hud_layout::GuiDraw::Fill { color, .. }) => color >> 24,
None => 0,
_ => panic!("sleep overlay must be a full-screen fill"),
};
assert_eq!(tick_sleep_timer(0, false), 0);
let mut timer = 0;
for _ in 0..50 {
timer = tick_sleep_timer(timer, true);
}
assert_eq!(alpha(timer as i32), 110);
for _ in 0..100 {
timer = tick_sleep_timer(timer, true);
}
assert_eq!(timer, 100);
assert_eq!(alpha(timer as i32), 220);
for _ in 0..5 {
timer = tick_sleep_timer(timer, false);
}
assert_eq!(alpha(timer as i32), 110);
for _ in 0..5 {
timer = tick_sleep_timer(timer, false);
}
assert_eq!(timer, 0);
assert!(hud_overlays::sleep_overlay(320, 240, timer as i32).is_empty());
}
/// An integrated server thread shares the loaded resources with the client.
#[test]
fn shared_resources_can_cross_threads() {
+167 -50
View File
@@ -11,7 +11,7 @@ use horizon_client::{
};
use serde_json::Value;
use std::{
collections::{BTreeMap, VecDeque},
collections::{BTreeMap, BTreeSet, VecDeque},
sync::Arc,
time::Instant,
};
@@ -72,13 +72,22 @@ impl Toast {
#[derive(Default)]
pub(super) struct AdvState {
pub(super) tree: Arc<Tree>,
/// `ClientAdvancements`: a server's tree carries each advancement's
/// place on its tab (`DisplayInfo` x, y), in tree order.
pub(super) positions: Option<Vec<(f32, f32)>>,
pub(super) progress: Progress,
pub(super) loaded: bool,
pub(super) toasts: VecDeque<Toast>,
/// Awards skip the toast (`/advancement grant ... everything`).
pub(super) quiet: bool,
/// The inventory last seen by `inventory_changed`.
last_inventory: u64,
pub(super) last_inventory: u64,
/// While the game acts for a network player (`as_guest`): the
/// advancements whose progress changed (`progressChanged`), the recipes
/// unlocked and the announcements, for their client and everyone's.
pub(super) changed: BTreeSet<usize>,
pub(super) unlocked: Vec<String>,
pub(super) announced: Vec<Text>,
}
/// The game's world for predicates.
struct View<'a, 'g>(&'a Game<'g>);
@@ -171,29 +180,10 @@ impl adv::World for View<'_, '_> {
}
}
fn now_text() -> String {
// "yyyy-MM-dd HH:mm:ss Z" in UTC.
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs()) as i64;
let days = secs.div_euclid(86400);
let rem = secs.rem_euclid(86400);
// Civil from days (Howard Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!(
"{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +0000",
rem / 3600,
rem % 3600 / 60,
rem % 60
)
adv::date_text(secs)
}
impl Game<'_> {
/// `ItemPredicate.test` (the `item_filter` of a filtered item modifier).
@@ -217,30 +207,30 @@ pub(super) fn item_view(s: &ItemStack) -> ItemView {
}
impl Game<'_> {
fn adv_path(&self) -> Option<std::path::PathBuf> {
let uuid = self.level.player_uuid?;
let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect();
let text = format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
);
Some(
self.world_root
.join("players/advancements")
.join(format!("{text}.json")),
)
Some(super::stats::player_json(
&self.world_root,
"advancements",
self.level.player_uuid?,
))
}
pub(super) fn load_advancements(&mut self) {
if self.adv.loaded || self.remote.is_some() {
return;
}
self.adv.loaded = true;
/// A server with no player of its own and nobody it acts for: there is
/// no player for advancements and statistics.
pub(super) fn no_player_here(&self) -> bool {
self.options.dedicated.is_some() && self.lan_acting.is_none()
}
/// The advancement tree, loaded once.
pub(super) fn advancement_tree(&mut self) -> Arc<Tree> {
if self.adv.tree.list.is_empty() {
self.adv.tree = Arc::new(Tree::load(&self.options.resources.join("data")));
}
self.adv.tree.clone()
}
pub(super) fn load_advancements(&mut self) {
if self.adv.loaded || self.remote.is_some() || self.no_player_here() {
return;
}
self.adv.loaded = true;
self.advancement_tree();
let progress = self
.adv_path()
.and_then(|p| std::fs::read_to_string(p).ok())
@@ -254,7 +244,7 @@ impl Game<'_> {
self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect();
}
pub(super) fn save_advancements(&self) {
if !self.adv.loaded || self.remote.is_some() {
if !self.adv.loaded || self.remote.is_some() || self.no_player_here() {
return;
}
let Some(path) = self.adv_path() else {
@@ -376,7 +366,7 @@ impl Game<'_> {
/// `SimpleCriterionTrigger.trigger`: test each open criterion of the
/// trigger and award what it completes.
pub(super) fn trigger(&mut self, name: &str, test: impl Fn(&Value, &dyn adv::World) -> bool) {
if self.remote.is_some() {
if self.remote.is_some() || self.no_player_here() {
return;
}
self.load_advancements();
@@ -403,15 +393,27 @@ impl Game<'_> {
let a = &tree.list[ai];
let was = self.adv.progress.done(a);
self.adv.progress.grant(&a.id, &a.criteria[ci].name, &date);
self.progress_changed(ai);
if !was && self.adv.progress.done(a) {
self.award(ai);
}
}
}
/// `PlayerAdvancements.progressChanged`, kept for a network player's client.
fn progress_changed(&mut self, index: usize) {
if self.lan_acting.is_some() {
self.adv.changed.insert(index);
}
}
/// After `ServerRecipeBook.addRecipes`: the toast and the
/// `recipe_unlocked` trigger of each recipe now known.
pub(super) fn recipe_unlocked(&mut self, unlocked: &[String]) {
self.recipe_toast(unlocked);
if self.lan_acting.is_some() {
// A network player's client gets them in ClientboundRecipeBookAddPacket.
self.adv.unlocked.extend_from_slice(unlocked);
} else {
self.recipe_toast(unlocked);
}
for r in unlocked {
let r = r.clone();
self.trigger("minecraft:recipe_unlocked", move |c, _| {
@@ -453,7 +455,8 @@ impl Game<'_> {
}
}
if let Some(d) = &a.display {
if d.show_toast && !self.adv.quiet {
// A network player's client shows its own toast.
if d.show_toast && !self.adv.quiet && self.lan_acting.is_none() {
self.adv.toasts.push_back(Toast {
icon: d.icon.clone(),
frame: d.frame,
@@ -471,10 +474,18 @@ impl Game<'_> {
Frame::Challenge => "chat.type.advancement.challenge",
};
let name = adv_name(a);
self.system_message(Text::translate(
key,
&[Text::literal(super::chat::PLAYER_NAME), name],
));
// PlayerList.broadcastSystemMessage: everyone hears of a
// network player's advancement.
match self.lan_acting_name.clone() {
Some(player) => self
.adv
.announced
.push(Text::translate(key, &[Text::literal(&player), name])),
None => self.system_message(Text::translate(
key,
&[Text::literal(super::chat::PLAYER_NAME), name],
)),
}
}
}
self.recipe_unlocked(&unlocked);
@@ -820,6 +831,7 @@ impl Game<'_> {
let was = self.adv.progress.done(a);
if self.adv.progress.grant(&a.id, c, &date) {
changed = true;
self.progress_changed(index);
if !was && self.adv.progress.done(a) {
self.award(index);
}
@@ -831,6 +843,7 @@ impl Game<'_> {
pub(super) fn revoke_advancement(&mut self, index: usize, criterion: Option<&str>) -> bool {
let tree = self.adv.tree.clone();
let a = &tree.list[index];
self.progress_changed(index);
match criterion {
Some(c) => self.adv.progress.revoke(&a.id, c),
None => {
@@ -843,6 +856,110 @@ impl Game<'_> {
}
}
}
impl Game<'_> {
/// `ClientAdvancements.update` (ClientboundUpdateAdvancementsPacket):
/// the server's advancements replace or join the tree, each changed one
/// takes the progress sent, and one just done shows its toast. `icons`
/// are the added advancements' icon items by name.
pub(super) fn remote_advancements(
&mut self,
p: horizon_protocol::packets::play::UpdateAdvancements,
icons: Vec<String>,
) {
use horizon_client::scoreboard::tag_to_json;
let mut list: Vec<adv::Advancement> = Vec::new();
let mut positions: Vec<(f32, f32)> = Vec::new();
if !p.reset {
let old = self.adv.positions.take().unwrap_or_default();
for (i, a) in self.adv.tree.list.iter().enumerate() {
if !p.removed.contains(&a.id) {
list.push(a.clone());
positions.push(old.get(i).copied().unwrap_or((0.0, 0.0)));
}
}
} else {
self.adv.progress = Progress::default();
}
for id in &p.removed {
self.adv.progress.criteria.remove(id);
}
for (a, icon) in p.added.into_iter().zip(icons) {
list.retain(|o| o.id != a.id);
let display = a.display.map(|d| adv::Display {
icon,
title: tag_to_json(&d.title),
description: tag_to_json(&d.description),
frame: match d.frame {
1 => Frame::Challenge,
2 => Frame::Goal,
_ => Frame::Task,
},
background: d.background,
show_toast: d.show_toast,
announce: false,
hidden: d.hidden,
});
let mut criteria: Vec<adv::Criterion> = Vec::new();
for name in a.requirements.iter().flatten() {
if !criteria.iter().any(|c| &c.name == name) {
criteria.push(adv::Criterion {
name: name.clone(),
trigger: String::new(),
conditions: Value::Null,
});
}
}
list.push(adv::Advancement {
id: a.id,
parent: a.parent,
display,
criteria,
requirements: a.requirements,
rewards: Default::default(),
});
positions.push((a.x, a.y));
}
let mut tree = Tree {
list,
..Tree::default()
};
for (i, a) in tree.list.iter().enumerate() {
tree.by_id.insert(a.id.clone(), i);
}
self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect();
self.adv.tree = Arc::new(tree);
self.adv.positions = Some(positions);
let tree = self.adv.tree.clone();
for (id, criteria) in p.progress {
let Some(&i) = tree.by_id.get(&id) else {
continue;
};
// The client only shows whether a criterion is obtained, not when.
let obtained: BTreeMap<String, String> = criteria
.into_iter()
.filter(|(_, at)| at.is_some())
.map(|(name, _)| (name, String::new()))
.collect();
self.adv.progress.criteria.insert(id, obtained);
let a = &tree.list[i];
if !p.reset
&& p.show
&& self.adv.progress.done(a)
&& let Some(d) = a.display.as_ref().filter(|d| d.show_toast)
{
self.adv.toasts.push_back(Toast {
icon: d.icon.clone(),
frame: d.frame,
title: text_of(&d.title),
slide: Slide::default(),
recipes: Vec::new(),
changed: false,
last_changed: 0,
});
}
}
}
}
/// A text component from advancement JSON (`translate` or `text`).
pub(super) fn text_of(v: &Value) -> Text {
if let Some(key) = v["translate"].as_str() {
@@ -163,11 +163,18 @@ impl Game<'_> {
}
let tree = self.adv.tree.clone();
let kids = tree.children();
let pos = tree
.layout()
.into_iter()
.map(|p| p.map(|(x, y)| (x * 28, (y * 27.0).floor() as i32)))
.collect();
// A server's advancements come placed (`DisplayInfo` x, y).
let pos = match &self.adv.positions {
Some(server) => server
.iter()
.map(|&(x, y)| Some(((x * 28.0).floor() as i32, (y * 27.0).floor() as i32)))
.collect(),
None => tree
.layout()
.into_iter()
.map(|p| p.map(|(x, y)| (x * 28, (y * 27.0).floor() as i32)))
.collect(),
};
self.adv_ui.cache = Some(Cache { tree, kids, pos });
}
fn adv_done(&self, i: usize) -> bool {
@@ -184,7 +191,12 @@ impl Game<'_> {
};
};
let tree = &c.tree;
let visible = tree.visible(&c.kids, |i| self.adv.progress.done(&tree.list[i]));
// A server sends only what the player may see.
let visible = if self.adv.positions.is_some() {
vec![true; tree.list.len()]
} else {
tree.visible(&c.kids, |i| self.adv.progress.done(&tree.list[i]))
};
// AdvancementTab.create: a displayed root with a background.
let mut tabs: Vec<usize> = (0..tree.list.len())
.filter(|&i| {
+109 -46
View File
@@ -9,11 +9,13 @@
use super::{Game, Options, lan::LanSettings};
use horizon_client::{
Result,
lan::{LoginGate, NetConfig, hub::HubConfig},
lan::{LoginGate, NetConfig, NetLog, OnlineMode, hub::HubConfig},
server::{
eula,
java_properties::now_millis,
profiles,
properties::{GAME_MODES, ServerProperties, SystemEntropy},
user_cache::UserCache,
user_lists::{
BanEntry, BanList, IpBanList, NameAndId, OpEntry, OpList, WhiteEntry, WhiteList,
format_date,
@@ -57,9 +59,26 @@ struct Setup {
started: Instant,
}
static SETUP: OnceLock<Mutex<Option<Setup>>> = OnceLock::new();
/// usercache.json (Services.nameToIdCache): used by the server thread only.
static USER_CACHE: Mutex<Option<UserCache>> = Mutex::new(None);
/// PlayerList.placeNewPlayer: a player who joined is cached (and the file saved).
pub(super) fn player_joined(id: u128, name: &str) {
if let Some(cache) = USER_CACHE.lock().unwrap().as_mut() {
cache.add(NameAndId {
id,
name: name.to_owned(),
});
}
}
/// Log4j's console pattern: `[HH:mm:ss] [thread/LEVEL]: message`.
pub(super) fn log(level: &str, message: &str) {
log_from("Server thread", level, message);
}
/// A line from another of vanilla's threads (the login's User Authenticator).
fn log_from(thread: &str, level: &str, message: &str) {
let file_level = match level {
"WARN" => ::log::Level::Warn,
"ERROR" => ::log::Level::Error,
@@ -73,7 +92,7 @@ pub(super) fn log(level: &str, message: &str) {
});
let secs = now_millis().div_euclid(1000).rem_euclid(86_400);
println!(
"[{:02}:{:02}:{:02}] [Server thread/{level}]: {message}",
"[{:02}:{:02}:{:02}] [{thread}/{level}]: {message}",
secs / 3600,
secs / 60 % 60,
secs % 60
@@ -343,6 +362,14 @@ impl Game<'_> {
line.clear();
}
})?;
// Main: Services.create loads the universe's usercache.json.
let (mut cache, warnings) = UserCache::load(universe.join("usercache.json"));
for warning in warnings {
log_from("main", "WARN", &warning);
}
// DedicatedServer.initServer: names nobody has resolve offline only without authentication.
cache.resolve_offline_users = !props.online_mode;
*USER_CACHE.lock().unwrap() = Some(cache);
log("INFO", "Starting minecraft server version 26.3");
log("INFO", "Loading properties");
let game_mode = props.game_mode;
@@ -354,6 +381,19 @@ impl Game<'_> {
),
);
let port = port.unwrap_or(props.server_port as u16);
// MinecraftServer.initializeKeyPair (only online mode uses it).
log("INFO", "Generating keypair");
let online = if props.online_mode {
let key = horizon_protocol::rsa::RsaPrivateKey::generate(1024)
.map_err(|e| format!("Failed to generate key pair: {e}"))?;
Some(Arc::new(OnlineMode {
public_der: key.public_der(),
key,
prevent_proxy: props.prevent_proxy_connections,
}))
} else {
None
};
log(
"INFO",
&format!(
@@ -365,27 +405,21 @@ impl Game<'_> {
}
),
);
if props.online_mode {
// Authentication needs Mojang's session servers (an HTTPS client
// and RSA), which Horizon does not have yet: offline mode.
if online.is_none() {
log("WARN", "**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!");
log(
"WARN",
"online-mode=true is not supported by Horizon yet: running in offline mode",
"The server will make no attempt to authenticate usernames. Beware.",
);
log(
"WARN",
"While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose.",
);
log(
"WARN",
"To change this, set \"online-mode\" to \"true\" in the server.properties file.",
);
}
log("WARN", "**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!");
log(
"WARN",
"The server will make no attempt to authenticate usernames. Beware.",
);
log(
"WARN",
"While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose.",
);
log(
"WARN",
"To change this, set \"online-mode\" to \"true\" in the server.properties file.",
);
let mut lists = Lists::load();
lists.use_whitelist = props.white_list;
lists.enforce_whitelist = props.enforce_whitelist;
@@ -451,6 +485,12 @@ impl Game<'_> {
.any(|e| e.user.id == uuid && e.bypasses_player_limit)
})),
gate: Some(gate),
online,
log: Some(NetLog {
write: Arc::new(log_from),
lang: Arc::new(horizon_client::net::load_language(&self.options.resources)),
log_ips: props.log_ips,
}),
};
let config = HubConfig {
default_game_mode: game_mode,
@@ -623,23 +663,36 @@ impl Game<'_> {
host.hub.resend_commands();
}
/// A known player by name: online first, else the offline profile.
fn resolve(&self, name: &str) -> NameAndId {
self.lan
.as_ref()
.and_then(|h| {
h.hub
.guests
.iter()
.find(|g| g.name.eq_ignore_ascii_case(name))
/// A player on the server, by name.
fn online_player(&self, name: &str) -> Option<NameAndId> {
let hub = &self.lan.as_ref()?.hub;
let g = hub
.guests
.iter()
.find(|g| g.name.eq_ignore_ascii_case(name))?;
Some(NameAndId {
id: g.uuid,
name: g.name.clone(),
})
}
/// GameProfileArgument for a name: the user cache, else the profile
/// service, else (offline) the offline player. None, told to the console:
/// no such player.
fn resolve(&self, name: &str) -> Option<NameAndId> {
let found = USER_CACHE.lock().unwrap().as_mut().and_then(|cache| {
cache.get_by_name(name, |lower| {
let found = profiles::find_by_name(&profiles::discovery_url(), lower);
if found.is_none() {
log("WARN", &format!("Couldn't find profile with name: {lower}"));
}
found
})
.map_or_else(
|| NameAndId::offline(name),
|g| NameAndId {
id: g.uuid,
name: g.name.clone(),
},
)
});
if found.is_none() {
self.console_reply(Text::translate("argument.player.unknown", &[]));
}
found
}
/// MinecraftServer.sendSystemMessage: what the console is told.
@@ -722,7 +775,9 @@ impl Game<'_> {
));
}
"op" | "deop" if !rest.is_empty() => {
let user = self.resolve(rest[0]);
let Some(user) = self.resolve(rest[0]) else {
return;
};
let level = 4;
let changed = {
let mut l = state.lists.lock().unwrap();
@@ -752,7 +807,9 @@ impl Game<'_> {
}
"whitelist" => self.console_whitelist(state, &rest),
"ban" if !rest.is_empty() => {
let user = self.resolve(rest[0]);
let Some(user) = self.resolve(rest[0]) else {
return;
};
let reason = (rest.len() > 1).then(|| rest[1..].join(" "));
let added = state.lists.lock().unwrap().bans.add(BanEntry::new(
user.clone(),
@@ -842,7 +899,9 @@ impl Game<'_> {
}
}
"pardon" if !rest.is_empty() => {
let user = self.resolve(rest[0]);
let Some(user) = self.resolve(rest[0]) else {
return;
};
let removed = state.lists.lock().unwrap().bans.remove(&user);
let key = if removed {
"commands.pardon.success"
@@ -908,15 +967,10 @@ impl Game<'_> {
}
}
"kick" if !rest.is_empty() => {
let user = self.resolve(rest[0]);
let online = self
.lan
.as_ref()
.is_some_and(|h| h.hub.guests.iter().any(|g| g.uuid == user.id));
if !online {
let Some(user) = self.online_player(rest[0]) else {
self.console_reply(Text::translate("argument.entity.notfound.player", &[]));
return;
}
};
let reason = if rest.len() > 1 {
Tag::String(JavaString::from(rest[1..].join(" ").as_str()))
} else {
@@ -996,7 +1050,9 @@ impl Game<'_> {
self.console_reply(Text::translate("commands.whitelist.reloaded", &[]));
}
["add", name] | ["remove", name] => {
let user = self.resolve(name);
let Some(user) = self.resolve(name) else {
return;
};
let mut l = state.lists.lock().unwrap();
let (ok, key) = if rest[0] == "add" {
if l.white.contains(&user) {
@@ -1073,6 +1129,13 @@ impl Game<'_> {
for g in &h.hub.guests {
horizon_client::lan::playerdata::save(g, &self.world_root);
}
}
if let Some(h) = self.lan.as_ref() {
for g in &h.hub.guests {
self.save_guest_records(h, g);
}
}
if let Some(h) = self.lan.as_mut() {
let conns: Vec<u32> = h.hub.guests.iter().map(|g| g.conn).collect();
for conn in conns {
h.hub.kick(
+74 -51
View File
@@ -222,7 +222,7 @@ impl Game<'_> {
}
}
fn block_name(&self, p: [i32; 3]) -> std::sync::Arc<str> {
pub(super) fn block_name(&self, p: [i32; 3]) -> std::sync::Arc<str> {
self.res
.facts
.get(self.world.block(p[0], p[1], p[2]))
@@ -366,31 +366,11 @@ impl Game<'_> {
if self.travelling.is_some() || p.health.dead_or_dying() {
return Ok(());
}
let w = f64::from(p.dimensions.width) / 2.0;
let lo = [p.position.x - w, p.position.y, p.position.z - w];
let hi = [
p.position.x + w,
p.position.y + f64::from(p.dimensions.height),
p.position.z + w,
];
let mut portal = false;
let mut gateway = None;
for x in lo[0].floor() as i32..=hi[0].floor() as i32 {
for y in lo[1].floor() as i32..=hi[1].floor() as i32 {
for z in lo[2].floor() as i32..=hi[2].floor() as i32 {
let name = self.block_name([x, y, z]);
// EndPortalBlock entity-inside shape: y 6/16..12/16.
if &*name == "minecraft:end_portal"
&& lo[1] < f64::from(y) + 0.75
&& hi[1] > f64::from(y) + 0.375
{
portal = true;
} else if &*name == "minecraft:end_gateway" && self.dim == Dim::End {
gateway = Some([x, y, z]);
}
}
}
}
let (portal, gateway) = self.inside_end_portals(
p.position,
f64::from(p.dimensions.width),
f64::from(p.dimensions.height),
);
if portal {
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
@@ -417,6 +397,38 @@ impl Game<'_> {
Ok(())
}
/// Whether a `width` by `height` box at `position` is inside an End
/// portal (its entity-inside shape), and the End gateway it touches.
pub(super) fn inside_end_portals(
&self,
position: Vec3,
width: f64,
height: f64,
) -> (bool, Option<[i32; 3]>) {
let w = width / 2.0;
let lo = [position.x - w, position.y, position.z - w];
let hi = [position.x + w, position.y + height, position.z + w];
let mut portal = false;
let mut gateway = None;
for x in lo[0].floor() as i32..=hi[0].floor() as i32 {
for y in lo[1].floor() as i32..=hi[1].floor() as i32 {
for z in lo[2].floor() as i32..=hi[2].floor() as i32 {
let name = self.block_name([x, y, z]);
// EndPortalBlock entity-inside shape: y 6/16..12/16.
if &*name == "minecraft:end_portal"
&& lo[1] < f64::from(y) + 0.75
&& hi[1] > f64::from(y) + 0.375
{
portal = true;
} else if &*name == "minecraft:end_gateway" && self.dim == Dim::End {
gateway = Some([x, y, z]);
}
}
}
}
(portal, gateway)
}
/// EndPortalBlock.getPortalDestination for the pending enter_dimension.
pub(super) fn end_destination(&self, target: Dim) -> Option<Vec3> {
if !self.end_portal_travel {
@@ -451,10 +463,36 @@ impl Game<'_> {
self.previous_eye = 1.62;
self.clock.reset();
}
let mut position = target;
if let Some(job) = self.end.job.take() {
position = self.resolve_gateway(job, target)?;
} else if self.dim == Dim::End {
let position = if let Some(job) = self.end.job.take() {
self.resolve_gateway(job, target)?
} else {
let (position, yaw) = self.end_arrival(target)?;
if let Some(yaw) = yaw {
self.yaw = yaw;
player.yaw = yaw;
player.head_yaw = yaw;
}
position
};
player.position = position;
player.velocity = Vec3::ZERO;
player.fall_distance = 0.0;
self.previous_position = player.position;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
let pitch = self.world.random.next_float() * 0.4 + 0.8;
self.audio
.play("minecraft:block.portal.travel", None, 0.25, pitch);
Ok(())
}
/// Where an End portal's traveller lands once `target` has loaded, and
/// the yaw it faces there: the platform below the End's spawn point,
/// facing west, or the top of the Overworld's spawn column.
pub(super) fn end_arrival(&mut self, target: Vec3) -> Result<(Vec3, Option<f32>)> {
if self.dim == Dim::End {
// EndPlatformFeature.createEndPlatform below the spawn point.
let origin = [END_SPAWN[0], END_SPAWN[1] - 1, END_SPAWN[2]];
for dz in -2..=2 {
@@ -473,28 +511,13 @@ impl Game<'_> {
}
}
// Direction.WEST.toYRot().
self.yaw = 90.0;
player.yaw = 90.0;
player.head_yaw = 90.0;
} else {
// ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column.
let y = self
.land_column(target.x.floor() as i32, target.z.floor() as i32)
.map_or(target.y, f64::from);
position = Vec3::new(target.x, y, target.z);
return Ok((target, Some(90.0)));
}
player.position = position;
player.velocity = Vec3::ZERO;
player.fall_distance = 0.0;
self.previous_position = player.position;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
let pitch = self.world.random.next_float() * 0.4 + 0.8;
self.audio
.play("minecraft:block.portal.travel", None, 0.25, pitch);
Ok(())
// ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column.
let y = self
.land_column(target.x.floor() as i32, target.z.floor() as i32)
.map_or(target.y, f64::from);
Ok((Vec3::new(target.x, y, target.z), None))
}
/// Dying away from the Overworld respawns at the world spawn there.
+7 -1
View File
@@ -55,7 +55,13 @@ impl Game<'_> {
.fov_player()
.map_or(1.0, |p| field_of_view_modifier(&p, first_person, effect));
let target = self.zoomed_fov_target(target);
let eye = self.player.as_ref().map(|p| p.dimensions.eye_height);
let eye = self.player.as_ref().map(|p| {
if self.sleeping.is_some() {
0.2
} else {
p.dimensions.eye_height
}
});
self.view.tick(eye, target);
}
/// The player's `deathTime` while dead or dying.
+1 -1
View File
@@ -67,7 +67,7 @@ impl Game<'_> {
/// attack clicks since the last tick and the held attack button.
pub(super) fn tick_local_hand(&mut self) -> Result<()> {
let attack_clicks = std::mem::take(&mut self.attack_clicks);
if self.screen == Screen::Playing && self.title.is_none() {
if self.screen == Screen::Playing && self.title.is_none() && self.sleeping.is_none() {
let mut clicks = std::mem::take(&mut self.clicks);
// keyAttack.isDown(); playing implies the grabbed mouse here
// (scripts under --control hold buttons without grabbing it).
+5 -11
View File
@@ -8,11 +8,9 @@
//!
//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the
//! player joins as a network player, and the server side of a network player
//! does not do everything single player does yet. Worlds whose player is
//! outside the Overworld open the usual way, since network players stay in
//! the Overworld so far.
//! does not do everything single player does yet.
use super::{
Dim, Game, Options, PackResources, Resources,
Game, Options, PackResources, Resources,
lan::{LanSettings, Owner},
};
use horizon_client::{
@@ -20,7 +18,6 @@ use horizon_client::{
audio::Audio,
hud::HudAtlas,
lan::{Lan, MAX_PLAYERS, NetConfig, hub::HubConfig},
save::Level,
settings::Settings,
title::WorldOptions,
};
@@ -137,12 +134,9 @@ struct Launch {
player: String,
}
/// Whether this world opens on a server thread: asked for, and its player
/// (if any yet) in the Overworld.
pub(super) fn wanted(options: &Options, world: &Path) -> bool {
options.server_thread
&& options.dedicated.is_none()
&& Level::read(world).is_none_or(|l| Dim::from_id(&l.dimension) == Dim::Overworld)
/// Whether this world opens on a server thread: asked for.
pub(super) fn wanted(options: &Options, _world: &Path) -> bool {
options.server_thread && options.dedicated.is_none()
}
impl Game<'_> {
+81
View File
@@ -57,6 +57,10 @@ pub(super) struct LanHost {
pub mob_players: HashMap<u32, u32>,
/// An integrated server's owner (game/integrated.rs).
pub owner: Option<Owner>,
/// The players' locator bars (game/lan_waypoints.rs), and the guests who
/// are dead, whose respawn replaces their waypoint.
pub waypoints: lan::waypoints::Waypoints,
pub waypoint_dead: std::collections::HashSet<u128>,
}
/// The player who owns an integrated server's world: a guest whose state is
@@ -502,6 +506,8 @@ impl Game<'_> {
mob_state: HashMap::new(),
mob_players: HashMap::new(),
owner: None,
waypoints: Default::default(),
waypoint_dead: Default::default(),
});
self.audio.capture = Some(Vec::new());
Ok(())
@@ -557,6 +563,75 @@ impl Game<'_> {
} else {
playerdata::save(guest, &self.world_root);
}
self.save_guest_records(host, guest);
}
/// The file name of a player's advancements and statistics: an
/// integrated server's owner keeps single player's.
fn records_uuid(&self, host: &LanHost, uuid: u128) -> Option<[i32; 4]> {
if host.owner.as_ref().is_some_and(|o| o.uuid == uuid) {
self.level.player_uuid
} else {
Some(playerdata::uuid_ints(uuid))
}
}
/// `PlayerAdvancements.save` and `ServerStatsCounter.save` of a network player.
pub(super) fn save_guest_records(
&self,
host: &LanHost,
guest: &horizon_client::lan::guest::Guest,
) {
if !guest.placed || self.adv.tree.list.is_empty() {
return;
}
let Some(uuid) = self.records_uuid(host, guest.uuid) else {
return;
};
let path = super::stats::player_json(&self.world_root, "advancements", uuid);
let json = guest
.advancements
.to_json(&self.adv.tree, horizon_world::DATA_VERSION);
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(text) = serde_json::to_string_pretty(&json) {
let _ = std::fs::write(path, text);
}
if let Some(play) = host.play.get(&guest.conn) {
play.stats
.write(&super::stats::player_json(&self.world_root, "stats", uuid));
}
}
/// `PlayerAdvancements.load` and `ServerStatsCounter.parseLocal` of a
/// network player who joined; every statistic goes out on the first
/// request (`PlayerList.placeNewPlayer`'s `markAllDirty`).
fn load_guest_records(&mut self, host: &mut LanHost, conn: u32) {
let Some(uuid) = host
.hub
.guest(conn)
.and_then(|g| self.records_uuid(host, g.uuid))
else {
return;
};
let tree = self.advancement_tree();
let path = super::stats::player_json(&self.world_root, "advancements", uuid);
let saved = std::fs::read_to_string(path)
.ok()
.and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok());
if let Some(g) = host.hub.guest_mut(conn)
&& let Some(json) = saved
{
let mut progress = horizon_client::advancements::Progress::from_json(&json);
// PlayerAdvancements.applyFrom: advancements this server lacks are dropped.
progress
.criteria
.retain(|id, _| tree.by_id.contains_key(id));
g.advancements = progress;
g.advancements_loaded = true;
}
let mut stats =
super::stats::Stats::read(&super::stats::player_json(&self.world_root, "stats", uuid));
stats.mark_all_dirty();
host.play.entry(conn).or_default().stats = stats;
}
/// The integrated server's owner into the world's player, for `Level::write`.
pub(super) fn store_owner(&mut self) {
@@ -568,6 +643,7 @@ impl Game<'_> {
};
if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) {
playerdata::store(g, &mut self.level);
self.save_guest_records(host, g);
}
}
@@ -729,6 +805,7 @@ impl Game<'_> {
&& let Some(g) = host.hub.guest(conn)
{
// PlayerList.placeNewPlayer, then the broadcast join message.
super::dedicated::player_joined(g.uuid, &g.name);
let [x, y, z] = g.position;
super::dedicated::log(
"INFO",
@@ -758,6 +835,7 @@ impl Game<'_> {
self.lan_crafting_left(&mut host, &mut guest);
self.save_guest(&host, &guest);
host.models.remove(&guest.conn);
host.play.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
super::dedicated::log(
"INFO",
@@ -782,9 +860,11 @@ impl Game<'_> {
}
self.lan_flush_effects(&mut host);
self.tick_guests(&mut host);
self.tick_server_travel(&mut host);
self.lan_swings(&mut host);
self.lan_update_streaming(&host);
self.lan_update_models(&mut host);
self.lan_update_waypoints(&mut host, state.as_ref());
drop(holding);
for g in &host.hub.guests {
g.sender.flush();
@@ -826,6 +906,7 @@ impl Game<'_> {
g.health = 20.0;
g.food = 20;
}
self.load_guest_records(host, conn);
let mut ctx = TickCtx {
world: &mut self.world,
host: state,
+60 -1
View File
@@ -51,6 +51,9 @@ pub(super) struct GuestPlay {
pub(super) crafting: super::lan_crafting::GuestCrafting,
/// 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.
pub(super) stats: super::stats::Stats,
last_inventory: u64,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -165,6 +168,15 @@ impl Game<'_> {
let host_ender = self.ender_open;
self.close_ender_chest();
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
// The guest's advancements, recipe book and statistics.
self.advancement_tree();
std::mem::swap(&mut self.adv.progress, &mut g.advancements);
std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed);
std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked);
std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book);
std::mem::swap(&mut self.stats, &mut play.stats);
let adv_loaded = std::mem::replace(&mut self.adv.loaded, true);
let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory);
self.lan_acting = Some(conn);
self.lan_acting_name = Some(g.name.clone());
self.lan_acting_uuid = Some(g.uuid);
@@ -200,6 +212,15 @@ impl Game<'_> {
}
let g = &mut host.hub.guests[i];
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
std::mem::swap(&mut self.adv.progress, &mut g.advancements);
std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed);
std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked);
std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book);
std::mem::swap(&mut self.stats, &mut play.stats);
self.adv.loaded = adv_loaded;
play.last_inventory = std::mem::replace(&mut self.adv.last_inventory, last_inventory);
let stat_events = std::mem::take(&mut play.stats.events);
let name = g.name.clone();
self.potions.swap_player(&mut g.effects, &mut play.potions);
if let Some(key) = host_ender {
self.world
@@ -244,6 +265,7 @@ impl Game<'_> {
host.hub.set_game_mode(conn, new_mode);
}
host.play.insert(conn, play);
self.stat_criteria_changed(&name, stat_events);
if let Some(pos) = opened
&& !self.lan_open_container(host, conn, pos)
&& !host.hub.guests[i].spectator()
@@ -642,6 +664,15 @@ impl Game<'_> {
self.guest_suggestions(host, conn, &payload);
}
S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn),
// ServerStatsCounter.sendStats.
S::ClientCommand(c) if c.action == 1 => {
let stats = host
.play
.get_mut(&conn)
.map(|p| p.stats.take_dirty())
.unwrap_or_default();
host.hub.send_stats(conn, &stats);
}
S::PickItemFromBlock(p) => {
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
let item = self.res.facts.get(state).item.clone();
@@ -879,6 +910,7 @@ impl Game<'_> {
if !host.hub.guests[i].dead {
return;
}
self.respawn_level(host);
let g = &mut host.hub.guests[i];
g.dead = false;
g.health = 20.0;
@@ -919,6 +951,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.announce_guest_advancements(host);
let conns: Vec<u32> = host
.hub
.guests
@@ -930,7 +963,7 @@ impl Game<'_> {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
continue;
};
if host.hub.guests[gi].dead {
if host.hub.guests[gi].dead || self.on_server_trip(conn) {
continue;
}
let play = host.play.entry(conn).or_default();
@@ -962,6 +995,14 @@ impl Game<'_> {
}
self.guest_delayed_destroy(host, conn);
self.guest_server_tick(host, conn);
// Player.tick's statistics and ServerPlayer.tick's triggers, then
// PlayerAdvancements.flushDirty.
let sleeping = host.hub.guests[gi].sleeping;
self.as_guest(host, conn, |g| {
g.count_tick_stats(sleeping);
g.tick_advancements();
});
host.hub.flush_progress(conn);
self.guest_dig_feedback(host, conn);
self.guest_pickups(host, gi);
let g = &mut host.hub.guests[gi];
@@ -987,6 +1028,18 @@ impl Game<'_> {
}
}
/// `PlayerList.broadcastSystemMessage` of the advancements guests made
/// (their own actions, commands and ticks).
fn announce_guest_advancements(&mut self, host: &mut LanHost) {
for text in std::mem::take(&mut self.adv.announced) {
host.hub
.system_message(horizon_client::lan::data::component_nbt(&text.component()));
if self.options.dedicated.is_none() {
self.system_message(text);
}
}
}
/// The guest's body on the server each tick: ServerPlayer.tick's damage
/// clock and Entity.baseTick's fluid phase (burning), then for each move
/// the guest made ServerGamePacketListenerImpl.handleMovePlayer's jump
@@ -1034,6 +1087,7 @@ impl Game<'_> {
w.player.health.advance_clock();
let _ = w.fluid_base_tick();
w.player.ground.on_ground = from_ground;
let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect();
for (moved, on_ground) in moves {
let movement = Vec3::new(moved[0], moved[1], moved[2]);
if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 {
@@ -1058,6 +1112,11 @@ impl Game<'_> {
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
let mut events = std::mem::take(&mut w.player.events);
// ServerGamePacketListenerImpl.handleMovePlayer:
// Player.checkMovementStatistics for each move.
for d in travelled {
game.movement_stats(Vec3::new(d[0], d[1], d[2]));
}
// LivingEntity.baseTick ends with tickEffects.
game.tick_mob_effects();
let Some(player) = game.player.as_mut() else {
+8 -1
View File
@@ -19,6 +19,7 @@ pub(super) struct Strike {
scale: f32,
crit: bool,
from: [f64; 3],
sweep: Option<[f64; 3]>,
}
impl Game<'_> {
@@ -73,6 +74,7 @@ impl Game<'_> {
let p = self.player.as_ref()?;
let from = [p.position.x, p.position.y, p.position.z];
let (amount, scale, crit) = self.melee_damage("minecraft:player");
let sweep = self.sweep_attack_position(scale, crit);
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
@@ -85,6 +87,7 @@ impl Game<'_> {
scale,
crit,
from,
sweep,
})
}
@@ -105,6 +108,10 @@ impl Game<'_> {
(true, false, true) => "minecraft:entity.player.attack.strong",
(true, false, false) => "minecraft:entity.player.attack.weak",
};
self.audio.play(sound, Some(s.from), 1.0, 1.0);
if let Some(at) = s.sweep.filter(|_| hurt) {
self.sweep_attack(at, Some(s.from));
} else {
self.audio.play(sound, Some(s.from), 1.0, 1.0);
}
}
}
@@ -0,0 +1,95 @@
//! The locator bar of the players on a served world (lan/waypoints.rs): what
//! each player looks like to the waypoint manager this tick.
use super::{Game, lan::LanHost};
use horizon_client::{
items::ItemStack,
lan::{
hub::HostState,
waypoints::{self, HIDING_HEADS, Icon, PLAYER_RANGE},
},
};
/// `waypoint_transmit_range`: hidden by crouching, invisibility or a head worn.
fn transmit_range(crouching: bool, invisible: bool, head: Option<&ItemStack>) -> f64 {
let hiding_head = head.is_some_and(|s| HIDING_HEADS.contains(&&*s.item));
if crouching || invisible || hiding_head {
0.0
} else {
PLAYER_RANGE
}
}
impl Game<'_> {
/// The player's team and its colour, as the locator bar shows it.
fn waypoint_team(&self, name: &str) -> Option<(String, Option<i32>)> {
let team = self.score.board.players_team(name)?;
let color = team.color.as_deref().and_then(waypoints::team_rgb);
Some((team.name.clone(), color))
}
pub(super) fn lan_update_waypoints(&mut self, host: &mut LanHost, state: Option<&HostState>) {
let mut players = Vec::new();
if let Some(h) = state {
let icon = self
.cmds
.waypoint_icons
.get(&super::commands::Target::Player)
.map(|i| Icon {
style: i.style.clone(),
color: i.color,
})
.unwrap_or_default();
players.push(waypoints::Player {
uuid: h.uuid,
conn: None,
position: h.position,
spectator: self.spectator(),
transmit_range: transmit_range(
h.sneaking,
self.potions.effects.get("invisibility").is_some(),
h.equipment[5].as_ref(),
),
receive_range: PLAYER_RANGE,
first_tick: false,
view_distance: host.hub.config.view_distance,
team: self.waypoint_team(&h.name),
icon,
});
}
let mut respawned = Vec::new();
for g in host.hub.guests.iter().filter(|g| g.placed) {
// PlayerList.respawn makes a new ServerPlayer.
if g.dead {
host.waypoint_dead.insert(g.uuid);
} else if host.waypoint_dead.remove(&g.uuid) {
respawned.push(g.uuid);
}
// Player.updatePlayerPose: the shift key crouches unless flying.
let crouching = g.sneaking && !g.flying && !g.fall_flying && !g.sleeping;
players.push(waypoints::Player {
uuid: g.uuid,
conn: Some(g.conn),
position: g.position,
spectator: g.spectator(),
transmit_range: transmit_range(
crouching,
g.effects.get("invisibility").is_some(),
g.armor[0].as_ref(),
),
receive_range: PLAYER_RANGE,
first_tick: g.ticks == 0,
view_distance: g.view_distance,
team: self.waypoint_team(&g.name),
icon: Icon::default(),
});
}
host.waypoint_dead
.retain(|uuid| players.iter().any(|p| p.uuid == *uuid));
let locator_bar = self.ui.rules.bool("locator_bar");
for (conn, packet) in host.waypoints.tick(&players, &respawned, locator_bar) {
if let Some(g) = host.hub.guest(conn) {
g.send(&packet);
}
}
}
}
+84 -16
View File
@@ -92,13 +92,13 @@ impl Game<'_> {
}
}
/// `ServerLevel.isAllowedToEnterPortal`.
fn may_enter(&self, target: Dim) -> bool {
pub(super) fn may_enter(&self, target: Dim) -> bool {
target != Dim::Nether || self.ui.rules.bool("allow_entering_nether_using_portals")
}
/// The plan of an entity of `width` by `height` at `at` going through the
/// portal at `entry` (`getDimensionTransitionFromExit` and the scaled,
/// clamped exit of `getPortalDestination`).
fn portal_plan(
pub(super) fn portal_plan(
&self,
entry: BlockPos,
at: Vec3,
@@ -195,7 +195,7 @@ impl Game<'_> {
}
/// The exit portal of `plan` in the loaded dimension: the closest one
/// within reach, else one built by `PortalForcer.createPortal`.
fn nether_exit_portal(&mut self, plan: &Plan) -> Option<FoundRectangle> {
pub(super) fn nether_exit_portal(&mut self, plan: &Plan) -> Option<FoundRectangle> {
let to_nether = plan.dim == Dim::Nether;
let radius = if to_nether { 16 } else { 128 };
let border = self.border_bounds();
@@ -231,7 +231,7 @@ impl Game<'_> {
}
/// `NetherPortalBlock.createDimensionTransition`: the arrival position
/// and the yaw turned by.
fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) {
pub(super) fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) {
let b = &self.res.behaviours;
let corner = exit.min_corner;
let exit_x_axis = b
@@ -312,8 +312,16 @@ impl Game<'_> {
self.portals.travel = Some(plan);
self.end_portal_travel = false;
self.enter_dimension(plan.dim)?;
// The destination is all on disk now: load around the portal its
// points of interest lead to, or the approximate exit.
let centre = self.arrival_centre(&plan);
if let Some((_, target)) = self.travelling.as_mut() {
*target = centre;
}
Ok(())
}
/// Where to wait for the destination of `plan` to load, once its level
/// is open: the portal its points of interest lead to, or the
/// approximate exit.
pub(super) fn arrival_centre(&self, plan: &Plan) -> Vec3 {
let to_nether = plan.dim == Dim::Nether;
let portals = self.portal_blocks(plan.approximate, if to_nether { 16 } else { 128 });
let (min_section, max_section) = if to_nether { (0, 15) } else { (-4, 19) };
@@ -327,14 +335,11 @@ impl Game<'_> {
max_section,
);
let centre = found.unwrap_or(plan.approximate);
if let Some((_, target)) = self.travelling.as_mut() {
*target = Vec3::new(
f64::from(centre.x) + 0.5,
f64::from(centre.y),
f64::from(centre.z) + 0.5,
);
}
Ok(())
Vec3::new(
f64::from(centre.x) + 0.5,
f64::from(centre.y),
f64::from(centre.z) + 0.5,
)
}
/// The player's arrival once the destination has loaded around the
/// approximate exit: the waiting entities first, then the exit portal
@@ -481,9 +486,10 @@ impl Game<'_> {
.filter(|m| self.mob_can_use_portal(m))
.map(|m| (m.id, m.position, m.width(), m.height()))
.collect();
let mut portal_sections = horizon_client::fast_hash::FxHashMap::default();
for (id, to, width, height) in items.into_iter().chain(mobs) {
let from = self.portals.before.get(&id).copied().unwrap_or(to);
if let Some(pos) = self.swept_portal(from, to, width, height) {
if let Some(pos) = self.swept_portal(from, to, width, height, &mut portal_sections) {
inside.push((id, pos));
}
}
@@ -497,7 +503,14 @@ impl Game<'_> {
}
/// The first nether portal block an entity box swept through
/// (`Entity.checkInsideBlocks`, whose first portal sets the entry).
fn swept_portal(&self, from: Vec3, to: Vec3, width: f32, height: f32) -> Option<BlockPos> {
fn swept_portal(
&self,
from: Vec3,
to: Vec3,
width: f32,
height: f32,
portal_sections: &mut horizon_client::fast_hash::FxHashMap<(i32, i32, i32), bool>,
) -> Option<BlockPos> {
let half = f64::from(width) / 2.0;
let bounds = horizon_core::geometry::Aabb::new(
Vec3::new(to.x - half, to.y, to.z - half),
@@ -508,6 +521,13 @@ impl Game<'_> {
f64::from(1.0e-5_f32),
f64::from(1.0e-5_f32),
));
// Every block the sweep visits lies in the box covering both ends.
let reach = bounds
.union_bounds(bounds.move_by(from.subtract(to)))
.inflate(Vec3::new(1.0, 1.0, 1.0));
if !self.may_hold_portal(reach, portal_sections) {
return None;
}
let mut found = None;
let _ = horizon_core::geometry::sweep_intersected_blocks(
from,
@@ -529,6 +549,54 @@ impl Game<'_> {
);
found
}
/// Whether a section `reach` touches has a nether portal state in its
/// palette: without one, no block there is a portal. Answers are kept
/// per section for the tick; a box over many sections is not checked.
fn may_hold_portal(
&self,
reach: horizon_core::geometry::Aabb,
seen: &mut horizon_client::fast_hash::FxHashMap<(i32, i32, i32), bool>,
) -> bool {
use horizon_client::chunk::{MIN_Y, SECTIONS};
let (min, max) = (reach.min_position(), reach.max_position());
if !min.is_finite() || !max.is_finite() {
return true;
}
let (min, max) = (BlockPos::containing(min), BlockPos::containing(max));
let top = SECTIONS as i32 - 1;
let (x0, x1) = (min.x >> 4, max.x >> 4);
let (z0, z1) = (min.z >> 4, max.z >> 4);
let (y0, y1) = (
((min.y - MIN_Y) >> 4).clamp(0, top),
((max.y - MIN_Y) >> 4).clamp(0, top),
);
let count = (i64::from(x1) - i64::from(x0) + 1)
* (i64::from(y1) - i64::from(y0) + 1)
* (i64::from(z1) - i64::from(z0) + 1);
if count > 64 {
return true;
}
let behaviours = &self.res.behaviours;
let chunks = &self.world.chunks;
(x0..=x1).any(|cx| {
(z0..=z1).any(|cz| {
(y0..=y1).any(|sy| {
*seen.entry((cx, sy, cz)).or_insert_with(|| {
chunks
.get(&(cx, cz))
.and_then(|c| c.sections.get(sy as usize))
.is_some_and(|s| {
s.blocks.maybe_has(|v| {
behaviours
.portal_axis(horizon_world::registry::BlockStateId(v))
.is_some()
})
})
})
})
})
})
}
/// `Entity.teleportCrossDimension` away from the loaded dimension: the
/// entity is saved and removed, and waits for its dimension to load.
fn send_through_portal(&mut self, id: u32, entry: BlockPos) {
+12 -1
View File
@@ -201,7 +201,7 @@ impl Game<'_> {
)
};
let p = self.player.as_ref()?;
let sleeping = self.sleeping.map(|(head, _)| {
let sleeping = self.sleeping.map(|head| {
let state = self.world.block(head[0], head[1], head[2]);
let props = self
.pack
@@ -313,6 +313,15 @@ impl Game<'_> {
.map_or(25, |s| Self::charge_ticks(s).max(1)) as i32;
let attack = (self.swing.old_animation, self.swing.animation);
let swinging = self.swing.swinging();
// currentSwing.hand().asArm(mainArm).
let swing_right_arm = swinging.then(|| {
(self.swing.attack_hand() == horizon_client::first_person::Hand::Main)
!= self.settings.main_hand_left
});
// LivingEntity.isVisuallySwimming and Entity.isInWater.
let visually_swimming =
p.pose == Pose::Swimming || (!p.fall_flying && p.pose == Pose::FallFlying);
let in_water = p.fluids.was_touching_water;
let (yaw, pitch) = (self.yaw, self.pitch);
let main = self.inventory[self.selected]
.as_ref()
@@ -378,6 +387,8 @@ impl Game<'_> {
m.extra.charged = charged;
m.extra.ints[5] = charge_duration;
m.extra.elytra.tick(fall_flying, crouching, velocity);
m.extra.swim.tick(visually_swimming, in_water);
m.extra.swing_right_arm = swing_right_arm;
m.hurt_time = hurt;
}
/// Whether the player's own model shows in the world view.
+235 -13
View File
@@ -136,6 +136,8 @@ pub(super) struct Remote {
decode_errors: u32,
clock: Option<i32>,
clock_rate: f32,
/// `ClientChunkCache.Storage`'s view centre (ClientboundSetChunkCacheCenterPacket).
chunk_center: (i32, i32),
}
fn face_direction(face: [i32; 3]) -> u8 {
@@ -312,7 +314,13 @@ impl Game<'_> {
decode_errors: 0,
clock: None,
clock_rate: 1.0,
chunk_center: (0, 0),
});
// The level's TickRateManager follows the server's ticking packets.
self.clock = horizon_client::clock::FixedStep::client();
// The player's advancements and statistics are the server's.
self.adv = Default::default();
self.stats = Default::default();
Ok(())
}
@@ -335,6 +343,9 @@ impl Game<'_> {
None => false,
};
horizon_client::crash::clear_detail("Server");
self.clock = Default::default();
self.adv = Default::default();
self.stats = Default::default();
self.debug_charts.reset();
self.tab_list.reset();
self.score.board = Default::default();
@@ -554,11 +565,7 @@ impl Game<'_> {
r.loaded_sent = false;
r.predictions.clear();
self.set_mode_id(spawn.game_type);
self.dim = if spawn.dimension == "minecraft:the_nether" {
Dim::Nether
} else {
Dim::Overworld
};
self.dim = Dim::from_id(&spawn.dimension);
if !same {
let mut streaming = Streaming::new(
Arc::new(NoTerrain),
@@ -585,6 +592,8 @@ impl Game<'_> {
r.entities.clear();
r.lerps.clear();
r.pending_items.clear();
// A new ClientLevel: a new chunk storage, centred on 0, 0.
r.chunk_center = (0, 0);
}
if let Some(renderer) = self.renderer.as_mut() {
renderer.clear_sections();
@@ -681,6 +690,128 @@ impl Game<'_> {
}
Ok(chunk)
}
/// `ClientChunkCache.Storage.inRange`: within the storage around the
/// view centre, `calculateStorageRange` (the server's radius, at least
/// two, plus three) chunks each way.
fn remote_chunk_in_range(&self, x: i32, z: i32) -> bool {
self.remote.as_ref().is_none_or(|r| {
let range = r.view_distance.max(2) + 3;
(x - r.chunk_center.0).abs() <= range && (z - r.chunk_center.1).abs() <= range
})
}
/// The columns a moved or resized storage no longer holds.
fn drop_remote_chunks_out_of_range(&mut self) {
let gone: Vec<(i32, i32)> = self
.world
.chunks
.keys()
.copied()
.filter(|&(x, z)| !self.remote_chunk_in_range(x, z))
.collect();
for (x, z) in gone {
self.streaming.forget(&mut self.world, x, z);
self.world
.block_entities
.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z));
if let Some(renderer) = self.renderer.as_mut() {
for sy in 0..SECTIONS as i32 {
renderer.remove((x, sy, z));
}
}
}
}
/// `handleBlockEntityData`: the block entity at `pos`, when it is of the
/// packet's type, loads the tag (`loadWithComponents`); an empty tag
/// changes nothing.
fn remote_block_entity_data(&mut self, pos: [i32; 3], kind: i32, tag: &Tag) {
let key = (pos[0], pos[1], pos[2]);
let Some(name) = self
.remote
.as_ref()
.and_then(|r| r.builtin.get("minecraft:block_entity_type")?.name(kind))
else {
return;
};
let Some(entity) = self.world.block_entities.get(&key) else {
return;
};
let Tag::Compound(fields) = tag else {
return;
};
if entity.id() != name || fields.is_empty() {
return;
}
let mut full = fields.clone();
full.insert("id".into(), Tag::String(name.into()));
for (k, v) in ["x", "y", "z"].into_iter().zip(pos) {
full.insert(k.into(), Tag::Int(v));
}
if let Some((_, loaded)) = horizon_client::save::decode_block_entity(&Tag::Compound(full)) {
self.world.block_entities.insert(key, loaded);
// The section is drawn again with what the block entity shows.
let state = self.world.block(pos[0], pos[1], pos[2]);
let _ = self.world.set(pos[0], pos[1], pos[2], state);
}
}
/// `handleAnimate`: a player wakes up, or an entity gets the critical
/// hit (`CRIT`) or magic critical hit (`ENCHANTED_HIT`) emitter.
fn remote_animate(&mut self, id: i32, action: u8) {
use horizon_client::particles::{ParticleOptions, ParticleType};
let me = self.remote.as_ref().is_some_and(|r| r.entity_id == id);
let body = if me {
self.player.as_ref().map(|p| {
let d = p.dimensions;
(
[p.position.x, p.position.y, p.position.z],
f64::from(d.width),
f64::from(d.height),
)
})
} else {
self.mobs.iter().find(|m| m.id == id as u32).map(|m| {
(
[m.position.x, m.position.y, m.position.z],
m.kind.width,
m.kind.height,
)
})
};
let Some((feet, width, height)) = body else {
return;
};
let particle = match action {
// Player.stopSleepInBed.
0 => {
if me {
self.sleeping = None;
}
return;
}
1 => ParticleType::Crit,
2 => ParticleType::EnchantedHit,
_ => return,
};
self.particles
.tracking_emitter(ParticleOptions::simple(particle), feet, width, height);
}
/// `handleServerData`: the server list entry of the server joined keeps
/// the icon the server sends (`ServerList.saveSingleServer`). Single
/// player has no entry.
fn remote_server_data(&mut self, icon: Option<&[u8]>) {
let (Some(r), Some(png)) = (self.remote.as_ref(), icon) else {
return;
};
if self.integrated.is_some() {
return;
}
if let Ok(dir) = std::env::current_dir() {
horizon_client::multiplayer::save_server_icon(
&dir.join("saves"),
&r.session.address,
png,
);
}
}
/// Keep the renderable block entities (chests, furnaces) in step with blocks.
fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) {
let name = self.res.facts.get(state).name.clone();
@@ -947,6 +1078,15 @@ impl Game<'_> {
})
.clamp(-90.0, 90.0);
}
// ClientChunkCache.replaceWithPacketData: a column outside the
// storage around the view centre is ignored.
C::LevelChunkWithLight(p) if !self.remote_chunk_in_range(p.x, p.z) => {
log::warn!(
"Ignoring chunk since it's not in the view range: {}, {}",
p.x,
p.z
);
}
C::LevelChunkWithLight(p) => match self.remote_chunk(&p) {
Ok(chunk) => {
let (x, z) = (p.x, p.z);
@@ -962,6 +1102,8 @@ impl Game<'_> {
);
let state = self.world.block(pos.0, pos.1, pos.2);
self.sync_block_entity(pos, state);
// LevelChunk.replaceWithPacketData: the block entity loads its update tag.
self.remote_block_entity_data([pos.0, pos.1, pos.2], info.kind, &info.tag);
}
}
Err(e) => log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z),
@@ -1245,7 +1387,7 @@ impl Game<'_> {
m.health = 0.0;
}
}
C::Animate(p) if p.action == 0 => {}
C::Animate(p) => self.remote_animate(p.id, p.action),
C::UpdateMobEffect(p) => self.remote_effect(&p),
C::RemoveMobEffect(p) => {
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
@@ -1277,9 +1419,16 @@ impl Game<'_> {
.map(|r| r.lang.clone())
.unwrap_or_default();
let message = plain(&p.message, &lang);
let me = self.remote.as_ref().is_some_and(|r| r.entity_id == p.id);
if let Some(r) = self.remote.as_mut() {
r.death_message = Some(message);
}
// ClientPacketListener.handlePlayerCombatKill: the death
// screen, whatever health was last sent.
if me && self.screen != Screen::Dead && self.player.is_some() {
self.screen = Screen::Dead;
self.capture(false);
}
}
C::SetExperience(p) => {
self.experience = Experience {
@@ -1580,6 +1729,68 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.view_distance = p.distance;
}
// ClientChunkCache.updateViewRadius: a new storage of that size.
self.drop_remote_chunks_out_of_range();
}
C::SetChunkCacheCenter(p) => {
if let Some(r) = self.remote.as_mut() {
r.chunk_center = (p.x, p.z);
}
self.drop_remote_chunks_out_of_range();
}
C::BlockEntityData(p) => self.remote_block_entity_data(p.pos, p.kind, &p.tag),
// handleSetSpawn: ClientLevel.setRespawnData, which spawn compasses point at.
C::SetDefaultSpawnPosition(p) => {
let [x, y, z] = p.pos.pos;
self.spawn = (p.pos.dimension == "minecraft:overworld")
.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()),
// handleTickingState / handleTickingStep: the level's TickRateManager.
C::TickingState(p) => {
self.clock.set_rate(p.rate);
self.clock.set_frozen(p.frozen);
}
C::TickingStep(p) => self.clock.set_frozen_ticks_to_run(p.steps),
C::UpdateAdvancements(p) => {
let icons = p
.added
.iter()
.map(|a| {
a.display
.as_ref()
.map_or_else(String::new, |d| self.item_name(d.icon.item).to_string())
})
.collect();
self.remote_advancements(p, icons);
}
// handleAwardStats: StatsCounter.setValue for each.
C::AwardStats(p) => {
let Some(r) = self.remote.as_ref() else {
return Ok(());
};
let mut known = Vec::new();
for (ty, value, count) in p.stats {
let Some(ty) = r
.builtin
.get("minecraft:stat_type")
.and_then(|t| t.name(ty))
else {
continue;
};
let values = match ty {
"minecraft:mined" => "minecraft:block",
"minecraft:killed" | "minecraft:killed_by" => "minecraft:entity_type",
"minecraft:custom" => "minecraft:custom_stat",
_ => "minecraft:item",
};
if let Some(key) = r.builtin.get(values).and_then(|v| v.name(value)) {
known.push((ty.to_owned(), key.to_owned(), count));
}
}
for (ty, key, count) in known {
self.stats.values.entry(ty).or_default().insert(key, count);
}
}
C::SetActionBarText(p) | C::SetTitleText(p) => {
let lang = self
@@ -1912,10 +2123,15 @@ impl Game<'_> {
/// One client tick while connected (Minecraft.tick with a ClientLevel).
pub(super) fn tick_remote(&mut self) -> Result<()> {
self.ticks += 1;
self.world.game_time += 1;
let rate = self.remote.as_ref().map_or(1.0, |r| r.clock_rate);
if rate > 0.0 {
self.world.day_time += rate.round() as i64;
// Minecraft.tick: TickRateManager.tick; ClientLevel.tick advances
// the time only while the level runs normally.
let running = self.clock.world_runs();
if running {
self.world.game_time += 1;
let rate = self.remote.as_ref().map_or(1.0, |r| r.clock_rate);
if rate > 0.0 {
self.world.day_time += rate.round() as i64;
}
}
// Weather levels drift toward their targets between server updates.
let w = &mut self.world.weather;
@@ -1926,7 +2142,7 @@ impl Game<'_> {
}
// ClientLevel.tick: the border's size change.
self.border.tick();
self.tick_remote_entities();
self.tick_remote_entities(running);
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells.
self.tick_block_entity_anims();
self.tick_hand();
@@ -2037,12 +2253,18 @@ impl Game<'_> {
self.send(S::ClientTickEnd(Empty));
Ok(())
}
fn tick_remote_entities(&mut self) {
/// ClientLevel.tickEntities; a frozen level only ticks the players
/// (`TickRateManager.isEntityFrozen`).
fn tick_remote_entities(&mut self, running: bool) {
let Some(r) = self.remote.as_mut() else {
return;
};
let mut lerps = std::mem::take(&mut r.lerps);
let players = &r.level_players;
for m in &mut self.mobs {
if !running && !players.contains_key(&(m.id as i32)) {
continue;
}
m.previous = m.position;
m.previous_yaw = m.yaw;
m.previous_body_yaw = m.body_yaw;
@@ -2080,7 +2302,7 @@ impl Game<'_> {
horizon_client::mobs::rabbit::post_tick(m);
}
}
for d in &mut self.dropped {
for d in self.dropped.iter_mut().filter(|_| running) {
d.previous = d.position;
d.age += 1;
if let Some(l) = lerps.get_mut(&(d.id as i32))
+22 -8
View File
@@ -303,20 +303,33 @@ impl Game<'_> {
// ---- criteria ----------------------------------------------------------
/// `ServerStatsCounter.setValue`'s scoreboard side: the objectives of
/// each changed statistic's criteria follow it for the player `name`.
pub(super) fn stat_criteria_changed(
&mut self,
name: &str,
events: Vec<(String, String, Option<i32>)>,
) {
let board = &mut self.score.board;
if board.objectives.is_empty() {
return;
}
for (ty, key, amount) in events {
let criteria = sb::stat_criteria(&ty, &key);
if board.has_objectives_for(&criteria) {
board.for_all_objectives(&criteria, name, |v| {
amount.map_or(0, |n| v.wrapping_add(n))
});
}
}
}
/// `ServerPlayer.doTick` score updates and the statistic criteria.
pub(super) fn tick_scoreboard(&mut self) {
self.load_scoreboard();
let events = std::mem::take(&mut self.stats.events);
self.stat_criteria_changed(PLAYER_NAME, events);
let board = &mut self.score.board;
if !board.objectives.is_empty() {
for (ty, key, amount) in events {
let criteria = sb::stat_criteria(&ty, &key);
if board.has_objectives_for(&criteria) {
board.for_all_objectives(&criteria, PLAYER_NAME, |v| {
amount.map_or(0, |n| v.wrapping_add(n))
});
}
}
let display = self.player_display_comp();
if let Some(p) = self.player.as_mut() {
let health_and_absorption = p.health.health() + p.health.absorption();
@@ -735,6 +748,7 @@ mod tab_list_tests {
conn: uuid as u32,
uuid,
name: name.into(),
properties: Vec::new(),
info: ClientInformation::new(8),
brand: "test".into(),
sender: PlayerSender::new(tx, Arc::default()),
@@ -288,6 +288,8 @@ impl Game<'_> {
if hit == Some(0) && self.remote.is_none() {
let keep = self.ui.rules.bool("keep_inventory") || self.spectator();
self.experience.respawn(keep);
// Autosaves keep a login position; death must resolve the respawn point instead.
self.level.position = None;
}
match hit {
Some(0) if self.remote.is_some() => {
+5
View File
@@ -373,6 +373,11 @@ impl Game<'_> {
let mut found = Vec::new();
for (s, section) in chunk.sections.iter().enumerate() {
let y0 = MIN_Y + s as i32 * 16;
// Without a sculk state in its palette, no block of the section
// is one: most sections are passed over without reading a block.
if !section.blocks.maybe_has(|v| self.kind_of_state(v) != 0) {
continue;
}
if section.blocks.uniform().is_some() {
// A uniform section of sculk blocks does not exist.
continue;
@@ -0,0 +1,248 @@
//! A server's player between dimensions.
//!
//! The server holds one level at a time, as the in-frame game does. While a
//! single player is online (single player on the server thread, or a world
//! with one player in it) that level follows the player through Nether and
//! End portals, and back to the Overworld when the player respawns. The swap
//! is the in-frame path's (`switch_level`, the portal plans, the arrival
//! search); the player hears it as `ServerPlayer.teleport` into another
//! level: a Respawn packet keeping all data, then a teleport to the exit once
//! the destination has loaded. With several players online the portals do
//! not take anyone yet: that needs the server to hold every level.
use super::nether_portal::PLAYER_DELAY;
use super::{Dim, Game, lan::LanHost};
use horizon_client::lan::hub::TickCtx;
use horizon_core::{geometry::Vec3, position::BlockPos};
/// A trip under way: the level has changed and its chunks are loading
/// around `target`.
pub(super) struct Trip {
conn: u32,
target: Vec3,
/// Through an End portal (or out of the End by respawning).
end: bool,
}
/// The lone player's box: Player's standing dimensions.
const WIDTH: f64 = 0.6;
const HEIGHT: f64 = 1.8;
impl Game<'_> {
/// Whether `conn` is between two levels: the server leaves its body
/// alone until it arrives.
pub(super) fn on_server_trip(&self, conn: u32) -> bool {
self.server_trip.as_ref().is_some_and(|t| t.conn == conn)
}
/// Per server tick, after the guests' own: `Entity.handlePortal` for the
/// lone player (Nether portals count up their transition time, End
/// portals take it at once), or the arrival of the trip under way.
pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) {
if self.options.dedicated.is_none() {
return;
}
if self.server_trip.is_some() {
self.arrive_server_trip(host);
return;
}
let [g] = host.hub.guests.as_slice() else {
return;
};
if !g.placed || !g.loaded || g.dead || g.spectator() {
return;
}
let (conn, at, invulnerable, sleeping) = (
g.conn,
Vec3::new(g.position[0], g.position[1], g.position[2]),
g.creative(),
g.sleeping,
);
// Entity.checkInsideBlocks: the Nether portal blocks the box is in.
if let Some(pos) = self.nether_portal_inside(at) {
self.portals.player.set_inside(pos, PLAYER_DELAY);
}
let (end_portal, _) = self.inside_end_portals(at, WIDTH, HEIGHT);
if end_portal {
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
Dim::Overworld
} else {
Dim::End
};
self.start_server_trip(host, conn, target, true);
}
// Entity.setAsInsidePortal while cooling down restarts the cooldown.
self.portals.player.cooldown = 10;
return;
}
let rule = if invulnerable {
"players_nether_portal_creative_delay"
} else {
"players_nether_portal_default_delay"
};
let transition = self.ui.rules.int(rule).max(0);
let Some(entry) = self
.portals
.player
.handle(!sleeping, transition, PLAYER_DELAY)
else {
return;
};
let plan = self.portal_plan(entry, at, WIDTH as f32, HEIGHT as f32, true);
if !self.may_enter(plan.dim) {
return;
}
self.portals.travel = Some(plan);
self.start_server_trip(host, conn, plan.dim, false);
}
/// A Nether portal block the lone player's box is in.
fn nether_portal_inside(&self, at: Vec3) -> Option<BlockPos> {
let w = WIDTH / 2.0 - 1.0e-5;
let lo = [at.x - w, at.y + 1.0e-5, at.z - w];
let hi = [at.x + w, at.y + HEIGHT - 1.0e-5, at.z + w];
for x in lo[0].floor() as i32..=hi[0].floor() as i32 {
for y in lo[1].floor() as i32..=hi[1].floor() as i32 {
for z in lo[2].floor() as i32..=hi[2].floor() as i32 {
if &*self.block_name([x, y, z]) == "minecraft:nether_portal" {
return Some(BlockPos::new(x, y, z));
}
}
}
}
None
}
/// The level swap, and the player told it is in the new level at the
/// approximate exit while it loads.
fn start_server_trip(&mut self, host: &mut LanHost, conn: u32, target: Dim, end: bool) {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let g = &host.hub.guests[i];
let from = Vec3::new(g.position[0], g.position[1], g.position[2]);
let yaw = g.yaw;
let source = self.dim;
self.end_portal_travel = end;
let switched = self.switch_level(target, from);
self.end_portal_travel = false;
let destination = match switched {
Ok(d) => d,
Err(e) => {
log::error!("could not open {}: {e}", target.id());
return;
}
};
let destination = match self.portals.travel {
Some(plan) if !end => self.arrival_centre(&plan),
_ => destination,
};
host.hub.set_dimension(target.id());
let at = [destination.x, destination.y, destination.z];
let ctx = self.server_ctx();
host.hub.change_level(i, at, yaw, &ctx);
self.as_guest(host, conn, |g| g.trigger_dimension(source, target));
self.server_trip = Some(Trip {
conn,
target: destination,
end,
});
}
/// Once the destination has loaded around the trip's target: the exit
/// (the Nether portal found or built, the End platform, the Overworld's
/// spawn column) and the teleport there.
fn arrive_server_trip(&mut self, host: &mut LanHost) {
let Some(trip) = self.server_trip.as_ref() else {
return;
};
let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else {
// They left on the way.
self.server_trip = None;
self.portals.travel = None;
return;
};
let (cx, cz) = (
(trip.target.x.floor() as i32) >> 4,
(trip.target.z.floor() as i32) >> 4,
);
if !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
return;
}
let Some(trip) = self.server_trip.take() else {
return;
};
self.resolve_arrivals();
let (position, yaw) = if trip.end {
match self.end_arrival(trip.target) {
Ok((at, yaw)) => (at, yaw.unwrap_or(host.hub.guests[i].yaw)),
Err(e) => {
log::error!("End arrival: {e}");
(trip.target, host.hub.guests[i].yaw)
}
}
} else {
let plan = self.portals.travel.take();
let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan));
match (plan, exit) {
(Some(plan), Some(exit)) => {
let (at, rotation) = self.arrival(&plan, exit);
(at, host.hub.guests[i].yaw + rotation)
}
_ => (trip.target, host.hub.guests[i].yaw),
}
};
// Player.getDimensionChangingDelay.
self.portals.player.cooldown = 10;
let g = &mut host.hub.guests[i];
g.yaw = yaw;
// A new body at the exit: no fall distance or motion carried over.
g.motion = None;
host.hub
.teleport(i, Some([position.x, position.y, position.z]));
}
/// `PlayerList.respawn` away from the Overworld: the lone player's level
/// goes back to the Overworld first, where the world spawn is.
pub(super) fn respawn_level(&mut self, host: &mut LanHost) {
if self.options.dedicated.is_none() || self.dim == Dim::Overworld {
return;
}
if host.hub.guests.len() != 1 {
return;
}
self.server_trip = None;
self.portals.travel = None;
self.end_portal_travel = true;
let from = self.spawn.unwrap_or(Vec3::ZERO);
let switched = self.switch_level(Dim::Overworld, from);
self.end_portal_travel = false;
if let Err(e) = switched {
log::error!("could not open the Overworld: {e}");
return;
}
host.hub.set_dimension(Dim::Overworld.id());
}
/// The hub's view of the server for packets sent outside its own tick.
pub(super) fn server_ctx(&mut self) -> TickCtx<'_> {
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
TickCtx {
world: &mut self.world,
host: None,
entities: &[],
next_entity: &mut self.next_entity,
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: self.level.difficulty_locked,
clock_rate: if self.ui.rules.bool("advance_time") {
self.ui.clock.rate
} else {
0.0
},
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
}
}
}
+98 -46
View File
@@ -3,8 +3,12 @@
//! killed by, saved to `players/stats/<uuid>.json`, plus the phantom
//! spawner that reads the time since rest (`PhantomSpawner`).
use super::{Dim, Game};
use horizon_core::geometry::Vec3;
use horizon_core::random::RandomSource;
use std::collections::BTreeMap;
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
};
/// `stats[type][key]`, with `type` and `key` namespaced ids.
#[derive(Default)]
@@ -16,6 +20,8 @@ pub(super) struct Stats {
/// Statistic changes (type, key, amount; `None` = reset) for the
/// scoreboard criteria to follow.
pub(super) events: Vec<(String, String, Option<i32>)>,
/// Changed since the client was last sent them (`StatsCounter`'s dirty set).
pub(super) dirty: BTreeSet<(String, String)>,
}
impl Stats {
pub(super) fn add(&mut self, ty: &str, key: &str, n: i32) {
@@ -28,6 +34,8 @@ impl Stats {
*v = v.saturating_add(n);
self.events
.push((format!("minecraft:{ty}"), key.to_owned(), Some(n)));
self.dirty
.insert((format!("minecraft:{ty}"), key.to_owned()));
}
pub(super) fn get(&self, ty: &str, key: &str) -> i32 {
self.values
@@ -40,52 +48,51 @@ impl Stats {
if let Some(m) = self.values.get_mut(&format!("minecraft:{ty}")) {
m.insert(key.to_owned(), 0);
}
self.dirty
.insert((format!("minecraft:{ty}"), key.to_owned()));
self.events
.push((format!("minecraft:{ty}"), key.to_owned(), None));
}
pub(super) fn custom(&mut self, key: &str, n: i32) {
self.add("custom", &format!("minecraft:{key}"), n);
}
}
impl Game<'_> {
fn stats_path(&self) -> Option<std::path::PathBuf> {
let uuid = self.level.player_uuid?;
let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect();
let text = format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
);
Some(
self.world_root
.join("players/stats")
.join(format!("{text}.json")),
)
/// `ServerStatsCounter.markAllDirty`: everything goes out on the next request.
pub(super) fn mark_all_dirty(&mut self) {
self.dirty = self
.values
.iter()
.flat_map(|(ty, m)| m.keys().map(|k| (ty.clone(), k.clone())))
.collect();
}
/// `ServerStatsCounter.parseLocal`.
pub(super) fn load_stats(&mut self) {
if self.stats.loaded || self.remote.is_some() {
return;
}
self.stats.loaded = true;
let Some(path) = self.stats_path() else {
return;
/// `ServerStatsCounter.sendStats`' entries: the dirty statistics and
/// their values, the set cleared.
pub(super) fn take_dirty(&mut self) -> Vec<(String, String, i32)> {
std::mem::take(&mut self.dirty)
.into_iter()
.map(|(ty, key)| {
let v = self.values.get(&ty).and_then(|m| m.get(&key)).copied();
(ty, key, v.unwrap_or(0))
})
.collect()
}
/// `ServerStatsCounter.parseLocal`: the counters of a stats file.
pub(super) fn read(path: &Path) -> Self {
let mut stats = Self {
loaded: true,
..Self::default()
};
let Ok(text) = std::fs::read_to_string(path) else {
return;
let Some(json) = std::fs::read_to_string(path)
.ok()
.and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
else {
return stats;
};
let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) else {
return;
};
if let Some(stats) = json.get("stats").and_then(|s| s.as_object()) {
for (ty, entries) in stats {
if let Some(all) = json.get("stats").and_then(|s| s.as_object()) {
for (ty, entries) in all {
let Some(entries) = entries.as_object() else {
continue;
};
let map = self.stats.values.entry(ty.clone()).or_default();
let map = stats.values.entry(ty.clone()).or_default();
for (key, v) in entries {
if let Some(n) = v.as_i64() {
map.insert(key.clone(), n as i32);
@@ -93,17 +100,11 @@ impl Game<'_> {
}
}
}
stats
}
/// `ServerStatsCounter.save`.
pub(super) fn save_stats(&self) {
if !self.stats.loaded || self.remote.is_some() {
return;
}
let Some(path) = self.stats_path() else {
return;
};
pub(super) fn write(&self, path: &Path) {
let stats: serde_json::Map<String, serde_json::Value> = self
.stats
.values
.iter()
.filter(|(_, m)| !m.is_empty())
@@ -124,9 +125,55 @@ impl Game<'_> {
let _ = std::fs::write(path, text);
}
}
}
/// `players/<dir>/<uuid>.json` of a world (advancements, stats).
pub(super) fn player_json(world: &Path, dir: &str, uuid: [i32; 4]) -> PathBuf {
let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect();
let text = format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
);
world.join("players").join(dir).join(format!("{text}.json"))
}
impl Game<'_> {
fn stats_path(&self) -> Option<PathBuf> {
Some(player_json(
&self.world_root,
"stats",
self.level.player_uuid?,
))
}
/// `ServerStatsCounter.parseLocal`.
pub(super) fn load_stats(&mut self) {
if self.stats.loaded || self.remote.is_some() || self.no_player_here() {
return;
}
self.stats.loaded = true;
if let Some(path) = self.stats_path() {
self.stats.values = Stats::read(&path).values;
}
}
/// `ServerStatsCounter.save`.
pub(super) fn save_stats(&self) {
if !self.stats.loaded || self.remote.is_some() || self.no_player_here() {
return;
}
if let Some(path) = self.stats_path() {
self.stats.write(&path);
}
}
/// The per-tick counters (`Player.tick`/`ServerPlayer.tick` awardStat).
pub(super) fn tick_stats(&mut self) {
self.load_stats();
self.count_tick_stats(self.sleeping.is_some());
self.tick_movement_stats();
}
/// `Player.tick`'s counters for the player in `self.player`.
pub(super) fn count_tick_stats(&mut self, sleeping: bool) {
let Some(p) = self.player.as_ref() else {
return;
};
@@ -137,21 +184,26 @@ impl Game<'_> {
s.custom("total_world_time", 1);
if alive {
s.custom("time_since_death", 1);
if self.sleeping.is_none() {
if !sleeping {
s.custom("time_since_rest", 1);
}
}
if crouching {
s.custom("sneak_time", 1);
}
self.tick_movement_stats();
}
/// `Player.checkMovementStatistics` / `checkRidingStatistics`.
fn tick_movement_stats(&mut self) {
let Some(p) = self.player.as_ref() else {
return;
};
let d = p.position.subtract(self.previous_position);
self.movement_stats(d);
}
/// `Player.checkMovementStatistics` / `checkRidingStatistics` for one move.
pub(super) fn movement_stats(&mut self, d: Vec3) {
let Some(p) = self.player.as_ref() else {
return;
};
let horizontal = ((d.x * d.x + d.z * d.z).sqrt() * 100.0).round() as i32;
let total = ((d.x * d.x + d.y * d.y + d.z * d.z).sqrt() * 100.0).round() as i32;
// Teleports are not travel.
@@ -173,6 +173,12 @@ const FOOTER: f32 = 33.0;
impl Game<'_> {
pub(super) fn open_stats(&mut self) {
self.load_stats();
// StatsScreen.init: a server's client asks for its statistics.
if self.remote.is_some() {
self.send(horizon_protocol::packets::play::Serverbound::ClientCommand(
horizon_protocol::packets::play::ClientCommand { action: 1 },
));
}
self.stats_ui = StatsUi::default();
self.screen = Screen::Stats;
}
+50 -7
View File
@@ -619,8 +619,12 @@ impl Renderer {
adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("Horizon device"),
// Mappable primary buffers: section pages that no
// longer fit in video memory go to system memory.
required_features: timing::GpuTimer::features(&adapter)
| (adapter.features() & wgpu::Features::INDIRECT_FIRST_INSTANCE),
| (adapter.features()
& (wgpu::Features::INDIRECT_FIRST_INSTANCE
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)),
required_limits: limits.clone(),
..Default::default()
})
@@ -1929,11 +1933,22 @@ impl Renderer {
self.indices = Self::quad_indices(&self.device, self.index_quads);
}
let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64;
let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices);
let sorted_indices = (translucent > 0).then(|| {
self.sorted_indices
.alloc(&self.device, &self.queue, u64::from(translucent) * 6)
});
// With video and system memory both full, the section is not drawn.
let Some((page, start)) = self.arena.alloc(&self.device, &self.queue, vertices) else {
return;
};
let sorted_indices = if translucent > 0 {
let indices =
self.sorted_indices
.alloc(&self.device, &self.queue, u64::from(translucent) * 6);
if indices.is_none() {
self.arena.release(page, start, vertices);
return;
}
indices
} else {
None
};
let stride = std::mem::size_of::<TerrainVertex>() as u64;
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
if !part.is_empty() {
@@ -2189,6 +2204,8 @@ impl Renderer {
);
}
pub fn render(&mut self, frame: &Frame) -> Result<bool> {
self.arena.trim();
self.sorted_indices.trim();
if self.suspended {
return Ok(false);
}
@@ -3498,13 +3515,39 @@ fn mix_frames(current: &mut [u8], next: &[u8], millis: u32) {
let t = millis as f32 / 1000.0;
for (c, n) in current.iter_mut().zip(next) {
let (a, b) = (f32::from(*c) / 255.0, f32::from(*n) / 255.0);
*c = ((a * (1.0 - t) + b * t) * 255.0).round() as u8;
*c = round_unorm8((a * (1.0 - t) + b * t) * 255.0);
}
}
/// `x.round() as u8` for `x >= 0`, without the `roundf` library call that
/// x86-64 makes for every `f32::round` (it has no rounding instruction before
/// SSE4.1): the fraction `x - trunc(x)` is exact below 2^23, so rounding half
/// away from zero is adding one when it is at least a half.
#[inline]
fn round_unorm8(x: f32) -> u8 {
let whole = x as u8;
whole.saturating_add(u8::from(x - f32::from(whole) >= 0.5))
}
#[cfg(test)]
mod sprite_upload_tests {
use super::*;
#[test]
fn blended_frames_round_like_f32_round() {
for millis in (0..1000).step_by(7).chain([999]) {
let t = millis as f32 / 1000.0;
for a in 0..=255u8 {
for b in 0..=255u8 {
let x = (f32::from(a) / 255.0 * (1.0 - t) + f32::from(b) / 255.0 * t) * 255.0;
assert_eq!(round_unorm8(x), x.round() as u8, "{a} {b} {millis}");
}
}
}
for x in [
0.0, 0.49999997, 0.5, 1.5, 2.5, 254.49998, 254.5, 255.0, 255.00002, 300.0,
] {
assert_eq!(round_unorm8(x), x.round() as u8, "{x}");
}
}
#[test]
fn real_rail_mips_do_not_change_with_larger_array_layers() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
+277 -42
View File
@@ -49,10 +49,16 @@ struct Page {
/// Terrain vertices in pages of at most `page_limit` vertices (devices cap
/// buffer sizes): a section's vertices sit in one page.
pub struct Arena {
pages: Vec<Page>,
pages: Vec<Option<Page>>,
stride: u64,
page_limit: u64,
initial_capacity: u64,
usage: wgpu::BufferUsages,
/// A page had to go to system memory (logged once).
spilled: bool,
/// Tests: GPU-local pages fail as if video memory were full.
#[cfg(test)]
video_memory_full: bool,
}
impl Arena {
@@ -73,27 +79,49 @@ impl Arena {
let page_limit = (bytes / stride) / GRAIN * GRAIN;
let capacity = capacity.next_multiple_of(GRAIN).min(page_limit);
Self {
pages: vec![Page {
buffer: Self::create(device, stride, capacity, usage),
capacity,
free: FreeList::new(capacity),
}],
pages: Vec::new(),
stride,
page_limit,
initial_capacity: capacity,
usage,
spilled: false,
#[cfg(test)]
video_memory_full: false,
}
}
fn create(
device: &wgpu::Device,
stride: u64,
capacity: u64,
usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section buffer arena"),
size: capacity * stride,
usage: usage | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
/// A buffer of `capacity` vertices in video memory or, when that is full
/// and the device allows it, in system memory: Vulkan drivers fail an
/// allocation rather than page like OpenGL ones, and wgpu's default error
/// handler panics. `None` when neither has room.
fn create(&mut self, device: &wgpu::Device, capacity: u64) -> Option<wgpu::Buffer> {
let usage = self.usage | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC;
#[cfg(test)]
let local = (!self.video_memory_full)
.then(|| try_create(device, capacity * self.stride, usage))
.flatten();
#[cfg(not(test))]
let local = try_create(device, capacity * self.stride, usage);
local.or_else(|| {
// Mappable buffers are placed in host-visible memory, which the
// allocator takes from system memory once video memory is full.
if !device
.features()
.contains(wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)
{
return None;
}
let buffer = try_create(
device,
capacity * self.stride,
usage | wgpu::BufferUsages::MAP_WRITE,
)?;
if !std::mem::replace(&mut self.spilled, true) {
log::warn!(
"Horizon: video memory is full; more terrain is kept in system memory \
(lower the render distance if frames slow down)"
);
}
Some(buffer)
})
}
/// The rounded length a request of `vertices` occupies.
@@ -102,55 +130,97 @@ impl Arena {
}
/// Bytes of every page's buffer.
pub fn bytes(&self) -> u64 {
self.pages.iter().map(|p| p.capacity).sum::<u64>() * self.stride
self.pages.iter().flatten().map(|p| p.capacity).sum::<u64>() * self.stride
}
pub fn buffer(&self, page: u32) -> &wgpu::Buffer {
&self.pages[page as usize].buffer
&self.pages[page as usize]
.as_ref()
.expect("live arena page")
.buffer
}
/// A range of `vertices`: (page, first vertex). Grows the newest page
/// (copying its contents on the GPU) or starts a new one when nothing
/// free is large enough.
/// free is large enough; `None` when no memory is left for it.
pub fn alloc(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
vertices: u64,
) -> (u32, u64) {
) -> Option<(u32, u64)> {
let len = Self::span(vertices).min(self.page_limit);
for (i, page) in self.pages.iter_mut().enumerate() {
if let Some(start) = page.free.take(len) {
return (i as u32, start);
if let Some(page) = page
&& let Some(start) = page.free.take(len)
{
return Some((i as u32, start));
}
}
let last = self.pages.len() - 1;
let current = self.pages[last].capacity;
if current < self.page_limit {
let last = self.pages.len().saturating_sub(1);
if let Some(page) = self.pages.last().and_then(Option::as_ref)
&& page.capacity < self.page_limit
{
let current = page.capacity;
let grown = (current * 2).max(current + len).min(self.page_limit);
if grown - current >= len || grown == self.page_limit {
self.grow(device, queue, last, grown);
if let Some(start) = self.pages[last].free.take(len) {
return (last as u32, start);
}
if (grown - current >= len || grown == self.page_limit)
&& self.grow(device, queue, last, grown)
&& let Some(start) = self.pages[last].as_mut().unwrap().free.take(len)
{
return Some((last as u32, start));
}
}
let capacity = (1 << 20u64).max(len).min(self.page_limit);
let capacity = if self.pages.is_empty() {
self.initial_capacity
} else {
1 << 20
}
.max(len)
.min(self.page_limit);
// A page just large enough when memory is short.
let (buffer, capacity) = match self.create(device, capacity) {
Some(buffer) => (buffer, capacity),
None if capacity > len => (self.create(device, len)?, len),
None => return None,
};
let mut free = FreeList::new(capacity);
let start = free.take(len).expect("a new page fits one section");
self.pages.push(Page {
buffer: Self::create(device, self.stride, capacity, self.usage),
let page = Page {
buffer,
capacity,
free,
});
((self.pages.len() - 1) as u32, start)
};
let index = self
.pages
.iter()
.position(Option::is_none)
.unwrap_or_else(|| {
self.pages.push(None);
self.pages.len() - 1
});
self.pages[index] = Some(page);
Some((index as u32, start))
}
pub fn release(&mut self, page: u32, start: u64, vertices: u64) {
let len = Self::span(vertices).min(self.page_limit);
self.pages[page as usize].free.give(start, len);
self.pages[page as usize]
.as_mut()
.expect("live arena page")
.free
.give(start, len);
}
fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, page: usize, capacity: u64) {
/// Moves a page into a larger buffer; false (the page unchanged) when
/// there is no memory for it.
fn grow(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
page: usize,
capacity: u64,
) -> bool {
let capacity = capacity.next_multiple_of(GRAIN).min(self.page_limit);
let buffer = Self::create(device, self.stride, capacity, self.usage);
let old = &mut self.pages[page];
let Some(buffer) = self.create(device, capacity) else {
return false;
};
let old = self.pages[page].as_mut().expect("live arena page");
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Grow section arena"),
});
@@ -161,18 +231,124 @@ impl Arena {
old.buffer = buffer;
old.capacity = capacity;
old.free.give(previous, capacity - previous);
true
}
pub fn clear(&mut self) {
/// Reclaim after an upload batch, so replacing a section can reuse its range.
pub fn trim(&mut self) {
for page in &mut self.pages {
page.free = FreeList::new(page.capacity);
if let Some(p) = page
&& p.free.0.len() == 1
&& p.free.0.get(&0) == Some(&p.capacity)
{
*page = None;
}
}
// Keep live page indices stable; later allocations reuse interior holes.
while self.pages.last().is_some_and(Option::is_none) {
self.pages.pop();
}
}
pub fn clear(&mut self) {
self.pages.clear();
}
}
/// `create_buffer` with an out-of-memory failure returned instead of raised
/// (raised errors are fatal).
fn try_create(device: &wgpu::Device, size: u64, usage: wgpu::BufferUsages) -> Option<wgpu::Buffer> {
let scope = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section buffer arena"),
size,
usage,
mapped_at_creation: false,
});
// Native error scopes resolve at once.
pollster::block_on(scope.pop()).is_none().then_some(buffer)
}
#[cfg(test)]
mod tests {
use super::*;
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
device_with(wgpu::Features::empty())
}
/// A device with those of `features` the adapter has.
fn device_with(features: wgpu::Features) -> 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!("arena GPU regression: {}", adapter.get_info().name);
let required_features = adapter.features() & features;
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_features,
..Default::default()
}))
.ok()
}
#[test]
fn empty_pages_are_reclaimed_without_moving_live_ranges() {
let Some((device, queue)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
let mut arena = Arena::new(&device, 4, GRAIN);
arena.page_limit = 2 * GRAIN;
assert_eq!(arena.bytes(), 0);
let (first, a) = arena.alloc(&device, &queue, GRAIN).unwrap();
let (_, b) = arena.alloc(&device, &queue, GRAIN).unwrap();
let (live, c) = arena.alloc(&device, &queue, 2 * GRAIN).unwrap();
let buffer = arena.buffer(live).clone();
let data = [1u8, 2, 3, 4];
queue.write_buffer(&buffer, c * 4, &data);
assert_eq!(arena.bytes(), 4 * GRAIN * 4);
arena.release(first, a, GRAIN);
arena.trim();
assert_eq!(arena.bytes(), 4 * GRAIN * 4);
arena.release(first, b, GRAIN);
arena.trim();
assert_eq!(arena.bytes(), 2 * GRAIN * 4);
assert_eq!(arena.buffer(live), &buffer);
let (reused, d) = arena.alloc(&device, &queue, GRAIN).unwrap();
assert_eq!(reused, first);
let (tx, rx) = std::sync::mpsc::channel();
wgpu::util::DownloadBuffer::read_buffer(
&device,
&queue,
&arena.buffer(live).slice(c * 4..c * 4 + 4),
move |result| tx.send(result.unwrap().to_vec()).unwrap(),
);
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
assert_eq!(rx.recv().unwrap(), data);
arena.release(reused, d, GRAIN);
arena.release(live, c, 2 * GRAIN);
arena.trim();
assert_eq!(arena.bytes(), 0);
assert!(arena.pages.is_empty());
}
#[test]
fn clearing_an_arena_releases_buffers_and_can_allocate_again() {
let Some((device, queue)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
for mut arena in [
Arena::new(&device, 28, GRAIN),
Arena::indices(&device, GRAIN),
] {
arena.alloc(&device, &queue, GRAIN).unwrap();
assert_eq!(arena.bytes(), arena.stride * GRAIN);
arena.clear();
assert_eq!(arena.bytes(), 0);
assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0)));
assert_eq!(arena.bytes(), arena.stride * GRAIN);
}
}
#[test]
fn free_ranges_coalesce() {
let mut free = FreeList::new(4 * GRAIN);
@@ -197,4 +373,63 @@ mod tests {
free.give(a, GRAIN);
assert_eq!(free.take(GRAIN), Some(a));
}
fn read(device: &wgpu::Device, queue: &wgpu::Queue, buffer: &wgpu::Buffer, offset: u64) -> u32 {
let (tx, rx) = std::sync::mpsc::channel();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&buffer.slice(offset..offset + 4),
move |result| tx.send(result.unwrap().to_vec()).unwrap(),
);
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
u32::from_le_bytes(rx.recv().unwrap()[..4].try_into().unwrap())
}
#[test]
fn full_video_memory_spills_to_system_memory() {
let Some((device, queue)) = device_with(wgpu::Features::MAPPABLE_PRIMARY_BUFFERS) else {
return;
};
if !device
.features()
.contains(wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)
{
return;
}
let mut arena = Arena::indices(&device, GRAIN);
let (page, start) = arena.alloc(&device, &queue, GRAIN).unwrap();
queue.write_buffer(arena.buffer(page), start * 4, &7u32.to_le_bytes());
arena.video_memory_full = true;
// The full page can't grow in video memory: it moves to system
// memory with its contents, and new ranges come from there.
let (grown, next) = arena.alloc(&device, &queue, GRAIN).unwrap();
assert!(arena.spilled);
assert_eq!(grown, page);
assert!(
arena
.buffer(page)
.usage()
.contains(wgpu::BufferUsages::MAP_WRITE)
);
queue.write_buffer(arena.buffer(grown), next * 4, &9u32.to_le_bytes());
assert_eq!(read(&device, &queue, arena.buffer(page), start * 4), 7);
assert_eq!(read(&device, &queue, arena.buffer(grown), next * 4), 9);
}
#[test]
fn no_memory_left_is_not_an_error() {
let Some((device, queue)) = device() else {
return;
};
let mut arena = Arena::indices(&device, GRAIN);
arena.alloc(&device, &queue, GRAIN).unwrap();
arena.video_memory_full = true;
// Without mappable primary buffers nothing can spill: the request
// fails, and the arena keeps what it has.
assert_eq!(arena.alloc(&device, &queue, GRAIN), None);
assert_eq!(arena.bytes(), GRAIN * 4);
arena.release(0, 0, GRAIN);
assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0)));
}
}
+198 -66
View File
@@ -4,11 +4,14 @@
//! ClientboundRecipeBookAddPacket) and the advancements the player may see go
//! out in ClientboundUpdateAdvancementsPacket (PlayerAdvancements.flushDirty).
use super::data::{SyncData, json_to_nbt};
use crate::{advancements::Tree, recipe_book::RecipeIndex};
use crate::{
advancements::{Progress, Tree},
recipe_book::{RecipeIndex, Settings},
};
use horizon_protocol::buf::Writer;
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
collections::{BTreeMap, BTreeSet, HashMap},
path::Path,
};
@@ -54,8 +57,16 @@ impl ServerAdvancements {
}
}
/// The first tick of a player without advancements.
pub fn first_tick(&self, sync: &SyncData, now_millis: i64) -> FirstTick {
/// The first tick of a player without advancements: the criteria
/// `minecraft:tick` meets go into `progress` and the recipes their
/// advancements reward into `book`.
pub fn first_tick(
&self,
sync: &SyncData,
now_millis: i64,
progress: &mut Progress,
book: &mut Settings,
) -> FirstTick {
// CriteriaTriggers.TICK: the criteria it meets, and what they complete.
let mut obtained: Vec<Vec<&str>> = vec![Vec::new(); self.tree.list.len()];
for (i, a) in self.tree.list.iter().enumerate() {
@@ -77,25 +88,24 @@ impl ServerAdvancements {
.all(|group| group.iter().any(|c| got.contains(&c.as_str())))
})
.collect();
let date = crate::advancements::date_text(now_millis.div_euclid(1000));
for (a, got) in self.tree.list.iter().zip(&obtained) {
for c in got {
progress.grant(&a.id, c, &date);
}
}
// AdvancementRewards.grant: the recipes, in the advancements' order.
let mut entries = Vec::new();
for (i, a) in self.tree.list.iter().enumerate() {
if !done[i] {
continue;
}
book.add_recipes(&self.displays, &a.rewards.recipes);
for id in &a.rewards.recipes {
entries.extend(self.book_entries(id, sync));
entries.extend(self.book_entries(id, sync, NOTIFY_AND_HIGHLIGHT));
}
}
let recipe_book_add = (!entries.is_empty()).then(|| {
let mut w = Writer::new();
w.varint(entries.len() as i32);
for e in entries {
w.data.extend(e);
}
w.bool(false); // not a replacement
w.data
});
let recipe_book_add = (!entries.is_empty()).then(|| book_add(entries, false));
// flushDirty: every advancement the player may see, and its progress.
let visible = self.tree.visible(&self.kids, |i| done[i]);
let shown: Vec<usize> = (0..self.tree.list.len()).filter(|i| visible[*i]).collect();
@@ -103,60 +113,14 @@ impl ServerAdvancements {
w.bool(true); // the first packet resets the client's advancements
w.varint(shown.len() as i32);
for &i in &shown {
let a = &self.tree.list[i];
w.string(&a.id);
w.bool(a.parent.is_some());
if let Some(p) = &a.parent {
w.string(p);
}
w.bool(a.display.is_some());
if let Some(d) = &a.display {
w.nbt(&json_to_nbt(&d.title));
w.nbt(&json_to_nbt(&d.description));
w.varint(sync.id("minecraft:item", &d.icon).unwrap_or(0));
w.varint(1);
w.varint(0);
w.varint(0);
w.varint(match d.frame {
crate::advancements::Frame::Task => 0,
crate::advancements::Frame::Challenge => 1,
crate::advancements::Frame::Goal => 2,
});
w.i32(
i32::from(d.background.is_some())
| i32::from(d.show_toast) << 1
| i32::from(d.hidden) << 2,
);
if let Some(b) = &d.background {
w.string(b);
}
}
w.varint(a.requirements.len() as i32);
for group in &a.requirements {
w.varint(group.len() as i32);
for c in group {
w.string(c);
}
}
w.bool(false); // sends_telemetry_event
let (x, y) = self.layout[i].unwrap_or((0, 0.0));
w.f32(x as f32);
w.f32(y);
self.write_advancement(&mut w, i, sync);
}
w.varint(0); // nothing removed
w.varint(shown.len() as i32);
for &i in &shown {
let a = &self.tree.list[i];
w.string(&a.id);
w.varint(a.criteria.len() as i32);
for c in &a.criteria {
w.string(&c.name);
let got = obtained[i].contains(&c.name.as_str());
w.bool(got);
if got {
w.i64(now_millis);
}
}
self.write_progress(&mut w, i, |c| {
obtained[i].contains(&c).then_some(now_millis)
});
}
w.bool(true); // show the advancements
FirstTick {
@@ -165,9 +129,162 @@ impl ServerAdvancements {
}
}
/// `PlayerAdvancements.flushDirty`: the advancements that became visible
/// or hidden since `visible` (which it updates; empty before the first
/// packet, which resets the client's and carries everything visible) and
/// the progress of the `changed` ones still visible. None when there is
/// nothing to send.
pub fn update(
&self,
sync: &SyncData,
progress: &Progress,
visible: &mut Vec<bool>,
changed: &BTreeSet<usize>,
show: bool,
) -> Option<Vec<u8>> {
let n = self.tree.list.len();
let first = visible.len() != n;
let now = self
.tree
.visible(&self.kids, |i| progress.done(&self.tree.list[i]));
let was = |i: usize| !first && visible[i];
let added: Vec<usize> = (0..n).filter(|&i| now[i] && !was(i)).collect();
let removed: Vec<usize> = (0..n).filter(|&i| !now[i] && was(i)).collect();
let progressed: Vec<usize> = if first {
(0..n).filter(|&i| now[i]).collect()
} else {
changed
.iter()
.copied()
.filter(|&i| i < n && now[i])
.collect()
};
*visible = now;
if !first && added.is_empty() && removed.is_empty() && progressed.is_empty() {
return None;
}
let mut w = Writer::new();
w.bool(first);
w.varint(added.len() as i32);
for &i in &added {
self.write_advancement(&mut w, i, sync);
}
w.varint(removed.len() as i32);
for &i in &removed {
w.string(&self.tree.list[i].id);
}
w.varint(progressed.len() as i32);
for &i in &progressed {
let id = &self.tree.list[i].id;
self.write_progress(&mut w, i, |c| {
progress
.criteria
.get(id)
.and_then(|m| m.get(c))
.map(|date| crate::advancements::date_millis(date).unwrap_or(0))
});
}
w.bool(show);
Some(w.data)
}
/// Which advancements a player with `progress` may see.
pub fn visibility(&self, progress: &Progress) -> Vec<bool> {
self.tree
.visible(&self.kids, |i| progress.done(&self.tree.list[i]))
}
/// `ClientboundUpdateAdvancementsPacket.PositionedAdvancement`.
fn write_advancement(&self, w: &mut Writer, i: usize, sync: &SyncData) {
let a = &self.tree.list[i];
w.string(&a.id);
w.bool(a.parent.is_some());
if let Some(p) = &a.parent {
w.string(p);
}
w.bool(a.display.is_some());
if let Some(d) = &a.display {
w.nbt(&json_to_nbt(&d.title));
w.nbt(&json_to_nbt(&d.description));
w.varint(sync.id("minecraft:item", &d.icon).unwrap_or(0));
w.varint(1);
w.varint(0);
w.varint(0);
w.varint(match d.frame {
crate::advancements::Frame::Task => 0,
crate::advancements::Frame::Challenge => 1,
crate::advancements::Frame::Goal => 2,
});
w.i32(
i32::from(d.background.is_some())
| i32::from(d.show_toast) << 1
| i32::from(d.hidden) << 2,
);
if let Some(b) = &d.background {
w.string(b);
}
}
w.varint(a.requirements.len() as i32);
for group in &a.requirements {
w.varint(group.len() as i32);
for c in group {
w.string(c);
}
}
w.bool(false); // sends_telemetry_event
let (x, y) = self.layout[i].unwrap_or((0, 0.0));
w.f32(x as f32);
w.f32(y);
}
/// An `AdvancementProgress`: each criterion and when it was obtained.
fn write_progress(&self, w: &mut Writer, i: usize, obtained: impl Fn(&str) -> Option<i64>) {
let a = &self.tree.list[i];
w.string(&a.id);
w.varint(a.criteria.len() as i32);
for c in &a.criteria {
w.string(&c.name);
let at = obtained(&c.name);
w.bool(at.is_some());
if let Some(at) = at {
w.i64(at);
}
}
}
/// `ServerRecipeBook.addRecipes`' packet for recipes just unlocked:
/// each display, with its notification and highlighted. None when no
/// recipe has a display.
pub fn recipes_added(&self, ids: &[String], sync: &SyncData) -> Option<Vec<u8>> {
let entries: Vec<Vec<u8>> = ids
.iter()
.flat_map(|id| self.book_entries(id, sync, NOTIFY_AND_HIGHLIGHT))
.collect();
(!entries.is_empty()).then(|| book_add(entries, false))
}
/// `ServerRecipeBook.sendInitialRecipeBook`: every known recipe, without
/// notifications, highlighted while not yet displayed, replacing the
/// client's book.
pub fn initial_recipe_book(&self, book: &Settings, sync: &SyncData) -> Vec<u8> {
let entries: Vec<Vec<u8>> = book
.recipes
.iter()
.flat_map(|id| {
let highlight = if book.to_be_displayed.contains(id) {
2
} else {
0
};
self.book_entries(id, sync, highlight)
})
.collect();
book_add(entries, true)
}
/// ClientboundRecipeBookAddPacket.Entry for each display of a recipe:
/// highlighted, and with a notification unless the recipe turns it off.
fn book_entries(&self, id: &str, sync: &SyncData) -> Vec<Vec<u8>> {
fn book_entries(&self, id: &str, sync: &SyncData, flags: i8) -> Vec<Vec<u8>> {
let Some(r) = self.recipes.get(id) else {
return Vec::new();
};
@@ -245,12 +362,27 @@ impl ServerAdvancements {
for v in placed {
holder_set(&mut w, v, &item);
}
// The notification only where the recipe shows one.
let notify = r["show_notification"].as_bool().unwrap_or(true);
w.i8(i8::from(notify) | 2);
w.i8(if notify { flags } else { flags & !1 });
vec![w.data]
}
}
/// ClientboundRecipeBookAddPacket.Entry flags: notification, highlight.
const NOTIFY_AND_HIGHLIGHT: i8 = 1 | 2;
/// ClientboundRecipeBookAddPacket: the entries, then whether they replace the book.
fn book_add(entries: Vec<Vec<u8>>, replace: bool) -> Vec<u8> {
let mut w = Writer::new();
w.varint(entries.len() as i32);
for e in entries {
w.data.extend(e);
}
w.bool(replace);
w.data
}
/// ShapedRecipePattern.shrink: the pattern without blank border rows and columns.
fn shrink(rows: &[Value]) -> Vec<Vec<char>> {
let rows: Vec<Vec<char>> = rows
+380 -68
View File
@@ -90,7 +90,78 @@ pub struct ChunkEncoder {
pub block_ids: Vec<i32>,
/// The save's tables, for the heightmaps.
pub tables: Option<Arc<crate::save::SaveTables>>,
/// Sections already looked at, by address (see `Encoded`).
cache: std::sync::Mutex<HashMap<usize, Encoded>>,
/// Each column's heightmaps, with the sections they were made from.
heights: std::sync::Mutex<HashMap<(i32, i32), Heights>>,
/// The level's sections among a column's: all of them in the Overworld,
/// y 0 to 255 in the Nether and the End (`DimensionType` min_y and height).
sections: std::ops::Range<usize>,
/// Whether the level has sky light (`DimensionType.hasSkyLight`).
sky: bool,
}
/// A column's client heightmaps, valid while it holds the same sections.
struct Heights {
sections: Vec<std::sync::Weak<Section>>,
maps: Vec<(i32, Vec<i64>)>,
}
/// What a resident section gives the wire, kept while the section is
/// unchanged. Resident sections are immutable behind `Arc` (edits go through
/// `Arc::make_mut`, which moves an edited section to a new address while a
/// `Weak` points at the old one), and the `Weak` keeps the old address from
/// being reused: the same address is the same, unchanged section.
struct Encoded {
section: std::sync::Weak<Section>,
non_air: bool,
/// LevelChunkSection.write, and whether it holds block entity blocks.
wire: Option<(Arc<[u8]>, bool)>,
/// The section's light as the wire's two DataLayers, when not uniform.
light: Option<Arc<Layers>>,
}
/// One section's light as DataLayers (two blocks per byte, the even one in
/// the low nibble), and whether each holds any light.
struct Layers {
sky: Vec<u8>,
block: Vec<u8>,
sky_any: bool,
block_any: bool,
}
impl Layers {
fn of(light: &Light) -> Self {
let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]);
let (sky_any, block_any) = match light {
Light::Uniform(v) => {
let (sk, bl) = (v >> 4, v & 15);
sky.fill(sk | sk << 4);
block.fill(bl | bl << 4);
(sk != 0, bl != 0)
}
Light::Full(a) => {
for ((pair, sky), block) in
a.as_chunks::<2>().0.iter().zip(&mut sky).zip(&mut block)
{
let [even, odd] = *pair;
*sky = even >> 4 | (odd & 0xF0);
*block = (even & 15) | odd << 4;
}
let all = a.iter().fold(0u8, |acc, &v| acc | v);
(all & 0xF0 != 0, all & 15 != 0)
}
};
Self {
sky,
block,
sky_any,
block_any,
}
}
}
/// Sections kept before the ones no longer resident are dropped.
const CACHE_SWEEP: usize = 1 << 15;
impl ChunkEncoder {
/// `biome_names`: the internal biome list in order; `biome_registry`:
/// the synchronized biome entries in network order.
@@ -143,8 +214,106 @@ impl ChunkEncoder {
biome_bits: ceil_log2(biome_registry.len()),
block_ids,
tables: None,
cache: Default::default(),
heights: Default::default(),
sections: 0..SECTIONS,
sky: true,
}
}
/// The client heightmaps (Heightmap.prime over the column), from the
/// cache while the column's sections are unchanged.
fn heightmaps(&self, chunk: &Chunk, tables: &crate::save::SaveTables) -> Vec<(i32, Vec<i64>)> {
let same = |h: &Heights| {
h.sections.len() == chunk.sections.len()
&& h.sections
.iter()
.zip(&chunk.sections)
.all(|(w, s)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(s)))
};
let mut heights = self.heights.lock().unwrap();
if let Some(h) = heights.get(&(chunk.x, chunk.z))
&& same(h)
{
return h.maps.clone();
}
if heights.len() >= CACHE_SWEEP / 4 {
heights.retain(|_, h| h.sections.iter().all(|w| w.strong_count() > 0));
if heights.len() >= CACHE_SWEEP / 8 {
heights.clear();
}
}
let min_y = MIN_Y + 16 * self.sections.start as i32;
let height = 16 * self.sections.len() as i32;
let maps = crate::save::client_heightmaps_in(chunk, tables, min_y, height);
heights.insert(
(chunk.x, chunk.z),
Heights {
sections: chunk.sections.iter().map(Arc::downgrade).collect(),
maps: maps.clone(),
},
);
maps
}
/// The cached entry for a section, made with `non_air` when missing.
fn cached<T>(&self, section: &Arc<Section>, read: impl FnOnce(&mut Encoded) -> T) -> T {
let mut cache = self.cache.lock().unwrap();
if cache.len() >= CACHE_SWEEP {
cache.retain(|_, e| e.section.strong_count() > 0);
if cache.len() >= CACHE_SWEEP / 2 {
cache.clear();
}
}
let entry = cache
.entry(Arc::as_ptr(section) as usize)
.or_insert_with(|| Encoded {
section: Arc::downgrade(section),
non_air: self.non_air(section),
wire: None,
light: None,
});
read(entry)
}
/// LevelChunkSection.hasOnlyAir, negated.
fn non_air(&self, section: &Section) -> bool {
let non_air = |v: u32| self.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0;
// The palette first: most sections are all air, or one block.
if !section.blocks.maybe_has(non_air) {
false
} else if let Some(v) = section.blocks.uniform() {
non_air(v)
} else {
// Stops at the first block, usually near the bottom.
(0..BLOCKS).any(|i| non_air(section.blocks.get(i)))
}
}
/// A section on the wire, from the cache or encoded now.
fn section_wire(&self, section: &Arc<Section>) -> (Arc<[u8]>, bool) {
if let Some(wire) = self.cached(section, |e| e.wire.clone()) {
return wire;
}
let (encoded, entities) = self.section(section);
let mut w = horizon_protocol::buf::Writer::new();
encoded.write(&mut w);
let wire: (Arc<[u8]>, bool) = (w.data.into(), entities);
self.cached(section, |e| e.wire = Some(wire.clone()));
wire
}
/// Encode for a level of `min_y` and `height` (multiples of 16 within
/// the column), with or without sky light.
pub fn set_dimension(&mut self, min_y: i32, height: i32, sky: bool) {
let lo = usize::try_from((min_y - MIN_Y) >> 4)
.unwrap_or(0)
.min(SECTIONS);
let n = usize::try_from(height >> 4).unwrap_or(SECTIONS);
self.sections = lo..(lo + n).min(SECTIONS);
self.sky = sky;
// The heightmaps depend on the level's height.
self.heights.get_mut().unwrap().clear();
}
pub fn entity_type(&self, state: u32) -> Option<i32> {
self.entity_types
.get(state as usize)
@@ -170,11 +339,17 @@ impl ChunkEncoder {
}
f & ENTITY != 0
};
let mut unpacked = [0u32; BLOCKS];
section.unpack(&mut unpacked);
for &v in &unpacked {
entities |= count(v, 1);
values.push(v as i32);
// One block everywhere (all air, mostly): what from_values would give.
let uniform = section.blocks.uniform();
if let Some(v) = uniform {
entities = count(v, BLOCKS as i16);
} else {
let mut unpacked = [0u32; BLOCKS];
section.unpack(&mut unpacked);
for &v in &unpacked {
entities |= count(v, 1);
values.push(v as i32);
}
}
let biome_values: Vec<i32> = (0..BIOMES)
.map(|j| {
@@ -189,11 +364,18 @@ impl ChunkEncoder {
horizon_protocol::chunk::Section {
non_empty,
fluids,
states: Paletted::from_values(
&values,
Strategy::Blocks,
crate::chunk::block_strategy().global_bits,
),
states: match uniform {
Some(v) => Paletted {
bits: 0,
palette: vec![v as i32],
data: Vec::new(),
},
None => Paletted::from_values(
&values,
Strategy::Blocks,
crate::chunk::block_strategy().global_bits,
),
},
biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits),
},
entities,
@@ -204,13 +386,8 @@ impl ChunkEncoder {
/// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir).
fn occupied(&self, chunk: &Chunk) -> u64 {
let mut bits = 0u64;
for (i, s) in chunk.sections.iter().enumerate() {
let mut unpacked = [0u32; BLOCKS];
s.unpack(&mut unpacked);
let any = unpacked
.iter()
.any(|&v| self.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0);
if any {
for (i, s) in chunk.sections[self.sections.clone()].iter().enumerate() {
if self.cached(s, |e| e.non_air) {
bits |= 1 << i;
}
}
@@ -228,8 +405,8 @@ impl ChunkEncoder {
}
}
}
let mut packet = self.encode(chunk, &world.block_entities);
packet.light = light_data(chunk, around);
let mut packet = self.encode_blocks(chunk, &world.block_entities);
packet.light = self.light_data(chunk, around);
packet
}
@@ -238,10 +415,27 @@ impl ChunkEncoder {
chunk: &Chunk,
block_entities: &HashMap<(i32, i32, i32), BlockEntity>,
) -> LevelChunkWithLight {
let mut sections = Vec::with_capacity(SECTIONS);
let mut packet = self.encode_blocks(chunk, block_entities);
packet.light = self.light_data(chunk, u64::MAX);
packet
}
/// The packet without its light.
fn encode_blocks(
&self,
chunk: &Chunk,
block_entities: &HashMap<(i32, i32, i32), BlockEntity>,
) -> LevelChunkWithLight {
let mut buffer = Vec::new();
let mut entity_infos = Vec::new();
for (i, s) in chunk.sections.iter().enumerate() {
let (encoded, has_entities) = self.section(s);
for (i, s) in chunk
.sections
.iter()
.enumerate()
.skip(self.sections.start)
.take(self.sections.len())
{
let (encoded, has_entities) = self.section_wire(s);
if has_entities {
for y in 0..16 {
for z in 0..16 {
@@ -265,7 +459,7 @@ impl ChunkEncoder {
}
}
}
sections.push(encoded);
buffer.extend_from_slice(&encoded);
}
// A loaded chunk's block entities enter its maps in the save's order
// (ChunkAccess.pendingBlockEntities, then LevelChunk.blockEntities):
@@ -297,14 +491,46 @@ impl ChunkEncoder {
heightmaps: self
.tables
.as_ref()
.map(|t| crate::save::client_heightmaps(chunk, t))
.map(|t| self.heightmaps(chunk, t))
.unwrap_or_default(),
buffer: ChunkData::from_sections(&sections),
buffer,
block_entities: entity_infos,
},
light: light_data(chunk, u64::MAX),
light: LightData {
sky_mask: Vec::new(),
block_mask: Vec::new(),
empty_sky_mask: Vec::new(),
empty_block_mask: Vec::new(),
sky: Vec::new(),
block: Vec::new(),
},
}
}
/// ClientboundLightUpdatePacketData: the light layers of the sections
/// that exist around the column (`around`: the non-air sections of it
/// and its neighbours, as bits). A resident section's layers come from
/// the cache while it is unchanged (uniform light is quicker to fill than
/// to keep).
fn light_data(&self, chunk: &Chunk, around: u64) -> LightData {
let mut data = light_data_with(&chunk.sections[self.sections.clone()], around, |s| {
if matches!(s.light, Light::Uniform(_)) {
return Arc::new(Layers::of(&s.light));
}
self.cached(s, |e| e.light.clone()).unwrap_or_else(|| {
let layers = Arc::new(Layers::of(&s.light));
self.cached(s, |e| e.light = Some(layers.clone()));
layers
})
});
if !self.sky {
// No sky light storage at all.
data.sky_mask.clear();
data.empty_sky_mask.clear();
data.sky.clear();
}
data
}
}
/// The order LevelChunk.getBlockEntities() iterates in: a fastutil
@@ -377,7 +603,18 @@ pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
/// non-air section of this column or a neighbouring one (`around`, bit i for
/// section i; LayerLightSectionStorage.updateSectionStatus). An existing
/// layer is sent, or marked empty when all dark; the others are left out.
fn light_data(chunk: &Chunk, around: u64) -> LightData {
#[cfg(test)]
fn light_data(sections: &[Arc<Section>], around: u64) -> LightData {
light_data_with(sections, around, |s| Arc::new(Layers::of(&s.light)))
}
/// The light layers, `section` giving a resident section's.
fn light_data_with(
sections: &[Arc<Section>],
around: u64,
section: impl Fn(&Arc<Section>) -> Arc<Layers>,
) -> LightData {
let n = sections.len();
let mut data = LightData {
sky_mask: Vec::new(),
block_mask: Vec::new(),
@@ -387,55 +624,27 @@ fn light_data(chunk: &Chunk, around: u64) -> LightData {
block: Vec::new(),
};
// Light section b holds chunk section b - 1.
let exists = |b: usize| {
(b.saturating_sub(2)..=b.min(SECTIONS - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0)
};
let full_sky = Light::Uniform(0xF0);
for b in 0..SECTIONS + 2 {
let exists =
|b: usize| (b.saturating_sub(2)..=b.min(n - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0);
for b in 0..n + 2 {
if !exists(b) {
continue;
}
let light = match b {
let layers = match b {
// Below the world nothing is lit; above it the sky is full.
0 => &Light::Uniform(0),
_ if b == SECTIONS + 1 => &full_sky,
_ => &chunk.sections[b - 1].light,
0 => Arc::new(Layers::of(&Light::Uniform(0))),
_ if b == n + 1 => Arc::new(Layers::of(&Light::Uniform(0xF0))),
_ => section(&sections[b - 1]),
};
let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]);
let (mut sky_any, mut block_any) = (false, false);
match light {
Light::Uniform(v) => {
let (sk, bl) = (v >> 4, v & 15);
sky_any = sk != 0;
block_any = bl != 0;
let (sb, bb) = (sk | sk << 4, bl | bl << 4);
sky.fill(sb);
block.fill(bb);
}
Light::Full(a) => {
for (j, &v) in a.iter().enumerate() {
let (sk, bl) = (v >> 4, v & 15);
sky_any |= sk != 0;
block_any |= bl != 0;
if j & 1 == 0 {
sky[j >> 1] |= sk;
block[j >> 1] |= bl;
} else {
sky[j >> 1] |= sk << 4;
block[j >> 1] |= bl << 4;
}
}
}
}
if sky_any {
if layers.sky_any {
set_bit(&mut data.sky_mask, b);
data.sky.push(sky);
data.sky.push(layers.sky.clone());
} else {
set_bit(&mut data.empty_sky_mask, b);
}
if block_any {
if layers.block_any {
set_bit(&mut data.block_mask, b);
data.block.push(block);
data.block.push(layers.block.clone());
} else {
set_bit(&mut data.empty_block_mask, b);
}
@@ -464,16 +673,119 @@ mod tests {
assert_eq!(block_entity_type("minecraft:stone"), None);
}
fn encoder() -> ChunkEncoder {
let states = ["minecraft:air", "minecraft:stone", "minecraft:water"]
.map(|n| (Arc::<str>::from(n), n.ends_with("water")));
ChunkEncoder::new(states, &Builtin::default(), &[], &[])
}
/// The bytes on the wire for a section, encoded afresh.
fn fresh(encoder: &ChunkEncoder, section: &Section) -> Vec<u8> {
let mut w = horizon_protocol::buf::Writer::new();
encoder.section(section).0.write(&mut w);
w.data
}
#[test]
fn cached_sections_follow_edits() {
let encoder = encoder();
let mut chunk = Chunk::empty(0, 0);
chunk.set(1, MIN_Y + 2, 3, 1);
let before = encoder.encode(&chunk, &HashMap::new());
assert_eq!(encoder.occupied(&chunk), 1);
assert_eq!(
&*encoder.section_wire(&chunk.sections[0]).0,
fresh(&encoder, &chunk.sections[0])
);
// An edit moves the section: the cache sees a new one.
chunk.set(4, MIN_Y + 20, 4, 2);
chunk.set(1, MIN_Y + 2, 3, 0);
assert_eq!(encoder.occupied(&chunk), 2);
let after = encoder.encode(&chunk, &HashMap::new());
assert_ne!(before.chunk.buffer, after.chunk.buffer);
let mut expected = Vec::new();
for s in &chunk.sections {
expected.extend(fresh(&encoder, s));
}
assert_eq!(after.chunk.buffer, expected);
}
#[test]
fn light_layers_pack_two_blocks_per_byte() {
let mut chunk = Chunk::empty(0, 0);
let mut light = Box::new([0u8; 4096]);
for (i, v) in light.iter_mut().enumerate() {
*v = (i * 37 % 251) as u8;
}
Arc::make_mut(&mut chunk.sections[3]).light = Light::Full(light.clone());
let data = light_data(&chunk.sections, u64::MAX);
// Layer 4 holds section 3. Below the world (layer 0) there is no sky
// light, so the sky layers listed start at layer 1; section 3 has the
// only block light.
let (sky, block) = (&data.sky[3], &data.block[0]);
for j in 0..4096 {
let (s, b) = if j & 1 == 0 {
(sky[j >> 1] & 15, block[j >> 1] & 15)
} else {
(sky[j >> 1] >> 4, block[j >> 1] >> 4)
};
assert_eq!((s, b), (light[j] >> 4, light[j] & 15), "block {j}");
}
}
#[test]
fn cached_light_follows_edits() {
let encoder = encoder();
let mut chunk = Chunk::empty(0, 0);
let mut light = Box::new([0x5Au8; 4096]);
Arc::make_mut(&mut chunk.sections[2]).light = Light::Full(light.clone());
let first = encoder.encode(&chunk, &HashMap::new()).light;
assert_eq!(first, light_data(&chunk.sections, u64::MAX));
// Relighting moves the section, so the cached layers aren't reused.
light[7] = 0xF3;
Arc::make_mut(&mut chunk.sections[2]).light = Light::Full(light);
let second = encoder.encode(&chunk, &HashMap::new()).light;
assert_ne!(first, second);
assert_eq!(second, light_data(&chunk.sections, u64::MAX));
}
#[test]
fn light_masks_cover_the_world_plus_borders() {
let chunk = Chunk::empty(0, 0);
// A column with nothing around it has no light layers at all.
assert!(light_data(&chunk, 0).sky.is_empty());
let data = light_data(&chunk, u64::MAX);
assert!(light_data(&chunk.sections, 0).sky.is_empty());
let data = light_data(&chunk.sections, u64::MAX);
// Default sections are full sky light and no block light.
assert_eq!(data.sky.len(), SECTIONS + 1);
assert_eq!(data.block.len(), 0);
assert_eq!(data.sky[0][0], 0xFF);
assert!(horizon_protocol::buf::bit(&data.empty_block_mask, 5));
}
#[test]
fn a_nether_column_sends_its_sixteen_sections_without_sky_light() {
let chunk = Chunk::empty(0, 0);
let mut encoder = ChunkEncoder::new(
[("minecraft:air".into(), false)],
&Builtin::default(),
&[],
&[],
);
let overworld = encoder.encode(&chunk, &HashMap::new());
encoder.set_dimension(0, 256, false);
let nether = encoder.encode(&chunk, &HashMap::new());
// An all-air section is the same bytes wherever it is.
let per_section = overworld.chunk.buffer.len() / SECTIONS;
assert_eq!(nether.chunk.buffer.len(), per_section * 16);
assert!(nether.light.sky.is_empty() && nether.light.sky_mask.is_empty());
// Block light layers: one below and one above the sixteen sections.
assert!(horizon_protocol::buf::bit(
&nether.light.empty_block_mask,
17
));
assert!(!horizon_protocol::buf::bit(
&nether.light.empty_block_mask,
18
));
}
}
+178 -9
View File
@@ -1,4 +1,5 @@
//! One accepted connection: handshake, status ping, offline-mode login and the
//! One accepted connection: handshake, status ping, login (offline, or online
//! with encryption and the session service's verdict) and the
//! configuration phase (ServerStatusPacketListenerImpl,
//! ServerLoginPacketListenerImpl, ServerConfigurationPacketListenerImpl). A
//! player that completes configuration continues in the play state: the
@@ -12,7 +13,7 @@ use super::{
use horizon_protocol::{
PROTOCOL_VERSION,
connection::{ConnReader, ConnWriter, Connection},
crypto::offline_uuid,
crypto::{offline_uuid, server_hash, uuid_string},
packets::{
Empty,
configuration::{self as cfg, ClientInformation, KnownPack},
@@ -25,7 +26,7 @@ use std::{
net::TcpStream,
sync::{
Arc, Mutex, PoisonError,
atomic::{AtomicI32, AtomicI64, AtomicUsize, Ordering},
atomic::{AtomicI32, AtomicI64, AtomicU32, AtomicUsize, Ordering},
mpsc::{Receiver, RecvTimeoutError, Sender, channel},
},
time::{Duration, Instant},
@@ -354,6 +355,145 @@ fn serve_status(c: &mut Connection, shared: &Shared) -> Result<(), String> {
}
}
/// ServerLoginPacketListenerImpl.getUserName: the name and the address
/// (Connection.getLoggableAddress, `/ip:port` as InetSocketAddress prints it).
fn user_name(name: &str, address: std::net::SocketAddr, log: &super::NetLog) -> String {
if log.log_ips {
format!("{name} (/{address})")
} else {
format!("{name} (<ip address withheld>)")
}
}
/// ServerLoginPacketListenerImpl.disconnect: log the reason's text and send
/// it. Returns the text, for the "lost connection" line that follows.
fn refuse(
c: &mut Connection,
shared: &Shared,
thread: &str,
user: &str,
reason: &horizon_world::nbt::Tag,
) -> String {
let text = shared
.config
.log
.as_ref()
.map(|log| horizon_protocol::text::plain(reason, &log.lang))
.unwrap_or_default();
if let Some(log) = &shared.config.log {
(log.write)(thread, "INFO", &format!("Disconnecting {user}: {text}"));
}
login_disconnect(c, reason);
text
}
/// ServerLoginPacketListenerImpl.onDisconnect, once the server thread sees
/// the connection closed: by a refusal, or by the client ("Disconnected").
fn lost(shared: &Shared, user: &str, text: &str) {
if let Some(log) = &shared.config.log {
(log.write)(
"Server thread",
"INFO",
&format!("{user} lost connection: {text}"),
);
}
}
/// UNIQUE_THREAD_ID: the User Authenticator threads are numbered from 1.
static AUTHENTICATORS: AtomicU32 = AtomicU32::new(0);
/// ServerLoginPacketListenerImpl.handleKey and the User Authenticator
/// thread: check the client's answer to the encryption request, encrypt the
/// connection, and ask the session service whether the player joined with
/// this server's hash. The profile, or the text of the refusal.
fn authenticate(
c: &mut Connection,
shared: &Shared,
online: &super::OnlineMode,
name: &str,
address: std::net::SocketAddr,
user: &str,
) -> Result<Result<(u128, Vec<login::Property>), String>, String> {
let e = |e: horizon_protocol::Error| e.to_string();
let mut challenge = [0u8; 4];
horizon_protocol::crypto::random_bytes(&mut challenge).map_err(e)?;
c.send(
&login::Clientbound::Hello(login::Hello {
server_id: String::new(),
public_key: online.public_der.clone(),
challenge: challenge.to_vec(),
should_authenticate: true,
})
.encode(),
)
.map_err(e)?;
let (id, payload) = c.recv().map_err(e)?;
let key = match login::Serverbound::decode(id, &payload).map_err(e)? {
login::Serverbound::Key(k) => k,
_ => return Err("Unexpected packet during login".into()),
};
// ServerboundKeyPacket.isChallengeValid and getSecretKey.
let protocol_error = || "Protocol error".to_owned();
if online.key.decrypt(&key.challenge).ok().as_deref() != Some(&challenge[..]) {
return Err(protocol_error());
}
let secret: [u8; 16] = online
.key
.decrypt(&key.key)
.ok()
.and_then(|s| s.try_into().ok())
.ok_or_else(protocol_error)?;
let digest = server_hash("", &secret, &online.public_der);
c.enable_encryption(&secret);
let thread = format!(
"User Authenticator #{}",
AUTHENTICATORS.fetch_add(1, Ordering::Relaxed) + 1
);
let log = |level: &str, line: &str| {
if let Some(log) = &shared.config.log {
(log.write)(&thread, level, line);
}
};
let ip = online.prevent_proxy.then(|| address.ip());
match crate::auth::has_joined(name, &digest, ip) {
Ok(Some(profile)) => {
log(
"INFO",
&format!("UUID of player {name} is {}", uuid_string(profile.uuid)),
);
Ok(Ok((profile.uuid, profile.properties)))
}
Ok(None) => {
let text = refuse(
c,
shared,
&thread,
user,
&translatable("multiplayer.disconnect.unverified_username", &[]),
);
log(
"ERROR",
&format!("Username '{name}' tried to join with an invalid session"),
);
Ok(Err(text))
}
Err(_) => {
let text = refuse(
c,
shared,
&thread,
user,
&translatable("multiplayer.disconnect.authservers_down", &[]),
);
log(
"ERROR",
"Couldn't verify username because servers are unavailable",
);
Ok(Err(text))
}
}
}
fn serve_login(
mut c: Connection,
address: std::net::SocketAddr,
@@ -372,14 +512,36 @@ fn serve_login(
);
return Ok(());
}
// Offline mode: the profile is derived from the name (PlayerList.canPlayerLogin
// then rejects duplicates and a full server).
let uuid = offline_uuid(&hello.name);
let user = shared
.config
.log
.as_ref()
.map(|log| user_name(&hello.name, address, log))
.unwrap_or_default();
// handleHello: online mode authenticates first; offline mode derives the
// profile from the name.
let (uuid, properties) = match &shared.config.online {
Some(online) => match authenticate(&mut c, shared, online, &hello.name, address, &user) {
Ok(Ok(profile)) => profile,
Ok(Err(refused)) => {
lost(shared, &user, &refused);
return Ok(());
}
Err(err) => {
lost(shared, &user, "Disconnected");
return Err(err);
}
},
None => (offline_uuid(&hello.name), Vec::new()),
};
// verifyLoginAndFinishConnectionSetup: PlayerList.canPlayerLogin, then
// duplicates and a full server.
if let Some(reason) = shared.try_admit(address, uuid, &hello.name) {
login_disconnect(&mut c, &reason);
let text = refuse(&mut c, shared, "Server thread", &user, &reason);
lost(shared, &user, &text);
return Ok(());
}
let result = login_and_configure(&mut c, shared, uuid, &hello.name);
let result = login_and_configure(&mut c, shared, uuid, &hello.name, properties);
match result {
Ok(Some(parts)) => {
play(c, shared, parts, address);
@@ -391,6 +553,9 @@ fn serve_login(
}
Err(err) => {
shared.release(uuid);
// ServerConfigurationPacketListenerImpl.onDisconnect.
let profile = format!("{} ({})", hello.name, uuid_string(uuid));
lost(shared, &profile, "Disconnected");
Err(err)
}
}
@@ -399,6 +564,7 @@ fn serve_login(
struct Parts {
uuid: u128,
name: String,
properties: Vec<login::Property>,
info: ClientInformation,
brand: String,
}
@@ -408,6 +574,7 @@ fn login_and_configure(
shared: &Arc<Shared>,
uuid: u128,
name: &str,
properties: Vec<login::Property>,
) -> Result<Option<Parts>, String> {
let e = |e: horizon_protocol::Error| e.to_string();
// ServerLoginPacketListenerImpl: memory connections are not compressed.
@@ -422,7 +589,7 @@ fn login_and_configure(
profile: login::GameProfile {
uuid,
name: name.to_owned(),
properties: Vec::new(),
properties: properties.clone(),
},
session: uuid,
})
@@ -501,6 +668,7 @@ fn login_and_configure(
Ok(Some(Parts {
uuid,
name: name.to_owned(),
properties,
info,
brand,
}))
@@ -527,6 +695,7 @@ fn play(c: Connection, shared: &Arc<Shared>, parts: Parts, address: std::net::So
conn: conn_id,
uuid: parts.uuid,
name: parts.name,
properties: parts.properties,
info: parts.info,
brand: parts.brand,
sender,
+22
View File
@@ -46,6 +46,8 @@ pub struct Guest {
pub left_reason: String,
pub uuid: u128,
pub name: String,
/// The profile's properties, for the player list (skins).
pub properties: Vec<horizon_protocol::packets::login::Property>,
pub entity_id: i32,
pub sender: PlayerSender,
pub latency: Arc<AtomicI32>,
@@ -136,6 +138,19 @@ pub struct Guest {
pub drag: Option<(u8, Vec<usize>)>,
/// The compound this player was loaded from, for fields Horizon does not model.
pub saved: Option<horizon_world::nbt::Tag>,
/// `ServerPlayer.recipeBook`.
pub recipe_book: crate::recipe_book::Settings,
/// `PlayerAdvancements`: the criteria obtained, whether they came from
/// the player's file, the advancements the client was last told it may
/// see (empty before the first packet), and those whose progress
/// changed since (`progressChanged`).
pub advancements: crate::advancements::Progress,
pub advancements_loaded: bool,
pub advancements_visible: Vec<bool>,
pub advancements_changed: std::collections::BTreeSet<usize>,
/// Recipes unlocked since the client was last told
/// (`ServerRecipeBook.addRecipes` sends them).
pub recipes_unlocked: Vec<String>,
}
impl Guest {
@@ -150,6 +165,7 @@ impl Guest {
left_reason: String::new(),
uuid: j.uuid,
name: j.name,
properties: j.properties,
entity_id,
sender: j.sender,
latency: j.latency,
@@ -214,6 +230,12 @@ impl Guest {
next_window: 0,
drag: None,
saved: None,
recipe_book: Default::default(),
advancements: Default::default(),
advancements_loaded: false,
advancements_visible: Vec::new(),
advancements_changed: Default::default(),
recipes_unlocked: Vec::new(),
}
}
pub fn send(&self, packet: &play::Clientbound) {
+181 -16
View File
@@ -186,9 +186,12 @@ impl Hub {
.id("minecraft:chat_type", "minecraft:chat")
.unwrap_or(0);
let dimension_type = sync
.id("minecraft:dimension_type", "minecraft:overworld")
.id("minecraft:dimension_type", &config.dimension)
.unwrap_or(0);
let clock_ids = (0..sync.dynamic.len("minecraft:world_clock") as i32).collect();
let mut encoder = encoder;
let d = horizon_protocol::registry::DimensionType::vanilla(&config.dimension);
encoder.set_dimension(d.min_y, d.height, d.has_skylight);
Self {
lan,
config,
@@ -397,7 +400,12 @@ impl Hub {
play::PlayerInfo {
uuid,
name: Some(name.to_owned()),
properties: Vec::new(),
properties: self
.guests
.iter()
.find(|g| g.uuid == uuid)
.map(|g| g.properties.clone())
.unwrap_or_default(),
chat_session: None,
game_mode: Some(mode),
listed: Some(true),
@@ -509,12 +517,18 @@ impl Hub {
g.send(&raw(ids::UPDATE_RECIPES, self.sync.recipes.clone()));
// PlayerList.sendPlayerPermissionLevel, then the recipe book.
self.send_permission_level(i);
// ServerRecipeBook.sendInitialRecipeBook: each book's open and
// filtering flags, then every known recipe.
let g = &self.guests[i];
let book = &g.recipe_book;
let settings = (0..4)
.flat_map(|b| [u8::from(book.open[b]), u8::from(book.filtering[b])])
.collect();
g.send(&raw(ids::RECIPE_BOOK_SETTINGS, settings));
g.send(&raw(
ids::RECIPE_BOOK_SETTINGS,
vec![0; 8], // four books, each closed and unfiltered
ids::RECIPE_BOOK_ADD,
self.sync.advancements.initial_recipe_book(book, &self.sync),
));
g.send(&raw(ids::RECIPE_BOOK_ADD, vec![0, 1])); // no entries, replace
// The others hear of the newcomer before it joins the list.
self.broadcast_except(
conn,
@@ -731,11 +745,12 @@ impl Hub {
}));
}
/// ClientboundSetDefaultSpawnPositionPacket for the level's respawn data.
/// ClientboundSetDefaultSpawnPositionPacket for the level's respawn data
/// (the world spawn, in the Overworld wherever the player is).
fn default_spawn(&self, spawn: [f64; 3]) -> C {
C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition {
pos: play::GlobalPos {
dimension: self.config.dimension.clone(),
dimension: "minecraft:overworld".into(),
pos: [
spawn[0].floor() as i32,
spawn[1].floor() as i32,
@@ -921,7 +936,9 @@ impl Hub {
.iter()
.map(|g| (g.uuid, g.latency.load(Ordering::Relaxed)))
.collect();
if self.ticks.is_multiple_of(100) && !latencies.is_empty() {
// PlayerList.tick: UPDATE_LATENCY once `++sendAllPlayerInfoIn > 600`,
// so on the 601st tick, then every 601.
if self.ticks.is_multiple_of(601) && !latencies.is_empty() {
let entries = latencies
.iter()
.map(|(uuid, latency)| play::PlayerInfo {
@@ -1408,15 +1425,29 @@ impl Hub {
id: g.entity_id,
values: vec![(9, serializer::FLOAT, Value::Float(g.health))],
}));
// ServerPlayer.tick's CriteriaTriggers.TICK, then flushDirty.
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
let first = self.sync.advancements.first_tick(&self.sync, now);
if let Some(add) = first.recipe_book_add {
g.send(&raw(ids::RECIPE_BOOK_ADD, add));
// ServerPlayer.tick's CriteriaTriggers.TICK, then flushDirty. A
// player who has been here has had the tick's criteria already.
if !g.advancements_loaded {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
let sync = self.sync.clone();
let g = &mut self.guests[i];
let first = sync.advancements.first_tick(
&sync,
now,
&mut g.advancements,
&mut g.recipe_book,
);
if let Some(add) = first.recipe_book_add {
g.send(&raw(ids::RECIPE_BOOK_ADD, add));
}
g.send(&raw(ids::UPDATE_ADVANCEMENTS, first.update_advancements));
g.advancements_visible = sync.advancements.visibility(&g.advancements);
g.advancements_changed.clear();
} else {
self.flush_advancements(i, true);
}
g.send(&raw(ids::UPDATE_ADVANCEMENTS, first.update_advancements));
}
let health = {
let g = &self.guests[i];
@@ -1467,6 +1498,65 @@ impl Hub {
}
}
/// `PlayerAdvancements.flushDirty` and the recipes the player unlocked
/// since (`ServerRecipeBook.addRecipes`), once the player's first tick
/// has sent their advancements.
pub fn flush_progress(&mut self, conn: u32) {
if let Some(i) = self.guests.iter().position(|g| g.conn == conn)
&& self.guests[i].sent_health.is_some()
{
self.flush_advancements(i, true);
}
}
fn flush_advancements(&mut self, i: usize, show: bool) {
let sync = self.sync.clone();
let g = &mut self.guests[i];
let unlocked = std::mem::take(&mut g.recipes_unlocked);
if let Some(add) = sync.advancements.recipes_added(&unlocked, &sync) {
g.send(&raw(ids::RECIPE_BOOK_ADD, add));
}
let changed = std::mem::take(&mut g.advancements_changed);
if let Some(update) = sync.advancements.update(
&sync,
&g.advancements,
&mut g.advancements_visible,
&changed,
show,
) {
g.send(&raw(ids::UPDATE_ADVANCEMENTS, update));
}
}
/// ClientboundAwardStatsPacket (`ServerStatsCounter.sendStats`): each
/// statistic as its type and value by network id (`Stat.STREAM_CODEC`),
/// then its count. Statistics the registries don't know are left out.
pub fn send_stats(&self, conn: u32, stats: &[(String, String, i32)]) {
let known: Vec<(i32, i32, i32)> = stats
.iter()
.filter_map(|(ty, key, count)| {
let values = match ty.as_str() {
"minecraft:mined" => "minecraft:block",
"minecraft:killed" | "minecraft:killed_by" => "minecraft:entity_type",
"minecraft:custom" => "minecraft:custom_stat",
_ => "minecraft:item",
};
Some((
self.sync.id("minecraft:stat_type", ty)?,
self.sync.id(values, key)?,
*count,
))
})
.collect();
let mut w = horizon_protocol::buf::Writer::new();
w.varint(known.len() as i32);
for (ty, value, count) in known {
w.varint(ty);
w.varint(value);
w.varint(count);
}
self.send_to(conn, &raw(ids::AWARD_STATS, w.data));
}
// ---- incoming ------------------------------------------------------
/// The squared movement past 1.0E-5F (handlePlayerKnownMovement).
@@ -1752,6 +1842,81 @@ impl Hub {
// ServerPlayer.initInventoryMenu.
self.send_inventory(i);
}
/// The level the players are in: the server holds one at a time, and the
/// hub's packets name it.
pub fn set_dimension(&mut self, dimension: &str) {
self.config.dimension = dimension.to_owned();
self.dimension_type = self
.sync
.id("minecraft:dimension_type", dimension)
.unwrap_or(0);
let d = horizon_protocol::registry::DimensionType::vanilla(dimension);
self.encoder
.set_dimension(d.min_y, d.height, d.has_skylight);
}
/// ServerPlayer.teleport(TeleportTransition) into the level the hub now
/// names (`set_dimension`): ClientboundRespawnPacket keeping all data,
/// then vanilla's packet order. Nothing tracked in the old level is
/// removed one by one: the client drops its whole level.
pub fn change_level(&mut self, i: usize, at: [f64; 3], yaw: f32, ctx: &TickCtx) {
let mode = self.guests[i].game_mode;
let info = self.spawn_info(mode);
self.close_container_for(i);
let g = &mut self.guests[i];
g.tracker.clear();
g.sent_chunks.clear();
g.chunk_queue.clear();
g.center = None;
g.yaw = yaw;
g.position = at;
g.previous_position = at;
g.send(&C::Respawn(play::Respawn {
spawn: info,
// ClientboundRespawnPacket.KEEP_ALL_DATA.
keep: 3,
}));
g.send(&C::ChangeDifficulty(play::ChangeDifficulty {
difficulty: ctx.difficulty,
locked: ctx.difficulty_locked,
}));
self.send_permission_level(i);
self.teleport(i, None);
let g = &mut self.guests[i];
g.send(&C::PlayerAbilities(play::PlayerAbilities {
flags: g.ability_flags(),
flying_speed: 0.05,
walking_speed: 0.1,
}));
self.send_level_info(i, ctx);
// PlayerList.sendAllPlayerInfo: the inventory and the held slot.
self.send_inventory(i);
let g = &mut self.guests[i];
g.send(&C::SetHeldSlot(play::SetHeldSlot {
slot: g.selected as i32,
}));
self.send_active_effects(i);
let g = &mut self.guests[i];
// ServerPlayer.sendPostEffects.
g.send(&raw(ids::POST_EFFECTS, vec![0]));
// TeleportTransition.PLAY_PORTAL_SOUND.
g.send(&C::LevelEvent(play::LevelEvent {
kind: 1032,
pos: [0, 0, 0],
data: 0,
global: false,
}));
// lastSentExp, lastSentHealth and lastSentFood.
g.sent_health = None;
g.sent_xp = None;
let (cx, cz) = g.chunk();
g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter {
x: cx,
z: cz,
}));
g.center_sent = Some((cx, cz));
}
}
/// A packet Horizon sends as raw bytes (no fields worth a type).
+29
View File
@@ -20,6 +20,7 @@ pub mod menu;
pub mod playerdata;
mod recipes;
pub mod tracking;
pub mod waypoints;
pub use conn::{Holding, PlayerSender};
use horizon_protocol::packets::play;
@@ -58,6 +59,8 @@ pub struct Joined {
pub conn: u32,
pub uuid: u128,
pub name: String,
/// The profile's properties (skin textures, in online mode).
pub properties: Vec<horizon_protocol::packets::login::Property>,
pub info: ClientInformation,
pub brand: String,
pub sender: PlayerSender,
@@ -81,6 +84,27 @@ pub enum Out {
pub type LoginGate =
Arc<dyn Fn(SocketAddr, u128, &str) -> Option<horizon_world::nbt::Tag> + Send + Sync>;
/// online-mode=true: the key pair the server made at startup
/// (MinecraftServer.initializeKeyPair) and how players are verified.
pub struct OnlineMode {
pub key: horizon_protocol::rsa::RsaPrivateKey,
/// The public key as X.509 (PublicKey.getEncoded), sent in the hello.
pub public_der: Vec<u8>,
/// prevent-proxy-connections: the session service also checks the address.
pub prevent_proxy: bool,
}
/// The dedicated server's log for the login phase: (thread, level, line)
/// written as vanilla's Log4j would, and the language that turns a
/// disconnect reason into its text (Component.getString).
#[derive(Clone)]
pub struct NetLog {
pub write: Arc<dyn Fn(&str, &str, &str) + Send + Sync>,
pub lang: Arc<horizon_protocol::text::Language>,
/// log-ips: addresses in the log, or "<ip address withheld>".
pub log_ips: bool,
}
/// How the server side of the network behaves: an integrated server's LAN
/// uses the defaults, a dedicated server takes them from server.properties.
#[derive(Clone)]
@@ -109,6 +133,9 @@ pub struct NetConfig {
/// Ops bypass a full server (ServerOpList.canBypassPlayerLimit).
pub bypasses_limit: Option<Arc<dyn Fn(u128) -> bool + Send + Sync>>,
pub gate: Option<LoginGate>,
/// Online mode: players are authenticated (none on a LAN world).
pub online: Option<Arc<OnlineMode>>,
pub log: Option<NetLog>,
}
impl NetConfig {
/// IntegratedServer.publishServer.
@@ -128,6 +155,8 @@ impl NetConfig {
listen: true,
bypasses_limit: None,
gate: None,
online: None,
log: None,
}
}
}
@@ -70,6 +70,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.game_mode = level.mode();
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.saved = level.player_extra.clone();
guest.recipe_book = level.recipe_book.clone();
if level.ender_items.len() == 27 {
guest.ender_items = level.ender_items.clone();
}
@@ -126,6 +127,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
level.selected_slot = guest.selected as i32;
level.on_ground = guest.on_ground;
level.player_extra = guest.saved.clone();
level.recipe_book = guest.recipe_book.clone();
level.ender_items = guest.ender_items.clone();
level.inventory.clear();
level.inventory_components.clear();
+643
View File
@@ -0,0 +1,643 @@
//! The locator bar for remote players: ServerWaypointManager and
//! WaypointTransmitter's connections, for players (the transmitters vanilla has
//! by default: `waypoint_transmit_range` is 0 for every other entity).
//!
//! Vanilla updates a player's connections each time the player's position
//! changes (`Entity.setPosRaw`, then `ServerChunkCache.move`). The hub sees the
//! position once a tick, after the moves it handled, and updates from there:
//! the same packets, since a client sends one move a tick. Hiding (crouching,
//! invisibility, a carved pumpkin or a mob head worn) changes
//! `waypoint_transmit_range` and tracks or untracks the waypoint, as
//! `LivingEntity.onAttributeUpdated` does; joining or leaving a team remakes the
//! connections with the team's colour (`ServerScoreboard.updatePlayerWaypoint`).
use horizon_protocol::packets::play::{
Clientbound as C, TrackedWaypoint, WaypointId, WaypointTarget, waypoint_operation,
};
use std::collections::HashMap;
/// `Player.createAttributes`: both waypoint ranges.
pub const PLAYER_RANGE: f64 = 6.0e7;
/// `WaypointTransmitter.REALLY_FAR_DISTANCE`.
const REALLY_FAR: f32 = 332.0;
/// `EntityAzimuthConnection.update`: half a degree.
const AZIMUTH_STEP: f32 = 0.008_726_646;
/// Items that hide their wearer (`Waypoint.addHideAttribute` on the head slot).
pub const HIDING_HEADS: [&str; 8] = [
"minecraft:carved_pumpkin",
"minecraft:skeleton_skull",
"minecraft:wither_skeleton_skull",
"minecraft:player_head",
"minecraft:zombie_head",
"minecraft:creeper_head",
"minecraft:dragon_head",
"minecraft:piglin_head",
];
/// A team colour as the locator bar draws it (`Waypoint.Icon.cloneAndAssignStyle`:
/// `TeamColor.rgb()`, black lightened so it shows).
pub fn team_rgb(color: &str) -> Option<i32> {
let rgb = match color {
"black" => return Some(-13_619_152),
"dark_blue" => 0x0000AA,
"dark_green" => 0x00AA00,
"dark_aqua" => 0x00AAAA,
"dark_red" => 0xAA0000,
"dark_purple" => 0xAA00AA,
"gold" => 0xFFAA00,
"gray" => 0xAAAAAA,
"dark_gray" => 0x555555,
"blue" => 0x5555FF,
"green" => 0x55FF55,
"aqua" => 0x55FFFF,
"red" => 0xFF5555,
"light_purple" => 0xFF55FF,
"yellow" => 0xFFFF55,
"white" => 0xFFFFFF,
_ => return None,
};
Some(rgb)
}
/// Waypoint.Icon.
#[derive(Clone, Debug, PartialEq)]
pub struct Icon {
pub style: String,
pub color: Option<i32>,
}
impl Default for Icon {
fn default() -> Self {
Self {
style: "minecraft:default".into(),
color: None,
}
}
}
/// A player as the waypoint manager sees them this tick.
#[derive(Clone, Debug)]
pub struct Player {
pub uuid: u128,
/// The connection that receives the player's locator bar (None: the host,
/// whose own game draws it).
pub conn: Option<u32>,
pub position: [f64; 3],
pub spectator: bool,
/// `waypoint_transmit_range`: 0 while hidden.
pub transmit_range: f64,
pub receive_range: f64,
/// `Entity.firstTick`: the player has not ticked since joining.
pub first_tick: bool,
/// The chunk view radius (`ChunkMap.getPlayerViewDistance`).
pub view_distance: i32,
/// The player's team and its colour (`TeamColor.rgb`).
pub team: Option<(String, Option<i32>)>,
/// The icon `/waypoint modify` set.
pub icon: Icon,
}
impl Player {
fn block(&self) -> [i32; 3] {
self.position.map(|v| v.floor() as i32)
}
fn chunk(&self) -> [i32; 2] {
let [x, _, z] = self.block();
[x >> 4, z >> 4]
}
/// `Entity.distanceTo`.
fn distance_to(&self, other: &Player) -> f32 {
let d2: f64 = (0..3)
.map(|k| (self.position[k] - other.position[k]).powi(2))
.sum();
d2.sqrt() as f32
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Kind {
Block([i32; 3]),
Chunk([i32; 2]),
Azimuth(f32),
}
#[derive(Clone, Debug)]
struct Connection {
kind: Kind,
icon: Icon,
}
/// What the manager remembers of a player between ticks.
struct Memo {
position: [f64; 3],
/// The centre of the player's ChunkTrackingView (`ChunkMap.move`).
view_center: [i32; 2],
transmitting: bool,
team: Option<(String, Option<i32>)>,
}
/// ServerWaypointManager for one level.
#[derive(Default)]
pub struct Waypoints {
/// The transmitters, in the order they were tracked.
waypoints: Vec<u128>,
/// The receivers, in the order they joined.
players: Vec<u128>,
/// Connections by receiver, then source.
connections: HashMap<u128, Vec<(u128, Connection)>>,
memo: HashMap<u128, Memo>,
/// The `locator_bar` game rule as last seen.
enabled: Option<bool>,
}
/// One tick's players, and the packets for their connections.
struct Tick<'a> {
players: HashMap<u128, &'a Player>,
view: HashMap<u128, ([i32; 2], i32)>,
/// Players a respawn replaced this tick: a new ServerPlayer, on its first tick.
fresh: &'a [u128],
enabled: bool,
out: Vec<(u32, C)>,
}
impl Tick<'_> {
fn send(
&mut self,
receiver: u128,
source: u128,
operation: i32,
icon: &Icon,
target: WaypointTarget,
) {
let Some(conn) = self.players.get(&receiver).and_then(|p| p.conn) else {
return;
};
self.out.push((
conn,
C::TrackedWaypoint(TrackedWaypoint {
operation,
id: WaypointId::Uuid(source),
style: icon.style.clone(),
color: icon.color,
target,
}),
));
}
fn connect(&mut self, receiver: u128, source: u128, c: &Connection) {
let target = match c.kind {
Kind::Block(p) => WaypointTarget::Block(p),
Kind::Chunk(p) => WaypointTarget::Chunk(p),
Kind::Azimuth(a) => WaypointTarget::Azimuth(a),
};
self.send(receiver, source, waypoint_operation::TRACK, &c.icon, target);
}
/// `ClientboundTrackedWaypointPacket.removeWaypoint`: an empty waypoint with the null icon.
fn disconnect(&mut self, receiver: u128, source: u128) {
self.send(
receiver,
source,
waypoint_operation::UNTRACK,
&Icon::default(),
WaypointTarget::Empty,
);
}
/// `ChunkTrackingView.isInViewDistance` of the receiver's view.
fn chunk_visible(&self, [x, z]: [i32; 2], receiver: u128) -> bool {
let Some(&([cx, cz], r)) = self.view.get(&receiver) else {
return false;
};
let dx = i64::from(((x - cx).abs() - 1).max(0));
let dz = i64::from(((z - cz).abs() - 1).max(0));
dx * dx + dz * dz < i64::from(r) * i64::from(r)
}
/// `WaypointTransmitter.doesSourceIgnoreReceiver`.
fn ignores(&self, source: &Player, receiver: &Player) -> bool {
if receiver.spectator {
return false;
}
if source.spectator {
return true;
}
let range = source.transmit_range.min(receiver.receive_range);
f64::from(source.distance_to(receiver)) >= range
}
fn really_far(source: &Player, receiver: &Player) -> bool {
source.distance_to(receiver) > REALLY_FAR
}
/// `EntityAzimuthConnection`: the angle of the receiver seen from the source,
/// `Mth.atan2` of the offset turned clockwise.
fn azimuth(source: &Player, receiver: &Player) -> f32 {
let d = [0, 1, 2].map(|k| receiver.position[k] - source.position[k]);
horizon_core::geometry::trig::atan2(d[0], -d[2]) as f32
}
/// `LivingEntity.makeWaypointConnectionWith`.
fn make(&self, source: u128, receiver: u128) -> Option<Connection> {
let (s, r) = (self.players.get(&source)?, self.players.get(&receiver)?);
if s.first_tick || self.fresh.contains(&source) || source == receiver || self.ignores(s, r)
{
return None;
}
// Waypoint.Icon.cloneAndAssignStyle: the icon's colour, else the team's.
let mut icon = s.icon.clone();
if icon.color.is_none() {
icon.color = s.team.as_ref().and_then(|t| t.1);
}
let kind = if Self::really_far(s, r) {
Kind::Azimuth(Self::azimuth(s, r))
} else if !self.chunk_visible(s.chunk(), receiver) {
Kind::Chunk(s.chunk())
} else {
Kind::Block(s.block())
};
Some(Connection { kind, icon })
}
/// `Connection.isBroken` for each kind.
fn broken(&self, c: &Connection, source: u128, receiver: u128) -> bool {
let (Some(s), Some(r)) = (self.players.get(&source), self.players.get(&receiver)) else {
return true;
};
match c.kind {
Kind::Block(last) => {
let now = s.block();
(0..3).map(|k| (now[k] - last[k]).abs()).sum::<i32>() > 1 || self.ignores(s, r)
}
Kind::Chunk(last) => {
let now = s.chunk();
let moved = (now[0] - last[0]).abs().max((now[1] - last[1]).abs());
moved > 1 || self.ignores(s, r) || self.chunk_visible(last, receiver)
}
Kind::Azimuth(_) => {
self.ignores(s, r)
|| self.chunk_visible(s.chunk(), receiver)
|| !Self::really_far(s, r)
}
}
}
/// `Connection.update`: the packet when the waypoint moved.
fn update(&mut self, c: &mut Connection, source: u128, receiver: u128) {
let (Some(s), Some(r)) = (self.players.get(&source), self.players.get(&receiver)) else {
return;
};
let target = match &mut c.kind {
Kind::Block(last) => {
let now = s.block();
if now == *last {
return;
}
*last = now;
WaypointTarget::Block(now)
}
Kind::Chunk(last) => {
let now = s.chunk();
if now == *last {
return;
}
*last = now;
WaypointTarget::Chunk(now)
}
Kind::Azimuth(last) => {
let now = Self::azimuth(s, r);
if (now - *last).abs() <= AZIMUTH_STEP {
return;
}
*last = now;
WaypointTarget::Azimuth(now)
}
};
let icon = c.icon.clone();
self.send(receiver, source, waypoint_operation::UPDATE, &icon, target);
}
}
impl Waypoints {
fn connection(&mut self, receiver: u128, source: u128) -> Option<&mut Connection> {
self.connections
.get_mut(&receiver)?
.iter_mut()
.find(|(s, _)| *s == source)
.map(|(_, c)| c)
}
fn put(&mut self, receiver: u128, source: u128, c: Connection) {
let row = self.connections.entry(receiver).or_default();
match row.iter_mut().find(|(s, _)| *s == source) {
Some(slot) => slot.1 = c,
None => row.push((source, c)),
}
}
fn take(&mut self, receiver: u128, source: u128) -> Option<Connection> {
let row = self.connections.get_mut(&receiver)?;
let i = row.iter().position(|(s, _)| *s == source)?;
Some(row.remove(i).1)
}
/// `createConnection`.
fn create_connection(&mut self, t: &mut Tick, receiver: u128, source: u128) {
if receiver == source || !t.enabled {
return;
}
match t.make(source, receiver) {
Some(c) => {
t.connect(receiver, source, &c);
self.put(receiver, source, c);
}
None => {
if self.take(receiver, source).is_some() {
t.disconnect(receiver, source);
}
}
}
}
/// `updateConnection`.
fn update_connection(&mut self, t: &mut Tick, receiver: u128, source: u128) {
if receiver == source || !t.enabled {
return;
}
let Some(mut c) = self.connection(receiver, source).cloned() else {
return;
};
if !t.broken(&c, source, receiver) {
t.update(&mut c, source, receiver);
self.put(receiver, source, c);
return;
}
match t.make(source, receiver) {
Some(new) => {
t.connect(receiver, source, &new);
self.put(receiver, source, new);
}
None => {
t.disconnect(receiver, source);
self.take(receiver, source);
}
}
}
/// `trackWaypoint`.
fn track(&mut self, t: &mut Tick, source: u128) {
if !self.waypoints.contains(&source) {
self.waypoints.push(source);
}
for receiver in self.players.clone() {
self.create_connection(t, receiver, source);
}
}
/// `updateWaypoint`.
fn update_waypoint(&mut self, t: &mut Tick, source: u128) {
if !self.waypoints.contains(&source) {
return;
}
for receiver in self.players.clone() {
if self.connection(receiver, source).is_some() {
self.update_connection(t, receiver, source);
} else {
self.create_connection(t, receiver, source);
}
}
}
/// `untrackWaypoint`.
fn untrack(&mut self, t: &mut Tick, source: u128) {
for receiver in self.players.clone() {
if self.take(receiver, source).is_some() {
t.disconnect(receiver, source);
}
}
self.waypoints.retain(|w| *w != source);
}
/// `addPlayer`.
fn add_player(&mut self, t: &mut Tick, player: u128, transmitting: bool) {
if !self.players.contains(&player) {
self.players.push(player);
}
for source in self.waypoints.clone() {
self.create_connection(t, player, source);
}
if transmitting {
self.track(t, player);
}
}
/// `updatePlayer`.
fn update_player(&mut self, t: &mut Tick, player: u128) {
for source in self.waypoints.clone() {
if self.connection(player, source).is_some() {
self.update_connection(t, player, source);
} else {
self.create_connection(t, player, source);
}
}
}
/// `removePlayer`.
fn remove_player(&mut self, t: &mut Tick, player: u128) {
for (source, _) in self.connections.remove(&player).unwrap_or_default() {
t.disconnect(player, source);
}
self.untrack(t, player);
self.players.retain(|p| *p != player);
}
/// `breakAllConnections`.
fn break_all(&mut self, t: &mut Tick) {
for receiver in self.players.clone() {
for (source, _) in self.connections.remove(&receiver).unwrap_or_default() {
t.disconnect(receiver, source);
}
}
self.connections.clear();
}
/// One tick: players who left, joined, moved, hid or changed team, and the
/// `locator_bar` game rule. `respawned` players are removed and added again,
/// as `PlayerList.respawn` replaces the ServerPlayer. Returns the packets for
/// each connection.
pub fn tick(
&mut self,
players: &[Player],
respawned: &[u128],
locator_bar: bool,
) -> Vec<(u32, C)> {
let mut t = Tick {
players: players.iter().map(|p| (p.uuid, p)).collect(),
view: HashMap::new(),
fresh: respawned,
enabled: locator_bar,
out: Vec::new(),
};
// Vanilla reads the rule when it connects; changing it breaks or remakes
// every connection (MinecraftServer.onGameRuleChanged).
let was = self.enabled.replace(locator_bar);
for (uuid, memo) in &self.memo {
if let Some(p) = t.players.get(uuid) {
t.view.insert(*uuid, (memo.view_center, p.view_distance));
}
}
// Players who left, and the ServerPlayer a respawn replaced.
let gone: Vec<u128> = self
.players
.iter()
.copied()
.filter(|uuid| !t.players.contains_key(uuid) || respawned.contains(uuid))
.collect();
for uuid in gone {
self.remove_player(&mut t, uuid);
self.memo.remove(&uuid);
}
if was == Some(true) && !locator_bar {
self.break_all(&mut t);
}
// Players who joined (PlayerList.placeNewPlayer: addPlayer).
for p in players {
if self.memo.contains_key(&p.uuid) {
continue;
}
let center = p.chunk();
t.view.insert(p.uuid, (center, p.view_distance));
let transmitting = p.transmit_range > 0.0;
self.memo.insert(
p.uuid,
Memo {
position: p.position,
view_center: center,
transmitting,
team: p.team.clone(),
},
);
if p.receive_range > 0.0 {
self.add_player(&mut t, p.uuid, transmitting);
} else if transmitting {
self.track(&mut t, p.uuid);
}
}
if was == Some(false) && locator_bar {
for player in self.players.clone() {
self.update_player(&mut t, player);
}
}
for p in players {
let memo = &self.memo[&p.uuid];
// Entity.setPosRaw, then ServerChunkCache.move.
if memo.position != p.position {
let moved_view = memo.view_center != p.chunk();
let transmitting = memo.transmitting;
self.memo.get_mut(&p.uuid).unwrap().position = p.position;
if !p.first_tick {
if transmitting {
self.update_waypoint(&mut t, p.uuid);
}
if p.receive_range > 0.0 {
self.update_player(&mut t, p.uuid);
}
}
if moved_view {
self.memo.get_mut(&p.uuid).unwrap().view_center = p.chunk();
t.view.insert(p.uuid, (p.chunk(), p.view_distance));
}
if p.receive_range > 0.0 {
self.update_player(&mut t, p.uuid);
}
}
// LivingEntity.onAttributeUpdated(WAYPOINT_TRANSMIT_RANGE).
let transmitting = p.transmit_range > 0.0;
if transmitting != self.memo[&p.uuid].transmitting {
self.memo.get_mut(&p.uuid).unwrap().transmitting = transmitting;
if transmitting {
self.track(&mut t, p.uuid);
} else {
self.untrack(&mut t, p.uuid);
}
}
// ServerScoreboard: a team joined, left or recoloured remakes the connections.
if p.team != self.memo[&p.uuid].team {
self.memo.get_mut(&p.uuid).unwrap().team = p.team.clone();
for receiver in self.players.clone() {
self.create_connection(&mut t, receiver, p.uuid);
}
}
}
t.out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn player(uuid: u128, conn: u32, position: [f64; 3]) -> Player {
Player {
uuid,
conn: Some(conn),
position,
spectator: false,
transmit_range: PLAYER_RANGE,
receive_range: PLAYER_RANGE,
first_tick: false,
view_distance: 4,
team: None,
icon: Icon::default(),
}
}
/// The packets to `conn`, as (operation, target).
fn to(out: &[(u32, C)], conn: u32) -> Vec<(i32, WaypointTarget)> {
out.iter()
.filter(|(c, _)| *c == conn)
.map(|(_, p)| match p {
C::TrackedWaypoint(w) => (w.operation, w.target),
other => panic!("{other:?}"),
})
.collect()
}
#[test]
fn a_new_player_shows_once_it_moves() {
let mut w = Waypoints::default();
let a = player(1, 10, [0.5, 100.0, 0.5]);
let mut b = player(2, 20, [5.5, 100.0, 0.5]);
b.first_tick = true;
w.tick(std::slice::from_ref(&a), &[], true);
let out = w.tick(&[a.clone(), b.clone()], &[], true);
// B gets A at once; A sees nothing of B while B hasn't ticked.
assert_eq!(to(&out, 20), [(0, WaypointTarget::Block([0, 100, 0]))]);
assert!(to(&out, 10).is_empty());
b.first_tick = false;
assert!(w.tick(&[a.clone(), b.clone()], &[], true).is_empty());
b.position[0] += 1.0;
let out = w.tick(&[a.clone(), b.clone()], &[], true);
assert_eq!(to(&out, 10), [(0, WaypointTarget::Block([6, 100, 0]))]);
// One block: an update. Three: a new connection. Out of view: a chunk.
b.position[0] += 1.0;
let out = w.tick(&[a.clone(), b.clone()], &[], true);
assert_eq!(to(&out, 10), [(2, WaypointTarget::Block([7, 100, 0]))]);
b.position[0] += 3.0;
let out = w.tick(&[a.clone(), b.clone()], &[], true);
assert_eq!(to(&out, 10), [(0, WaypointTarget::Block([10, 100, 0]))]);
b.position[0] = 100.5;
let out = w.tick(&[a.clone(), b.clone()], &[], true);
assert_eq!(to(&out, 10), [(0, WaypointTarget::Chunk([6, 0]))]);
// Really far: an angle.
b.position[0] = 1000.5;
let out = w.tick(&[a.clone(), b.clone()], &[], true);
assert!(matches!(
to(&out, 10)[..],
[(0, WaypointTarget::Azimuth(_))]
));
// Hidden: untracked; the rule off: every connection broken.
b.transmit_range = 0.0;
let out = w.tick(&[a.clone(), b.clone()], &[], true);
assert_eq!(to(&out, 10), [(1, WaypointTarget::Empty)]);
let out = w.tick(&[a.clone(), b.clone()], &[], false);
assert_eq!(to(&out, 20), [(1, WaypointTarget::Empty)]);
assert!(to(&out, 10).is_empty());
// Leaving untracks what was left.
let out = w.tick(&[a.clone(), b.clone()], &[], true);
assert!(matches!(
to(&out, 20)[..],
[(0, WaypointTarget::Azimuth(_))]
));
let out = w.tick(&[b.clone()], &[], true);
assert_eq!(to(&out, 20), [(1, WaypointTarget::Empty)]);
}
#[test]
fn team_colours() {
assert_eq!(team_rgb("red"), Some(0xFF5555));
assert_eq!(team_rgb("black"), Some(0xFF30_3030_u32 as i32));
assert_eq!(team_rgb("reset"), None);
}
}
+36
View File
@@ -690,6 +690,10 @@ pub struct Extra {
pub fall_fly_ticks: i32,
pub main_hand_left: bool,
pub elytra: ElytraAnimation,
pub swim: SwimAnimation,
/// The arm the current swing moves (`currentSwing.hand().asArm`): `Some(true)`
/// for the right arm.
pub swing_right_arm: Option<bool>,
pub flag: bool,
pub flag2: bool,
/// Species scratch values (the wither's head targets and clocks).
@@ -807,6 +811,8 @@ pub struct Mob {
/// Entity.wasEyeInWater: the eyes were in water before this tick's fluid
/// update (`isUnderWater` reads it).
pub was_eye_in_water: bool,
/// `Entity.firstTick`: no splash for a mob that appears in water.
pub first_tick: bool,
pub no_gravity: bool,
/// `Entity.mainSupportingBlockPos`: the block it stood on after its last
/// move.
@@ -1484,6 +1490,7 @@ impl Mob {
extra: Extra::default(),
fluids: living::Fluids::default(),
was_eye_in_water: false,
first_tick: true,
no_gravity: false,
supporting: None,
no_ai: false,
@@ -2068,6 +2075,35 @@ impl ElytraAnimation {
}
}
/// `LivingEntity.swimAmount` and the render state the swimming pose reads
/// (`isVisuallySwimming`, `isInWater`).
#[derive(Clone, Copy, Debug, Default)]
pub struct SwimAnimation {
pub old: f32,
pub amount: f32,
/// `isVisuallySwimming`: in the swimming pose (or still in the gliding
/// pose after a glide ended).
pub visually: bool,
pub in_water: bool,
}
impl SwimAnimation {
/// `LivingEntity.updateSwimAmount`.
pub fn tick(&mut self, visually: bool, in_water: bool) {
self.old = self.amount;
self.amount = if visually {
(self.amount + 0.09).min(1.0)
} else {
(self.amount - 0.09).max(0.0)
};
self.visually = visually;
self.in_water = in_water;
}
/// `LivingEntity.getSwimAmount`.
pub fn amount(&self, partial: f32) -> f32 {
self.old + partial * (self.amount - self.old)
}
}
#[cfg(test)]
mod elytra_tests {
use super::*;
+18 -4
View File
@@ -225,6 +225,22 @@ pub fn register(m: &mut Mob) {
Family::Bat => super::bat::register(m),
Family::Bee => super::bee::register(m),
}
// FloatGoal's constructor lets the navigation float, as do the
// constructors of these brain-driven and flying mobs. A floater rises
// 0.04 a tick in Mob.jumpInLiquid, the others 0.3 (the bounce of #542).
if m.ai.goals.has("Float")
|| matches!(
m.species(),
Species::Allay
| Species::Armadillo
| Species::Camel
| Species::Goat
| Species::Parrot
| Species::Wither
)
{
m.ai.nav.can_float = true;
}
}
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
@@ -428,10 +444,7 @@ fn tick_swing(m: &mut Mob) {
/// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick.
fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.was_eye_in_water = m.fluids.eye_in_water;
m.fluids = w.fluids(m.bounds(), m.eye_y());
if m.fluids.in_water {
m.fall_distance = 0.0;
}
m.update_fluids(w, events);
let fire = crate::motion::environment::fire_contact(w.world, w.registry, m.bounds());
if fire > 0.0 {
m.ticks_frozen = 0;
@@ -474,6 +487,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.position.y < f64::from(crate::chunk::MIN_Y - 64) {
m.damage(4.0, Damage::of(DamageKind::OutOfWorld));
}
m.first_tick = false;
if m.alive() {
// LivingEntity.baseTick: suffocation inside full blocks.
let (ex, ey, ez) = (
+197 -9
View File
@@ -235,6 +235,8 @@ pub enum ArmPose {
Bow,
CrossbowHold,
CrossbowCharge,
/// Raising a trident to throw it (or to launch with Riptide).
ThrowTrident,
}
/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself.
pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) {
@@ -276,6 +278,12 @@ pub struct Hum {
pub charge: (f32, f32),
/// `PiglinModel.setupAttackAnimation`: swing a held weapon down.
pub weapon_swing: bool,
/// `swimAmount` at this frame.
pub swim: f32,
/// `isUsingItem`: the swim stroke leaves the arms alone.
pub using_item: bool,
/// The arm the current swing moves (`Some(true)` for the right one).
pub swing_right_arm: Option<bool>,
}
impl Hum {
pub fn new(right: ArmPose, left: ArmPose) -> Self {
@@ -290,6 +298,9 @@ impl Hum {
holding: false,
charge: (0.0, 0.0),
weapon_swing: false,
swim: 0.0,
using_item: false,
swing_right_arm: None,
}
}
}
@@ -298,7 +309,7 @@ impl ArmPose {
matches!(self, Self::Bow | Self::CrossbowHold | Self::CrossbowCharge)
}
fn affects_offhand(self) -> bool {
self.two_handed()
self.two_handed() || self == Self::ThrowTrident
}
}
/// `AnimationUtils.animateCrossbowHold`.
@@ -350,6 +361,11 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) {
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -PI / 2.0 + hx);
}
ArmPose::ThrowTrident => {
let x = p.get(arm)[3];
p.xrot(arm, x * 0.5 - PI);
p.yrot(arm, 0.0);
}
ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right),
ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right),
}
@@ -435,12 +451,17 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
let x = drop + ym * 1.2 - xm * 0.4;
let y = 0.1 - ym * 0.6;
p.xrot("right_arm", x);
p.yrot("right_arm", if raise { -y } else { y });
p.zrot("right_arm", 0.0);
p.xrot("left_arm", x);
p.yrot("left_arm", if raise { y } else { -y });
p.zrot("left_arm", 0.0);
// An arm raising a trident keeps its pose.
if h.right != ArmPose::ThrowTrident {
p.xrot("right_arm", x);
p.yrot("right_arm", if raise { -y } else { y });
p.zrot("right_arm", 0.0);
}
if h.left != ArmPose::ThrowTrident {
p.xrot("left_arm", x);
p.yrot("left_arm", if raise { y } else { -y });
p.zrot("left_arm", 0.0);
}
}
if h.crouching {
p.xrot("body", 0.5);
@@ -455,6 +476,86 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
}
bob(p, "right_arm", s.age, 1.0);
bob(p, "left_arm", s.age, -1.0);
if h.swim > 0.0 {
swim(p, s.pos, h);
}
}
/// `Mth.rotLerpRad`.
fn rot_lerp_rad(a: f32, from: f32, to: f32) -> f32 {
let mut diff = to - from;
while diff < -PI {
diff += PI * 2.0;
}
while diff >= PI {
diff -= PI * 2.0;
}
from + a * diff
}
/// `HumanoidModel.setupSwimAnimation`: the stroke of both arms over 26
/// walk-animation units, the head down and a slow flutter kick. The left arm
/// eases the short way round, the right one linearly, as in vanilla.
fn swim(p: &mut Poses, pos: f32, h: &Hum) {
let amount = h.swim;
if !h.fall_flying {
let x = p.get("head")[3];
p.xrot(
"head",
rot_lerp_rad(amount, x, -std::f32::consts::FRAC_PI_4),
);
}
let swim_pos = pos % 26.0;
let right_amount = if h.swing_right_arm == Some(true) {
0.0
} else {
amount
};
let left_amount = if h.swing_right_arm == Some(false) {
0.0
} else {
amount
};
let lerp = |a: f32, from: f32, to: f32| from + a * (to - from);
let quadratic = |x: f32| -65.0 * x + x * x;
if !h.using_item {
// Targets (x, y, z) for the left and right arm.
let targets = if swim_pos < 14.0 {
let stroke = 1.870_796_4 * quadratic(swim_pos) / quadratic(14.0);
Some(([0.0, PI, PI + stroke], [0.0, PI, PI - stroke]))
} else if swim_pos < 22.0 {
let t = (swim_pos - 14.0) / 8.0;
let x = PI / 2.0 * t;
Some((
[x, PI, 5.012_389 - 1.870_796_4 * t],
[x, PI, 1.270_796_3 + 1.870_796_4 * t],
))
} else if swim_pos < 26.0 {
let t = (swim_pos - 22.0) / 4.0;
let x = PI / 2.0 - PI / 2.0 * t;
Some(([x, PI, PI], [x, PI, PI]))
} else {
None
};
if let Some((left, right)) = targets {
for (i, target) in left.into_iter().enumerate() {
let angle = &mut p.get("left_arm")[3 + i];
*angle = rot_lerp_rad(left_amount, *angle, target);
}
for (i, target) in right.into_iter().enumerate() {
let angle = &mut p.get("right_arm")[3 + i];
*angle = lerp(right_amount, *angle, target);
}
}
}
let x = p.get("left_leg")[3];
p.xrot(
"left_leg",
lerp(amount, x, 0.3 * (pos * 0.333_333_34 + PI).mcos()),
);
let x = p.get("right_leg")[3];
p.xrot(
"right_leg",
lerp(amount, x, 0.3 * (pos * 0.333_333_34).mcos()),
);
}
/// Apply the mob's model animation to `p`.
pub fn setup(
@@ -526,7 +627,21 @@ pub fn setup(
| Anim::ZombieVillager
| Anim::ZombifiedPiglin
| Anim::Humanoid { zombie_arms: true } => {
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
// DrownedRenderer.getArmPose: an aggressive drowned raises the
// trident in its main arm.
let throwing = m.kind.anim == Anim::Drowned
&& m.ai.aggressive
&& m.extra.main_hand.as_deref() == Some("minecraft:trident");
let main = if throwing {
ArmPose::ThrowTrident
} else {
ArmPose::Empty
};
let mut h = if m.extra.main_hand_left {
Hum::new(ArmPose::Empty, main)
} else {
Hum::new(main, ArmPose::Empty)
};
h.zombie = Some(m.ai.aggressive);
h.holding = m.extra.main_hand.is_some();
h.crouching = m.extra.crouching;
@@ -549,6 +664,7 @@ pub fn setup(
let pose = if player {
match m.extra.main_hand.as_deref() {
Some("minecraft:bow") if m.extra.using_item > 0 => ArmPose::Bow,
Some("minecraft:trident") if m.extra.using_item > 0 => ArmPose::ThrowTrident,
Some("minecraft:crossbow") if m.extra.using_item > 0 && !m.extra.charged => {
ArmPose::CrossbowCharge
}
@@ -561,7 +677,7 @@ pub fn setup(
} else {
right
};
let off = if player && m.extra.off_hand.is_some() && !pose.two_handed() {
let off = if player && m.extra.off_hand.is_some() && !pose.affects_offhand() {
ArmPose::Item
} else {
ArmPose::Empty
@@ -580,6 +696,9 @@ pub fn setup(
}
h.crouching = m.extra.crouching;
h.passenger = m.extra.passenger;
h.swim = m.extra.swim.amount(s.partial);
h.using_item = m.extra.using_item > 0;
h.swing_right_arm = m.extra.swing_right_arm;
humanoid(p, s, &h);
if m.ai.aggressive && !bow {
// SkeletonModel melee pose.
@@ -709,5 +828,74 @@ mod flight_pose_tests {
humanoid(&mut flight, &state, &h);
assert_eq!(flight.get("head")[3], -std::f32::consts::FRAC_PI_4);
assert_eq!(flight.get("right_leg")[3], ground.get("right_leg")[3] / 8.0);
// THROW_TRIDENT: the arm goes up over the head, and zombie arms leave it there.
let mut throw = make();
let mut h = Hum::new(ArmPose::ThrowTrident, ArmPose::Item);
h.zombie = Some(true);
humanoid(&mut throw, &state, &h);
let still = (state.pos * 0.6662 + PI).mcos() * 2.0 * 0.5;
assert_eq!(throw.get("right_arm")[3], still * 0.5 - PI);
assert_eq!(throw.get("right_arm")[4], 0.0);
assert_eq!(throw.get("left_arm")[3], -PI / 1.5);
}
#[test]
fn swimming_strokes_the_arms_and_kicks() {
let state = State {
pos: 7.0,
speed: 1.0,
age: 0.0,
y_rot: 0.0,
x_rot: 30.0,
swing: 0.0,
baby: false,
partial: 0.0,
};
let make = || Poses {
map: ["head", "right_arm", "left_arm", "right_leg", "left_leg"]
.into_iter()
.map(|n| (n.to_string(), [0.0; 9]))
.collect(),
dummy: [0.0; 9],
skipped: Default::default(),
hidden: Default::default(),
};
let same_angle = |a: f32, b: f32| ((a - b + PI).rem_euclid(PI * 2.0) - PI).abs() < 1e-5;
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
h.swim = 1.0;
let mut p = make();
humanoid(&mut p, &state, &h);
// Mid-stroke: both arms sweep out from overhead by the quadratic.
let stroke = 1.870_796_4 * (-65.0 * 7.0 + 49.0) / (-65.0 * 14.0 + 196.0);
assert_eq!(p.get("right_arm")[5], PI - stroke);
assert!(same_angle(p.get("left_arm")[5], PI + stroke));
assert_eq!(p.get("right_arm")[4], PI);
assert!(same_angle(p.get("head")[3], -std::f32::consts::FRAC_PI_4));
assert!(same_angle(
p.get("right_leg")[3],
0.3 * (7.0f32 * 0.333_333_34).mcos()
));
// Using an item keeps the arms; a swing frees its own arm only.
let mut using = make();
h.using_item = true;
humanoid(&mut using, &state, &h);
assert_eq!(using.get("right_arm")[4], 0.0);
h.using_item = false;
h.swing_right_arm = Some(true);
let mut swinging = make();
humanoid(
&mut swinging,
&State {
swing: 0.5,
..state
},
&h,
);
assert!(swinging.get("right_arm")[4] < 1.0);
assert!(same_angle(swinging.get("left_arm")[4], PI));
// Out of the pose nothing changes.
let mut dry = make();
humanoid(&mut dry, &state, &Hum::new(ArmPose::Empty, ArmPose::Empty));
assert_eq!(dry.get("head")[3], 30.0f32.to_radians());
}
}
+20 -6
View File
@@ -83,19 +83,33 @@ pub fn register(m: &mut Mob) {
return super::llama::register(m);
}
let tempt = m.kind.tempt.clone();
let rears = can_rear(m.species());
let species = m.species();
let rears = can_rear(species);
let stand_interval = m.kind.ambient_interval;
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(1, MountPanic(Panic::new(1.2)));
g.add(1, RunAroundLikeCrazy);
g.add(2, Breed::new(1.0));
g.add(3, Tempt::new(1.25, tempt, false));
g.add(4, FollowParent::new(1.0));
g.add(6, Stroll::avoiding_water(0.7));
g.add(7, LookAtPlayer::new(6.0));
g.add(8, RandomLookAround::default());
if rears {
g.add(9, RandomStand { next: -80 });
// resetStandInterval: -getAmbientStandInterval (400 for every horse).
g.add(
9,
RandomStand {
next: -stand_interval,
},
);
}
// addBehaviourGoals, after the rest: none for the skeleton horse (it
// sinks), no mount panic for the zombie horse.
if species != Species::SkeletonHorse {
g.add(0, Float);
if species != Species::ZombieHorse {
g.add(1, MountPanic(Panic::new(1.2)));
}
g.add(3, Tempt::new(1.25, tempt, false));
}
}
/// `generateMaxHealth`, `generateSpeed`, `generateJumpStrength` and the coat.
@@ -285,7 +299,7 @@ impl Goal for RandomStand {
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
self.next += 1;
if self.next > 0 && m.random.next_int_bound(1000).unwrap_or(1000) < self.next {
self.next = -80;
self.next = -m.kind.ambient_interval;
return m.random.next_int_bound(10).unwrap_or(1) == 0;
}
false
+4
View File
@@ -94,6 +94,10 @@ impl GoalSelector {
.map(|g| g.goal.name())
.collect()
}
/// Whether a goal of this name is registered, running or not.
pub fn has(&self, name: &str) -> bool {
self.goals.iter().any(|g| g.goal.name() == name)
}
pub fn is_running(&self, name: &str) -> bool {
self.goals
.iter()
+110 -5
View File
@@ -398,10 +398,7 @@ impl Mob {
/// (touching water resets the fall), then Entity.checkFallDamage.
fn check_fall_damage(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec<MobEvent>) {
if !self.fluids.in_water {
self.fluids = w.fluids(self.bounds(), self.eye_y());
if self.fluids.in_water {
self.fall_distance = 0.0;
}
self.update_fluids(w, events);
}
if !self.fluids.in_water && moved.y < 0.0 {
self.fall_distance -= f64::from(moved.y as f32);
@@ -413,6 +410,23 @@ impl Mob {
self.fall_distance = 0.0;
}
}
/// Entity.updateFluidInteraction: the fluid state, then touching water
/// resets the fall and entering it (after the first tick) splashes.
pub(super) fn update_fluids(&mut self, w: &MobWorld, events: &mut Vec<MobEvent>) {
let was_touching_water = self.fluids.in_water;
self.fluids = w.fluids(self.bounds(), self.eye_y());
if self.fluids.in_water {
self.fall_distance = 0.0;
if !was_touching_water && !self.first_tick {
// The splash is the mob's own: Horizon's mobs carry no
// controlling passenger here.
let _ = horizon_world::water_splash::water_splash(
&mut Splash { mob: self, events },
1_000_000,
);
}
}
}
/// Entity.applyMovementEmissionAndPlaySound: walked distance, footsteps
/// and swimming sounds.
fn movement_emission(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec<MobEvent>) {
@@ -811,7 +825,8 @@ impl Mob {
self.velocity.y += if self.species() == super::Species::Bee {
0.01
} else if self.ai.nav.can_float {
0.04
// LivingEntity.jumpInLiquid adds 0.04F.
f64::from(0.04_f32)
} else {
0.3
};
@@ -915,3 +930,93 @@ fn free_position(
let free = allowed_shape.join(&collisions, ShapeOp::ONLY_FIRST).ok()?;
free.closest_point(preferred)
}
/// `Entity.doWaterSplashEffect` for a mob: its own random, its splash sound
/// (`getSwimSplashSound`), particles for the client and the SPLASH game event.
struct Splash<'a> {
mob: &'a mut Mob,
events: &'a mut Vec<MobEvent>,
}
impl horizon_world::water_splash::WaterSplashWorld for Splash<'_> {
type Error = std::convert::Infallible;
type Entity = ();
type Sound = &'static str;
fn this_entity(&self) {}
fn controlling_passenger(&mut self) -> Result<Option<()>, Self::Error> {
Ok(None)
}
fn velocity(&mut self, _: ()) -> Result<Vec3, Self::Error> {
Ok(self.mob.velocity)
}
fn splash_sound(&mut self, _high_speed: bool) -> Result<&'static str, Self::Error> {
use super::Species;
// Entity.getSwimSplashSound and getSwimHighSpeedSplashSound: the
// overrides are Monster's, the hoglin's, the dolphin's and the axolotl's.
let species = self.mob.species();
Ok(match species {
Species::Dolphin => "entity.dolphin.splash",
Species::Axolotl => "entity.axolotl.splash",
_ if species == Species::Hoglin || super::ai::is_monster(species) => {
"entity.hostile.splash"
}
_ => "entity.generic.splash",
})
}
fn random_float(&mut self) -> Result<f32, Self::Error> {
Ok(self.mob.random.next_float())
}
fn random_double(&mut self) -> Result<f64, Self::Error> {
Ok(self.mob.random.next_double())
}
fn play_sound(
&mut self,
sound: &'static str,
volume: f32,
pitch: f32,
) -> Result<(), Self::Error> {
if !self.mob.silent {
let at = [
self.mob.position.x,
self.mob.position.y,
self.mob.position.z,
];
self.events.push(MobEvent::Sound(sound, at, volume, pitch));
}
Ok(())
}
fn position(&self) -> Vec3 {
self.mob.position
}
fn width(&self) -> f32 {
self.mob.width()
}
fn particle(
&mut self,
kind: horizon_world::water_splash::SplashParticle,
position: Vec3,
velocity: Vec3,
) -> Result<(), Self::Error> {
self.events.push(MobEvent::ParticleAt {
kind: match kind {
horizon_world::water_splash::SplashParticle::Bubble => "bubble",
horizon_world::water_splash::SplashParticle::Splash => "splash",
},
at: [position.x, position.y, position.z],
velocity: [velocity.x, velocity.y, velocity.z],
});
Ok(())
}
fn splash_event(&mut self) -> Result<(), Self::Error> {
self.events.push(MobEvent::GameEvent {
event: "minecraft:splash",
at: [
self.mob.position.x,
self.mob.position.y,
self.mob.position.z,
],
source: self.mob.id,
state: horizon_world::registry::BlockStateId(0),
});
Ok(())
}
}
+22 -8
View File
@@ -4,8 +4,8 @@
//! `AmphibiousNodeEvaluator`), ported rule for rule.
use super::{MobWorld, data};
use crate::blocks::Fluid;
use crate::fast_hash::FxHashMap;
use horizon_core::geometry::{Aabb, Vec3};
use std::collections::HashMap;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PathType {
@@ -301,10 +301,13 @@ pub struct Finder<'a, 'w> {
mob: &'a PathMob,
eval: Evaluator,
nodes: Vec<Node>,
index: HashMap<(i32, i32, i32), u32>,
index: FxHashMap<(i32, i32, i32), u32>,
heap: Vec<u32>,
types: HashMap<(i32, i32, i32), PathType>,
collisions: HashMap<[u64; 6], bool>,
types: FxHashMap<(i32, i32, i32), PathType>,
/// `path_type` of each position asked during this query: it reads up to
/// 26 blocks, and overlapping mob boxes ask for the same positions.
statics: std::cell::RefCell<FxHashMap<(i32, i32, i32), PathType>>,
collisions: FxHashMap<[u64; 6], bool>,
entity_width: i32,
entity_height: i32,
entity_depth: i32,
@@ -319,10 +322,11 @@ impl<'a, 'w> Finder<'a, 'w> {
mob,
eval,
nodes: Vec::new(),
index: HashMap::new(),
index: FxHashMap::default(),
heap: Vec::new(),
types: HashMap::new(),
collisions: HashMap::new(),
types: FxHashMap::default(),
statics: Default::default(),
collisions: FxHashMap::default(),
entity_width: (mob.width + 1.0).floor() as i32,
entity_height: (mob.height + 1.0).floor() as i32,
entity_depth: (mob.width + 1.0).floor() as i32,
@@ -385,7 +389,17 @@ impl<'a, 'w> Finder<'a, 'w> {
}
// --- path types -----------------------------------------------------
/// WalkNodeEvaluator.getPathTypeStatic (+ the fly/amphibious overrides).
/// The world doesn't change during a query, so each position's type is
/// worked out once.
fn path_type(&self, x: i32, y: i32, z: i32) -> PathType {
if let Some(t) = self.statics.borrow().get(&(x, y, z)) {
return *t;
}
let t = self.compute_path_type(x, y, z);
self.statics.borrow_mut().insert((x, y, z), t);
t
}
fn compute_path_type(&self, x: i32, y: i32, z: i32) -> PathType {
match self.eval {
Evaluator::Fly => self.fly_path_type(x, y, z),
Evaluator::Amphibious { .. } => {
@@ -991,7 +1005,7 @@ impl<'a, 'w> Finder<'a, 'w> {
let malus =
|s: &Self, n: Option<u32>| n.is_some_and(|n| s.nodes[n as usize].cost_malus >= 0.0);
// Direction.values(): down, up, north, south, west, east.
let mut by_dir: HashMap<(i32, i32, i32), Option<u32>> = HashMap::new();
let mut by_dir: FxHashMap<(i32, i32, i32), Option<u32>> = FxHashMap::default();
for (dx, dy, dz) in [
(0, -1, 0),
(0, 1, 0),
+25 -11
View File
@@ -765,6 +765,17 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
};
let mut base = origin * rotation;
if m.death_time > 0 && !super::creaking::tearing_down(m) {
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
.sqrt()
.min(1.0);
base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).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))
* glam::Mat4::from_rotation_z(PI);
}
// AvatarRenderer.setupRotations, after LivingEntityRenderer's.
if m.extra.fall_flying {
let ticks = m.extra.fall_fly_ticks as f32 + alpha;
let scale = (ticks * ticks / 100.0).min(1.0);
@@ -785,17 +796,20 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4
(sign * horizon_core::jmath::acos(dot.abs().min(1.0))) as f32,
);
}
}
if m.death_time > 0 && !super::creaking::tearing_down(m) {
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
.sqrt()
.min(1.0);
base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).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))
* glam::Mat4::from_rotation_z(PI);
} else if m.extra.swim.amount(alpha) > 0.0 {
// AvatarRenderer.setupRotations: tip forward with the swim amount,
// following the pitch in water, then lie along the swimming box.
let amount = m.extra.swim.amount(alpha);
let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha;
let target = if m.extra.swim.in_water {
-90.0 - pitch
} else {
-90.0
};
base *= glam::Mat4::from_rotation_x((amount * target).to_radians());
if m.extra.swim.visually {
base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.0, 0.3));
}
}
base *= species_rotations(m, alpha);
base *= glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0));
+10 -1
View File
@@ -1634,7 +1634,16 @@ impl Def {
use Species as S;
match self.species {
S::Turtle => 200,
S::Horse | S::Donkey | S::Mule | S::Llama | S::TraderLlama => 400,
// AbstractHorse.getAmbientSoundInterval, for every subclass.
S::Horse
| S::Donkey
| S::Mule
| S::ZombieHorse
| S::SkeletonHorse
| S::Llama
| S::TraderLlama
| S::Camel
| S::CamelHusk => 400,
S::Ocelot => 900,
S::Squid
| S::GlowSquid
+10 -1
View File
@@ -855,8 +855,17 @@ impl Goal for CatSitOnBlock {
JUMP | MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !m.extra.tame || m.extra.sitting {
return false;
}
// MoveToBlockGoal.canUse draws the next delay only once the last one
// has run out.
if self.0.next_start > 0 {
self.0.next_start -= 1;
return false;
}
let next = reduced(200 + m.random.next_int_bound(200).unwrap_or(0));
m.extra.tame && !m.extra.sitting && self.0.can_use(m, cx.w, next, can_sit_on)
self.0.can_use(m, cx.w, next, can_sit_on)
}
fn can_continue(&mut self, _: &mut Mob, cx: &mut Cx) -> bool {
self.0.can_continue(cx.w, can_sit_on)
+45
View File
@@ -281,6 +281,17 @@ fn attribute_error(error: impl std::fmt::Debug) -> io::Error {
io::Error::other(format!("movement attribute: {error:?}"))
}
impl PlayerMotion {
/// `Player.isSweepAttack`, using the resident player's known horizontal velocity.
pub fn is_sweep_attack(&self, strength: f32, critical: bool, sword: bool) -> bool {
let movement = self.velocity;
let limit = f64::from(self.speed) * 2.5;
strength > 0.9
&& !critical
&& !self.sprinting
&& self.ground.on_ground
&& movement.x * movement.x + movement.z * movement.z < limit * limit
&& sword
}
pub fn load_environment_once(
&mut self,
pending: &mut bool,
@@ -1986,6 +1997,40 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> {
mod tests {
use super::*;
#[test]
fn sword_sweep_requires_charge_ground_and_slow_horizontal_movement() {
let root = std::env::var_os("HORIZON_TEST_RESOURCES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3")
});
if !root.join("movement-properties.nbt").exists() {
eprintln!("skipped sword sweep regression: prepared resources unavailable");
return;
}
let assets = Assets::load(&root).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
let mut p = PlayerMotion::new(&resources, Vec3::ZERO).unwrap();
p.ground.on_ground = true;
p.speed = 0.1;
assert!(p.is_sweep_attack(1.0, false, true));
assert!(!p.is_sweep_attack(0.9, false, true));
assert!(!p.is_sweep_attack(1.0, true, true));
assert!(!p.is_sweep_attack(1.0, false, false));
p.sprinting = true;
assert!(!p.is_sweep_attack(1.0, false, true));
p.sprinting = false;
p.ground.on_ground = false;
assert!(!p.is_sweep_attack(1.0, false, true));
p.ground.on_ground = true;
p.velocity = Vec3::new(0.2, 10.0, 0.0);
assert!(p.is_sweep_attack(1.0, false, true));
p.velocity.z = 0.2;
assert!(!p.is_sweep_attack(1.0, false, true));
p.velocity = Vec3::new(f64::from(p.speed) * 2.5, 0.0, 0.0);
assert!(!p.is_sweep_attack(1.0, false, true));
}
#[test]
fn player_stands_walks_sneaks_and_jumps_on_ghast() {
let root = std::env::var_os("HORIZON_TEST_RESOURCES")
+8
View File
@@ -204,6 +204,14 @@ fn save_icon(file: &Path, address: &str, icon: Option<String>) {
}
}
/// `ClientPacketListener.handleServerData`: a valid icon the joined server
/// sends replaces the one its list entries keep.
pub fn save_server_icon(saves: &Path, address: &str, png: &[u8]) {
if icon_pixels(png).is_some() {
save_icon(&servers_file(saves), address, Some(crate::lan::base64(png)));
}
}
/// The address of list row `index`: the saved servers, then the LAN games.
fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option<String> {
match servers.get(index) {
+1 -1
View File
@@ -159,7 +159,7 @@ static TABLE: LazyLock<Vec<Def>> = LazyLock::new(|| {
b("reducedDebugInfo", false),
def("renderClouds", O(Clouds), V::Int(2)),
i("cloudRange", 2, 128, 128),
i("renderDistance", 2, 32, 12),
i("renderDistance", 2, 64, 12),
i("simulationDistance", 5, 32, 12),
u("screenEffectScale", 1.0),
def("soundDevice", O(AnyStr), V::Str(String::new())),
+21 -2
View File
@@ -190,7 +190,7 @@ impl Opt {
let unit = |v: f32, lo: f32, hi: f32| Kind::Slider(((v - lo) / (hi - lo)).clamp(0.0, 1.0));
match self {
Opt::Fov => unit(s.fov, 30.0, 110.0),
Opt::RenderDistance => unit(s.render_distance as f32, 2.0, 32.0),
Opt::RenderDistance => unit(s.render_distance as f32, 2.0, 64.0),
Opt::SimulationDistance => unit(s.simulation_distance as f32, 5.0, 32.0),
Opt::Sensitivity => Kind::Slider(s.sensitivity),
Opt::WheelSensitivity => unit(s.mouse_wheel_sensitivity, 0.01, 10.0),
@@ -484,7 +484,7 @@ impl Opt {
let step = |lo: f32, hi: f32| (lo + v * (hi - lo)).round();
match self {
Opt::Fov => s.fov = step(30.0, 110.0),
Opt::RenderDistance => s.render_distance = step(2.0, 32.0) as i32,
Opt::RenderDistance => s.render_distance = step(2.0, 64.0) as i32,
Opt::SimulationDistance => s.simulation_distance = step(5.0, 32.0) as i32,
Opt::Sensitivity => s.sensitivity = v,
Opt::WheelSensitivity => s.mouse_wheel_sensitivity = 0.01 + v * 9.99,
@@ -2356,6 +2356,25 @@ mod tests {
use super::*;
use crate::ui_theme::{MenuStyle, set_style, style};
#[test]
fn render_distance_slider_round_trips_through_extended_options_range() {
let mut s = Settings::default();
for (position, distance) in [(0.0, 2), (0.5, 33), (1.0, 64)] {
set_slider(Opt::RenderDistance, &mut s, position);
assert_eq!(s.render_distance, distance);
let reloaded = Settings::parse(&s.serialize());
assert_eq!(reloaded.render_distance, distance);
assert_eq!(
Opt::RenderDistance.slider_position(&reloaded),
Some(position)
);
}
let mut file = crate::options_file::OptionsFile::default();
file.set_text("renderDistance", "64").unwrap();
assert!(file.set_text("renderDistance", "65").is_err());
assert!(file.set_text("renderDistance", "1").is_err());
assert_eq!(file.int("renderDistance"), 64);
}
fn atlas() -> HudAtlas {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
+13 -5
View File
@@ -728,6 +728,15 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag {
/// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES),
/// as (network id, packed longs) in Heightmap.Types order.
pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec<i64>)> {
client_heightmaps_in(chunk, tables, MIN_Y, SECTIONS as i32 * 16)
}
/// The client heightmaps of a level from `min_y`, `height` blocks high.
pub fn client_heightmaps_in(
chunk: &Chunk,
tables: &SaveTables,
min_y: i32,
height: i32,
) -> Vec<(i32, Vec<i64>)> {
let kinds = [
(1, HeightmapType::WorldSurface),
(4, HeightmapType::MotionBlocking),
@@ -735,11 +744,7 @@ pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec<i6
];
let mut maps: Vec<(i32, Heightmap)> = kinds
.iter()
.filter_map(|(id, k)| {
Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16)
.ok()
.map(|m| (*id, m))
})
.filter_map(|(id, k)| Heightmap::new(*k, min_y, height).ok().map(|m| (*id, m)))
.collect();
let view = HeightmapView { chunk, tables };
let mut refs: Vec<&mut Heightmap> = maps.iter_mut().map(|(_, m)| m).collect();
@@ -2781,6 +2786,9 @@ impl<G: ChunkGenerator> ChunkGenerator for Persistent<G> {
chunk.entities = self.save.load_entities(x, z);
Some(chunk)
}
fn prepare_loaded(&self, worker: &mut G::Worker, chunk: &Chunk) {
self.inner.prepare_loaded(worker, chunk);
}
fn proto(&self, worker: &mut G::Worker, x: i32, z: i32) -> crate::streaming::Proto {
let mut proto = self.inner.proto(worker, x, z);
if let Some(saved) = self
+7 -1
View File
@@ -36,6 +36,9 @@ pub trait ChunkGenerator: Send + Sync + 'static {
fn load(&self, _x: i32, _z: i32) -> Option<Chunk> {
None
}
/// What a loaded chunk needs from the generator before the game uses it,
/// on the worker that loaded it.
fn prepare_loaded(&self, _worker: &mut Self::Worker, _chunk: &Chunk) {}
fn proto(&self, worker: &mut Self::Worker, x: i32, z: i32) -> Proto;
fn decorates(&self) -> bool {
false
@@ -369,7 +372,10 @@ impl Streaming {
};
let done = match job {
Job::Generate(x, z) => match generator.load(x, z) {
Some(chunk) => Done::Generated(chunk),
Some(chunk) => {
generator.prepare_loaded(&mut worker, &chunk);
Done::Generated(chunk)
}
None => {
let proto = generator.proto(&mut worker, x, z);
let decorated = generator.is_decorated(&proto);
+13
View File
@@ -265,6 +265,19 @@ impl ChunkGenerator for VanillaTerrain {
fn worker(&self) -> GeneratorWorker {
self.generator.worker()
}
/// The structure starts a saved chunk references, as vanilla reads them
/// with the chunk: built here, on the loading worker, into the
/// generator's cache, rather than on the game thread the first time
/// spawning or a mob asks which structures hold a position (a village
/// start took 70 to 110 ms there, one tick each, after a world loaded).
fn prepare_loaded(&self, worker: &mut GeneratorWorker, chunk: &Chunk) {
let mut starts: Vec<(i32, i32)> = chunk.structure_refs.iter().map(|(_, at)| *at).collect();
starts.sort_unstable();
starts.dedup();
for (x, z) in starts {
worker.structure_starts(ChunkPos::new(x, z));
}
}
fn proto(&self, worker: &mut GeneratorWorker, x: i32, z: i32) -> Proto {
match worker.generate_proto(ChunkPos::new(x, z)) {
Ok(chunk) => Box::new(VanillaProto::Ready(Box::new(chunk))),
+2 -3
View File
@@ -7,6 +7,8 @@ rust-version = "1.86"
description = "Port a Java modpack to Horizon: import, inventory, classification and data carry-over (docs/modpacks.md)"
[dependencies]
# Content path rules only (no runtime): what the game's content loader accepts.
horizon-mods = { path = "../horizon-mods", default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha1 = "0.10"
@@ -14,8 +16,5 @@ toml = "1.1.6"
ureq = { version = "2", default-features = false, features = ["tls"] }
zip = { version = "2", default-features = false, features = ["deflate"] }
[dev-dependencies]
horizon-mods = { path = "../horizon-mods", default-features = false }
[lints]
workspace = true
+67 -2
View File
@@ -19,6 +19,10 @@ pub struct Report {
/// Files outside what a content mod may hold (other namespaces, vanilla
/// data other than tags), kept in `outside/` for review.
pub outside: Vec<String>,
/// Files of the mod's own content the game would refuse, kept in
/// `outside/` too, with why: a path vanilla does not read (upper case),
/// JSON that does not parse, a vanilla tag the mod replaces.
pub unreadable: BTreeMap<String, String>,
pub recipes_upgraded: usize,
pub loot_tables_upgraded: usize,
/// Worldgen and structure files (`data/<id>/worldgen/`, `structure/`).
@@ -291,6 +295,32 @@ fn place(name: &str, id: &str) -> Option<bool> {
Some(ns == id || shared_tags)
}
/// Why the game would refuse a file of the mod's own content, if it would.
/// Vanilla skips such files one by one (an invalid resource path, a data
/// file that does not parse); Horizon's content loader refuses the whole
/// set, so they stay out of the carry.
fn unreadable(name: &str, bytes: &mut Vec<u8>) -> Option<String> {
if let Err(e) = horizon_mods::content::check_path(name) {
return Some(e);
}
if !(name.ends_with(".json") || name.ends_with(".mcmeta")) {
return None;
}
// A byte-order mark: Horizon's JSON readers take the file without it.
if bytes.starts_with(b"\xEF\xBB\xBF") {
bytes.drain(..3);
}
let value: Value = match serde_json::from_slice(bytes) {
Ok(v) => v,
Err(e) => return Some(format!("does not parse as JSON: {e}")),
};
let shared_tag = name.starts_with("data/minecraft/tags/") || name.starts_with("data/c/tags/");
if shared_tag && value.get("replace").and_then(Value::as_bool) == Some(true) {
return Some("replaces a shared tag; a content mod may only add to it".into());
}
None
}
/// Carries `jar` over into `out/carry/`. With the oracle's `facts`, blocks
/// and items are the ones the mod registers, with the templates and numbers
/// the facts give; `allowed` says which vanilla blocks the game has.
@@ -334,6 +364,15 @@ pub fn carry(
entry
.read_to_end(&mut bytes)
.map_err(|e| format!("{name}: {e}"))?;
let unreadable = if keep {
unreadable(&name, &mut bytes)
} else {
None
};
let keep = keep && unreadable.is_none();
if let Some(why) = unreadable {
report.unreadable.insert(name.clone(), why);
}
let dest = if keep {
report.copied += 1;
inside.join(&name)
@@ -716,6 +755,17 @@ mod tests {
r#"{"values": ["gem:gem_block"]}"#,
),
("data/c/tags/item/gems.json", r#"{"values": ["gem:gem"]}"#),
// What the game would refuse: vanilla skips these files alone.
("assets/gem/lang/ry_UA.json", r#"{"item.gem.gem": "Gem"}"#),
("data/gem/tags/item/empty.json", ""),
(
"data/minecraft/tags/worldgen/biome/has_structure/village_plains.json",
r#"{"replace": true, "values": []}"#,
),
(
"assets/gem/lang/de_de.json",
"\u{feff}{\"item.gem.gem\": \"Juwel\"}",
),
];
for (name, text) in files {
zip.start_file(*name, zip::write::SimpleFileOptions::default())
@@ -732,8 +782,23 @@ mod tests {
assert_eq!(info.census.classes, 1);
let out = dir.join("work/mods/gem");
let report = carry(&jar, &info, &out, None, &|_| true).unwrap();
assert_eq!(report.copied, 12);
assert!(report.outside.is_empty());
assert_eq!(report.copied, 13);
let unreadable: Vec<&str> = report.unreadable.keys().map(String::as_str).collect();
assert_eq!(
unreadable,
[
"assets/gem/lang/ry_UA.json",
"data/gem/tags/item/empty.json",
"data/minecraft/tags/worldgen/biome/has_structure/village_plains.json",
]
);
assert_eq!(report.outside.len(), 3);
assert!(!out.join("carry/data/gem/tags/item/empty.json").exists());
// A byte-order mark is dropped, the file kept.
assert_eq!(
fs::read(out.join("carry/assets/gem/lang/de_de.json")).unwrap()[0],
b'{'
);
assert_eq!((report.recipes_upgraded, report.recipes_kept.len()), (1, 1));
assert_eq!(report.item_definitions_added, 2);
assert_eq!(report.blocks["gem_door"], "minecraft:oak_door");
+389
View File
@@ -0,0 +1,389 @@
//! Step 1b, the jars: for the mods the player asked to port, their own
//! download of each jar into `<work>/jars/`. Only from where the pack itself
//! points (a Modrinth pack's download URLs) or the same file on Modrinth's
//! public CDN (found by its SHA-1), and only kept when the hash matches; or
//! copied from a folder the player already has (an installed instance, a
//! downloads folder). CurseForge's own downloads need an API key, so a file
//! only CurseForge has is listed as needing one. `<work>/fetch.json` says
//! what happened to each file.
use crate::{
import::{Pack, PackFile, sha1_hex},
inventory::Record,
modrinth::{self, Cache},
pipeline::{Log, read_json, write_json},
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
collections::HashMap,
fs,
io::Read,
path::{Path, PathBuf},
};
/// Hosts a Modrinth pack may download from (the `.mrpack` format's list).
const HOSTS: [&str; 4] = [
"https://cdn.modrinth.com/",
"https://github.com/",
"https://raw.githubusercontent.com/",
"https://gitlab.com/",
];
/// No mod jar is this large; a bigger answer is not one.
const MAX_JAR: u64 = 512 << 20;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum How {
/// Already in `jars/` (or the imported instance).
Present,
/// Downloaded from the pack's URL or Modrinth's CDN, hash checked.
Downloaded,
/// Copied from the player's folder.
Local,
/// Only on CurseForge, whose downloads need an API key.
NeedsKey,
NotFound,
Failed,
}
impl How {
pub fn label(self) -> &'static str {
match self {
How::Present => "already here",
How::Downloaded => "downloaded",
How::Local => "copied from your folder",
How::NeedsKey => "needs a CurseForge key",
How::NotFound => "not found",
How::Failed => "failed",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Outcome {
pub key: String,
pub file: String,
pub how: How,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub detail: String,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Fetched {
pub files: Vec<Outcome>,
}
impl Fetched {
pub fn count(&self, how: How) -> usize {
self.files.iter().filter(|o| o.how == how).count()
}
/// `<work>/fetch.json`, empty when the step has not run.
pub fn load(work: &Path) -> Self {
read_json(&work.join("fetch.json")).unwrap_or_default()
}
}
/// The jars of the records `want` picks that the work folder lacks.
pub fn fetch(
work: &Path,
records: &[Record],
from: Option<&Path>,
want: &dyn Fn(&Record) -> bool,
log: Log,
) -> Result<Fetched, String> {
let pack: Pack = read_json(&work.join("pack.json"))?;
let cache = Cache::load(&work.join("modrinth.json"));
let files: HashMap<&str, &PackFile> = pack.files.iter().map(|f| (f.path.as_str(), f)).collect();
let jars = work.join("jars");
fs::create_dir_all(&jars).map_err(|e| format!("{}: {e}", jars.display()))?;
let local = from.map(Local::index);
let wanted: Vec<&Record> = records.iter().filter(|r| want(r)).collect();
let mut fetched = Fetched::default();
for (i, r) in wanted.iter().enumerate() {
let Some(file) = files.get(r.path.as_str()) else {
continue;
};
let name = file.file_name();
let outcome = |how, detail: String| Outcome {
key: r.key.clone(),
file: name.to_owned(),
how,
detail,
};
let dest = jars.join(name);
let sha1 = file.sha1.as_deref();
let o = if r.jar.is_some() || matches(&dest, sha1) {
outcome(How::Present, String::new())
} else if let Some(path) = local.as_ref().and_then(|l| l.find(file)) {
match fs::copy(&path, &dest) {
Ok(_) => outcome(How::Local, path.display().to_string()),
Err(e) => outcome(How::Failed, format!("{}: {e}", path.display())),
}
} else if let Some(url) = url_of(file, &cache) {
log(format!("{}/{} {name}", i + 1, wanted.len()));
match download(&url, sha1, &dest) {
Ok(()) => outcome(How::Downloaded, url),
Err(e) => outcome(How::Failed, e),
}
} else if pack.format == "curseforge" || file.curseforge.is_some() {
outcome(
How::NeedsKey,
"on CurseForge only: choose your installed instance, or put the jar in jars/"
.into(),
)
} else {
outcome(How::NotFound, "no download link in the pack".into())
};
if matches!(o.how, How::Failed | How::NeedsKey | How::NotFound) {
log(format!("{}: {} ({})", o.key, o.how.label(), o.detail));
}
fetched.files.push(o);
}
write_json(&work.join("fetch.json"), &fetched)?;
log(format!(
"jars: {} downloaded, {} copied, {} already here, {} need a CurseForge key, {} not found, {} failed",
fetched.count(How::Downloaded),
fetched.count(How::Local),
fetched.count(How::Present),
fetched.count(How::NeedsKey),
fetched.count(How::NotFound),
fetched.count(How::Failed)
));
Ok(fetched)
}
/// Whether `path` holds the file with this SHA-1 (any file when none is known).
fn matches(path: &Path, sha1: Option<&str>) -> bool {
match (fs::read(path), sha1) {
(Ok(bytes), Some(h)) => sha1_hex(&bytes).eq_ignore_ascii_case(h),
(Ok(_), None) => true,
(Err(_), _) => false,
}
}
/// The pack's own download link, else the same file on Modrinth.
pub fn url_of(file: &PackFile, cache: &Cache) -> Option<String> {
let allowed = |u: &&str| HOSTS.iter().any(|h| u.starts_with(h));
if let Some(u) = file.downloads.iter().map(String::as_str).find(allowed) {
return Some(u.to_owned());
}
let sha1 = file.sha1.as_deref()?;
cache.versions.get(sha1)?["files"]
.as_array()?
.iter()
.find(|f| f["hashes"]["sha1"].as_str() == Some(sha1))?["url"]
.as_str()
.filter(allowed)
.map(str::to_owned)
}
/// Downloads `url` to `dest`, kept only if its SHA-1 is `sha1`.
fn download(url: &str, sha1: Option<&str>, dest: &Path) -> Result<(), String> {
let response = ureq::get(url)
.set("User-Agent", modrinth::AGENT)
.call()
.map_err(|e| format!("{url}: {e}"))?;
let mut bytes = Vec::new();
response
.into_reader()
.take(MAX_JAR)
.read_to_end(&mut bytes)
.map_err(|e| format!("{url}: {e}"))?;
let got = sha1_hex(&bytes);
if let Some(want) = sha1.filter(|w| !w.eq_ignore_ascii_case(&got)) {
return Err(format!("{url}: SHA-1 {got}, the pack says {want}"));
}
let part = dest.with_extension("part");
fs::write(&part, &bytes).map_err(|e| format!("{}: {e}", part.display()))?;
fs::rename(&part, dest).map_err(|e| format!("{}: {e}", dest.display()))
}
/// The jars in a folder of the player's, by SHA-1 and by name, and what a
/// CurseForge app instance (`minecraftinstance.json`) says each
/// project's file is called.
#[derive(Default)]
struct Local {
by_sha1: HashMap<String, PathBuf>,
by_name: HashMap<String, PathBuf>,
curseforge: HashMap<(u64, u64), String>,
}
impl Local {
fn index(dir: &Path) -> Local {
let mut local = Local::default();
local.walk(dir, 3);
if let Ok(text) = fs::read_to_string(dir.join("minecraftinstance.json")) {
if let Ok(v) = serde_json::from_str::<Value>(&text) {
local.curseforge = curseforge_names(&v);
}
}
local
}
fn walk(&mut self, dir: &Path, depth: usize) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for path in entries.flatten().map(|e| e.path()) {
if path.is_dir() {
if depth > 0 {
self.walk(&path, depth - 1);
}
} else if path.extension().is_some_and(|x| x == "jar") {
if let Ok(bytes) = fs::read(&path) {
self.by_sha1.insert(sha1_hex(&bytes), path.clone());
}
if let Some(n) = path.file_name() {
self.by_name
.insert(n.to_string_lossy().into_owned(), path.clone());
}
}
}
}
fn find(&self, file: &PackFile) -> Option<PathBuf> {
if let Some(h) = &file.sha1 {
return self.by_sha1.get(&h.to_ascii_lowercase()).cloned();
}
let name = file
.curseforge
.and_then(|ids| self.curseforge.get(&ids))
.map_or(file.file_name(), String::as_str);
self.by_name.get(name).cloned()
}
}
/// `installedAddons[]`: (project, file) → the jar's file name.
pub fn curseforge_names(instance: &Value) -> HashMap<(u64, u64), String> {
instance["installedAddons"]
.as_array()
.into_iter()
.flatten()
.filter_map(|a| {
let file = &a["installedFile"];
Some((
(a["addonID"].as_u64()?, file["id"].as_u64()?),
file["fileName"].as_str()?.to_owned(),
))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn file(sha1: Option<&str>, downloads: &[&str]) -> PackFile {
PackFile {
path: "mods/a.jar".into(),
sha1: sha1.map(str::to_owned),
downloads: downloads.iter().map(|d| (*d).to_owned()).collect(),
..PackFile::default()
}
}
#[test]
fn links_come_from_the_pack_or_modrinth_and_only_allowed_hosts() {
let mut cache = Cache::default();
cache.versions.insert(
"ab".into(),
json!({"files": [
{"hashes": {"sha1": "cd"}, "url": "https://cdn.modrinth.com/other.jar"},
{"hashes": {"sha1": "ab"}, "url": "https://cdn.modrinth.com/a.jar"}]}),
);
let pack_link = file(
Some("ab"),
&["https://evil.example/a.jar", "https://github.com/a.jar"],
);
assert_eq!(
url_of(&pack_link, &cache).as_deref(),
Some("https://github.com/a.jar")
);
let modrinth = file(Some("ab"), &["https://evil.example/a.jar"]);
assert_eq!(
url_of(&modrinth, &cache).as_deref(),
Some("https://cdn.modrinth.com/a.jar")
);
assert_eq!(url_of(&file(Some("ef"), &[]), &cache), None);
assert_eq!(url_of(&file(None, &[]), &cache), None);
}
#[test]
fn reads_a_curseforge_instance() {
let instance = json!({"installedAddons": [
{"addonID": 238222, "installedFile": {"id": 5101366, "fileName": "jei-1.21.1.jar"}},
{"addonID": 1, "installedFile": {"fileName": "no-id.jar"}}]});
let names = curseforge_names(&instance);
assert_eq!(names.len(), 1);
assert_eq!(names[&(238222, 5101366)], "jei-1.21.1.jar");
}
#[test]
fn copies_the_players_jars_and_lists_what_needs_a_key() {
let root = std::env::temp_dir().join(format!("horizon-fetch-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let (work, mine) = (root.join("work"), root.join("instance/mods"));
fs::create_dir_all(&mine).unwrap();
fs::create_dir_all(&work).unwrap();
fs::write(mine.join("renamed.jar"), b"jar a").unwrap();
fs::write(mine.join("cf.jar"), b"jar b").unwrap();
fs::write(
root.join("instance/minecraftinstance.json"),
json!({"installedAddons": [{"addonID": 7, "installedFile": {"id": 8, "fileName": "cf.jar"}}]})
.to_string(),
)
.unwrap();
let pack = Pack {
format: "curseforge".into(),
files: vec![
PackFile {
path: "mods/a.jar".into(),
sha1: Some(sha1_hex(b"jar a")),
..PackFile::default()
},
PackFile {
path: "mods/curseforge-7-8".into(),
curseforge: Some((7, 8)),
..PackFile::default()
},
PackFile {
path: "mods/curseforge-9-9".into(),
curseforge: Some((9, 9)),
..PackFile::default()
},
],
..Pack::default()
};
write_json(&work.join("pack.json"), &pack).unwrap();
let records: Vec<Record> = pack
.files
.iter()
.map(|f| Record {
key: f.file_name().into(),
path: f.path.clone(),
..Record::default()
})
.collect();
let fetched = fetch(
&work,
&records,
Some(&root.join("instance")),
&|_| true,
&|_| {},
)
.unwrap();
let hows: Vec<How> = fetched.files.iter().map(|o| o.how).collect();
assert_eq!(hows, [How::Local, How::Local, How::NeedsKey]);
assert_eq!(fs::read(work.join("jars/a.jar")).unwrap(), b"jar a");
assert_eq!(
fs::read(work.join("jars/curseforge-7-8")).unwrap(),
b"jar b"
);
// A second run finds them in place.
let again = fetch(&work, &records, None, &|_| true, &|_| {}).unwrap();
assert_eq!(again.count(How::Present), 2);
assert_eq!(Fetched::load(&work).count(How::Present), 2);
fs::remove_dir_all(&root).unwrap();
}
}
+57 -2
View File
@@ -22,8 +22,20 @@ pub struct Pack {
pub files: Vec<PackFile>,
/// Override files by top folder (`config`, `kubejs`, ...).
pub overrides: BTreeMap<String, usize>,
/// A CurseForge zip's files by project and file id only: how many its
/// manifest lists, when the files came from the pack's own mod list.
#[serde(default, skip_serializing_if = "is_zero")]
pub curseforge_files: usize,
}
fn is_zero(n: &usize) -> bool {
*n == 0
}
/// Where Crash Assistant keeps its list in an instance (and in the
/// overrides of packs that ship it, such as All the Mods 10).
pub const MODLIST: &str = "config/crash_assistant/modlist.json";
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PackFile {
/// Path in the instance (`mods/create-1.21.1-6.0.4.jar`).
@@ -83,7 +95,16 @@ pub fn import(path: &Path) -> Result<Pack, String> {
return Ok(mrpack(&index, &names(&zip)));
}
if let Some(manifest) = read_json(&mut zip, "manifest.json")? {
return Ok(curseforge(&manifest, &names(&zip)));
let mut pack = curseforge(&manifest, &names(&zip));
// The manifest names files only by CurseForge ids, which need a key
// to resolve; the pack's own mod list names them and gives their
// SHA-1s, so Modrinth can answer for most.
let root = manifest["overrides"].as_str().unwrap_or("overrides");
if let Some(list) = read_json(&mut zip, &format!("{root}/{MODLIST}"))? {
pack.curseforge_files = pack.files.len();
pack.files = modlist(&list)?.files;
}
return Ok(pack);
}
Err(format!(
"{}: neither modrinth.index.json nor manifest.json",
@@ -103,7 +124,7 @@ fn read_json(zip: &mut zip::ZipArchive<fs::File>, name: &str) -> Result<Option<V
entry
.read_to_string(&mut text)
.map_err(|e| format!("{name}: {e}"))?;
serde_json::from_str(&text)
serde_json::from_str(text.trim_start_matches('\u{feff}'))
.map(Some)
.map_err(|e| format!("{name}: {e}"))
}
@@ -161,6 +182,7 @@ pub fn mrpack(index: &Value, names: &[String]) -> Pack {
names,
&["overrides", "client-overrides", "server-overrides"],
),
..Pack::default()
}
}
@@ -197,6 +219,7 @@ pub fn curseforge(manifest: &Value, names: &[String]) -> Pack {
loader_version: loader_version.to_owned(),
files,
overrides: overrides(names, &[root]),
..Pack::default()
}
}
@@ -418,4 +441,36 @@ mod tests {
assert_eq!(p.files[0].curseforge, Some((238222, 5101366)));
assert_eq!(p.overrides["kubejs"], 1);
}
#[test]
fn a_curseforge_zip_takes_names_from_its_mod_list() {
use std::io::Write;
let dir = std::env::temp_dir().join(format!("horizon-cf-zip-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let path = dir.join("pack.zip");
let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap());
let opts = zip::write::SimpleFileOptions::default();
let manifest = json!({"name": "Pack", "overrides": "overrides",
"minecraft": {"version": "1.21.1", "modLoaders": [{"id": "neoforge-21.1.259"}]},
"files": [{"projectID": 1, "fileID": 2}, {"projectID": 3, "fileID": 4}]});
zip.start_file("manifest.json", opts).unwrap();
zip.write_all(manifest.to_string().as_bytes()).unwrap();
zip.start_file(format!("overrides/{MODLIST}"), opts)
.unwrap();
let list = json!({"mcw-doors-1.1.2.jar": {"jarName": "mcw-doors-1.1.2.jar",
"modId": "mcwdoors", "modrinthHash": "0123456789abcdef0123456789abcdef01234567"}});
// Crash Assistant writes a byte order mark.
zip.write_all(format!("\u{feff}{list}").as_bytes()).unwrap();
zip.finish().unwrap();
let pack = import(&path).unwrap();
assert_eq!(
(pack.format.as_str(), pack.name.as_str()),
("curseforge", "Pack")
);
assert_eq!(pack.curseforge_files, 2);
assert_eq!(pack.files.len(), 1);
assert_eq!(pack.files[0].path, "mods/mcw-doors-1.1.2.jar");
assert_eq!(pack.overrides["config"], 1);
fs::remove_dir_all(&dir).unwrap();
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Port a Java modpack to Horizon (`docs/modpacks.md`): the steps behind the
//! `horizon-port-pack` command, and the launcher's "Import modpack".
//!
//! Every step reads and writes files in a work folder (`pipeline`), so it can
//! be rerun, resumed and inspected. The work folder belongs to the user: the
//! jars they downloaded and what is carried over from them stay there and
//! are never uploaded or committed.
pub mod carry;
pub mod classify;
pub mod fetch;
pub mod import;
pub mod inventory;
pub mod jar;
pub mod modrinth;
pub mod oracle;
pub mod pipeline;
pub mod report;
+71 -188
View File
@@ -6,57 +6,77 @@
//! `<work>/modrinth.json`), the jars in the instance or `<work>/jars/`,
//! classes, tiers and dependency layers in `<work>/inventory.json` and
//! `inventory.csv`.
//! - `fetch <work> [--from <folder>] [<mod id>...]`: the jars of the
//! portable mods (content, data tier; or the ones named) into
//! `<work>/jars/`: copied from the player's folder, or downloaded from the
//! pack's own links or Modrinth's CDN, hash checked. What only CurseForge
//! has needs a key and is listed in `<work>/fetch.json`.
//! - `carry <work> [--resources <prepared>] [<mod id>...]`: the content
//! mods' data and assets into `<work>/mods/<id>/carry/`, a folder mod for
//! local use. With the NeoForge oracle's `<work>/oracle/facts.json`
//! (`tools/neoforge_oracle.py`), blocks and items come from its facts;
//! `--resources` limits templates to the blocks Horizon's tables have.
//!
//! - `report <work>`: the coverage report, per mod ported, partial, not yet
//! or not needed with the reason, in `<work>/coverage.json` and
//! `coverage.md`.
//! - `port <pack> <work> [--from <folder>] [--resources <prepared>]`: every
//! step for the portable mods, as the launcher's "Import modpack" runs it.
//!
//! The work folder belongs to the user: jars and carried-over files stay
//! there and are never uploaded or committed.
mod carry;
mod classify;
mod import;
mod inventory;
mod jar;
mod modrinth;
mod oracle;
mod report;
use horizon_port_pack::{fetch, inventory::Record, pipeline};
use std::{
path::{Path, PathBuf},
process::ExitCode,
};
use std::{fs, path::Path, process::ExitCode};
const USAGE: &str = "usage: horizon-port-pack import <pack> <work> | inventory <work> [--offline] | carry <work> [--resources <prepared>] [<mod id>...] | report <work>";
const USAGE: &str = "usage: horizon-port-pack import <pack> <work> | inventory <work> [--offline] | fetch <work> [--from <folder>] [<mod id>...] | carry <work> [--resources <prepared>] [<mod id>...] | report <work> | port <pack> <work> [--from <folder>] [--resources <prepared>]";
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let path = |i: usize| args.get(i).map(Path::new).ok_or(USAGE.to_owned());
let result = match args.first().map(String::as_str) {
Some("import") => path(1)
.and_then(|p| Ok((p, path(2)?)))
.and_then(|(p, w)| import(p, w)),
Some("inventory") => {
path(1).and_then(|w| inventory(w, args.iter().any(|a| a == "--offline")))
let mut args: Vec<String> = std::env::args().skip(1).collect();
let result = (|| {
let from = option(&mut args, "--from")?;
let resources = option(&mut args, "--resources")?;
let offline = take_flag(&mut args, "--offline");
let path = |i: usize| args.get(i).map(Path::new).ok_or(USAGE.to_owned());
let rest = || args.get(2..).unwrap_or_default().to_vec();
let log = &|line: String| println!("{line}");
match args.first().map(String::as_str) {
Some("import") => pipeline::import(path(1)?, path(2)?, log).map(drop),
Some("inventory") => pipeline::inventory(path(1)?, offline, log).map(drop),
Some("fetch") => {
let work = path(1)?;
let records: Vec<Record> = pipeline::read_json(&work.join("inventory.json"))?;
let only = rest();
let want = |r: &Record| {
if only.is_empty() {
pipeline::portable(r)
} else {
only.contains(&r.key)
}
};
fetch::fetch(work, &records, from.as_deref(), &want, log).map(drop)
}
Some("carry") => {
pipeline::carry(path(1)?, resources.as_deref(), &rest(), log).map(drop)
}
Some("report") => {
let work = path(1)?;
pipeline::report(work, log)?;
println!("{}", work.join("coverage.md").display());
Ok(())
}
Some("port") => {
let work = path(2)?;
pipeline::import(path(1)?, work, log)?;
pipeline::inventory(work, offline, log)?;
pipeline::port(work, resources.as_deref(), from.as_deref(), log)?;
println!("{}", work.join("coverage.md").display());
Ok(())
}
_ => Err(USAGE.to_owned()),
}
Some("carry") => path(1).and_then(|w| {
let mut rest = args[2..].to_vec();
let resources = match rest.iter().position(|a| a == "--resources") {
Some(i) if i + 1 < rest.len() => {
let r = rest.remove(i + 1);
rest.remove(i);
Some(std::path::PathBuf::from(r))
}
Some(_) => return Err(USAGE.to_owned()),
None => None,
};
carry(w, resources.as_deref(), &rest)
}),
Some("report") => path(1).and_then(report),
_ => Err(USAGE.to_owned()),
};
})();
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
@@ -66,158 +86,21 @@ fn main() -> ExitCode {
}
}
fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<(), String> {
let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?;
fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
}
fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, String> {
let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
}
fn report(work: &Path) -> Result<(), String> {
let pack: import::Pack = read_json(&work.join("pack.json"))?;
let records: Vec<inventory::Record> = read_json(&work.join("inventory.json"))?;
let rows = report::build(&records, work);
write_json(&work.join("coverage.json"), &rows)?;
let title = format!(
"{} ({} {}, Minecraft {})",
pack.name, pack.loader, pack.loader_version, pack.minecraft
);
fs::write(work.join("coverage.md"), report::markdown(&title, &rows))
.map_err(|e| format!("coverage.md: {e}"))?;
println!("{title}: {} files: {:?}", rows.len(), report::counts(&rows));
println!("{}", work.join("coverage.md").display());
Ok(())
}
fn import(pack: &Path, work: &Path) -> Result<(), String> {
let pack = import::import(pack)?;
fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?;
write_json(&work.join("pack.json"), &pack)?;
let mut kinds = std::collections::BTreeMap::<&str, usize>::new();
for f in &pack.files {
*kinds.entry(f.kind()).or_default() += 1;
}
println!(
"{} ({}): Minecraft {}, {} {}; files {kinds:?}; overrides {:?}",
pack.name, pack.format, pack.minecraft, pack.loader, pack.loader_version, pack.overrides
);
Ok(())
}
fn inventory(work: &Path, offline: bool) -> Result<(), String> {
let pack: import::Pack = read_json(&work.join("pack.json"))?;
let cache_path = work.join("modrinth.json");
let mut cache = modrinth::Cache::load(&cache_path);
if !offline {
let hashes: Vec<String> = pack.files.iter().filter_map(|f| f.sha1.clone()).collect();
cache.fetch(&hashes)?;
write_json(&cache_path, &cache)?;
}
let records = inventory::build(&pack, &cache, work);
write_json(&work.join("inventory.json"), &records)?;
fs::write(work.join("inventory.csv"), inventory::csv(&records))
.map_err(|e| format!("inventory.csv: {e}"))?;
let jars = records.iter().filter(|r| r.jar.is_some()).count();
println!("{} files, {jars} jars read", records.len());
for (title, field) in [
(
"class",
(|r: &inventory::Record| r.class.as_str()) as fn(&inventory::Record) -> &str,
),
("tier", |r| r.tier.as_str()),
("confidence", |r| r.confidence.as_str()),
("source", |r| r.source.as_str()),
] {
println!("{title}: {:?}", inventory::counts(&records, field));
}
let layers = records.iter().map(|r| r.layer).max().map_or(0, |m| m + 1);
let per_layer: Vec<usize> = (0..layers)
.map(|l| records.iter().filter(|r| r.layer == l).count())
.collect();
println!("layers: {per_layer:?}");
let missing: usize = records.iter().map(|r| r.missing.len()).sum();
if missing > 0 {
println!("{missing} required dependencies are not in the pack (see inventory.json)");
}
Ok(())
}
/// The vanilla blocks a prepared resource root has (`facts.json`'s defaults).
fn vanilla_blocks(resources: &Path) -> Result<std::collections::BTreeSet<String>, String> {
let facts: serde_json::Value = read_json(&resources.join("facts.json"))?;
let defaults = facts["defaults"]
.as_object()
.ok_or("facts.json: no defaults")?;
Ok(defaults.keys().cloned().collect())
}
fn carry(work: &Path, resources: Option<&Path>, only: &[String]) -> Result<(), String> {
let records: Vec<inventory::Record> = read_json(&work.join("inventory.json"))?;
let facts_path = work.join("oracle/facts.json");
let facts = if facts_path.exists() {
let f = oracle::Facts::read(&facts_path)?;
println!(
"oracle facts: {} blocks, {} items",
f.blocks.len(),
f.items.len()
);
Some(f)
} else {
None
};
let vanilla = resources.map(vanilla_blocks).transpose()?;
let allowed = |b: &str| vanilla.as_ref().is_none_or(|v| v.contains(b));
let mut done = 0;
for r in &records {
let chosen = if only.is_empty() {
r.class == "content"
} else {
only.contains(&r.key)
};
let (Some(jar), Some(info)) = (&r.jar, &r.info) else {
if chosen && !only.is_empty() {
eprintln!("{}: no jar (put it in {}/jars/)", r.key, work.display());
}
continue;
};
if !chosen {
continue;
}
match carry::carry(
jar,
info,
&work.join("mods").join(&r.key),
facts.as_ref(),
&allowed,
) {
Ok(report) => {
done += 1;
println!(
"{}: {} files, {} recipes upgraded ({} kept), {} loot tables upgraded, {} item definitions added, {} blocks ({} left out, {} with differences), {} items ({} left out), {} convention tags, {} outside",
r.key,
report.copied,
report.recipes_upgraded,
report.recipes_kept.len(),
report.loot_tables_upgraded,
report.item_definitions_added,
report.blocks.len(),
report.blocks_unknown.len(),
report.differences.len(),
report.items,
report.items_unknown.len(),
report.convention_tags,
report.outside.len()
);
}
Err(e) => eprintln!("{}: {e}", r.key),
/// Removes `--name <value>` from `args`.
fn option(args: &mut Vec<String>, name: &str) -> Result<Option<PathBuf>, String> {
match args.iter().position(|a| a == name) {
Some(i) if i + 1 < args.len() => {
let value = args.remove(i + 1);
args.remove(i);
Ok(Some(PathBuf::from(value)))
}
Some(_) => Err(USAGE.to_owned()),
None => Ok(None),
}
println!(
"{done} mods carried over into {}",
work.join("mods").display()
);
Ok(())
}
fn take_flag(args: &mut Vec<String>, name: &str) -> bool {
let before = args.len();
args.retain(|a| a != name);
args.len() != before
}
+3 -3
View File
@@ -1,13 +1,13 @@
//! Modrinth metadata for the pack's files: the version of each file by
//! SHA-1, and its project (categories, licence, sides). Only metadata: no
//! jar is downloaded. Answers are cached in `<work>/modrinth.json`, so a
//! SHA-1, and its project (categories, licence, sides). Only metadata (the
//! jars are `fetch`'s). Answers are cached in `<work>/modrinth.json`, so a
//! rerun works offline.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::BTreeMap, path::Path};
const API: &str = "https://api.modrinth.com/v2";
const AGENT: &str = "ludovic111/horizon horizon-port-pack/0.1 (docs/modpacks.md)";
pub(crate) const AGENT: &str = "ludovic111/horizon horizon-port-pack/0.1 (docs/modpacks.md)";
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Cache {
+246
View File
@@ -0,0 +1,246 @@
//! The steps on a work folder, as the command line and the launcher run
//! them. Each one reads what the earlier steps wrote and says what it did
//! through `log`, one line at a time.
use crate::{carry, fetch, import, inventory, modrinth, oracle, report};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::Path,
};
/// Where a step's lines go: the terminal, or the launcher's log.
pub type Log<'a> = &'a dyn Fn(String);
pub fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<(), String> {
let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?;
fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
}
pub fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, String> {
let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
}
/// Step 1: the pack at `pack` to `<work>/pack.json`.
pub fn import(pack: &Path, work: &Path, log: Log) -> Result<import::Pack, String> {
let pack = import::import(pack)?;
fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?;
write_json(&work.join("pack.json"), &pack)?;
let mut kinds = BTreeMap::<&str, usize>::new();
for f in &pack.files {
*kinds.entry(f.kind()).or_default() += 1;
}
log(format!(
"{} ({}): Minecraft {}, {} {}; files {kinds:?}; overrides {:?}",
pack.name, pack.format, pack.minecraft, pack.loader, pack.loader_version, pack.overrides
));
Ok(pack)
}
/// Step 2: `<work>/inventory.json` and `inventory.csv`. Online, Modrinth is
/// asked about the files it has not answered for yet; when it cannot be
/// reached, the cached answers and the reviewed table classify alone.
pub fn inventory(work: &Path, offline: bool, log: Log) -> Result<Vec<inventory::Record>, String> {
let pack: import::Pack = read_json(&work.join("pack.json"))?;
let cache_path = work.join("modrinth.json");
let mut cache = modrinth::Cache::load(&cache_path);
if !offline {
let hashes: Vec<String> = pack.files.iter().filter_map(|f| f.sha1.clone()).collect();
match cache.fetch(&hashes) {
Ok(()) => write_json(&cache_path, &cache)?,
Err(e) => log(format!("Modrinth not reached, classifying offline: {e}")),
}
}
let records = inventory::build(&pack, &cache, work);
write_json(&work.join("inventory.json"), &records)?;
fs::write(work.join("inventory.csv"), inventory::csv(&records))
.map_err(|e| format!("inventory.csv: {e}"))?;
let jars = records.iter().filter(|r| r.jar.is_some()).count();
log(format!("{} files, {jars} jars read", records.len()));
for (title, field) in [
(
"class",
(|r: &inventory::Record| r.class.as_str()) as fn(&inventory::Record) -> &str,
),
("tier", |r| r.tier.as_str()),
("confidence", |r| r.confidence.as_str()),
("source", |r| r.source.as_str()),
] {
log(format!("{title}: {:?}", inventory::counts(&records, field)));
}
let layers = records.iter().map(|r| r.layer).max().map_or(0, |m| m + 1);
let per_layer: Vec<usize> = (0..layers)
.map(|l| records.iter().filter(|r| r.layer == l).count())
.collect();
log(format!("layers: {per_layer:?}"));
let missing: usize = records.iter().map(|r| r.missing.len()).sum();
if missing > 0 {
log(format!(
"{missing} required dependencies are not in the pack (see inventory.json)"
));
}
Ok(records)
}
/// The vanilla blocks a prepared resource root has (`facts.json`'s defaults).
fn vanilla_blocks(resources: &Path) -> Result<BTreeSet<String>, String> {
let facts: serde_json::Value = read_json(&resources.join("facts.json"))?;
let defaults = facts["defaults"]
.as_object()
.ok_or("facts.json: no defaults")?;
Ok(defaults.keys().cloned().collect())
}
/// Step 4: the content mods with a jar (or the ones in `only`) carried over
/// into `<work>/mods/<id>/carry/`. Returns how many were.
pub fn carry(
work: &Path,
resources: Option<&Path>,
only: &[String],
log: Log,
) -> Result<usize, String> {
let records: Vec<inventory::Record> = read_json(&work.join("inventory.json"))?;
let facts_path = work.join("oracle/facts.json");
let facts = if facts_path.exists() {
let f = oracle::Facts::read(&facts_path)?;
log(format!(
"oracle facts: {} blocks, {} items",
f.blocks.len(),
f.items.len()
));
Some(f)
} else {
None
};
// Without the prepared tables, templates are not limited to what the game has.
let vanilla = resources.and_then(|r| {
vanilla_blocks(r)
.inspect_err(|e| log(format!("templates not limited to the game's blocks: {e}")))
.ok()
});
let allowed = |b: &str| vanilla.as_ref().is_none_or(|v| v.contains(b));
let mut done = 0;
for r in &records {
let chosen = if only.is_empty() {
r.class == "content"
} else {
only.contains(&r.key)
};
let (Some(jar), Some(info)) = (&r.jar, &r.info) else {
if chosen && !only.is_empty() {
log(format!(
"{}: no jar (put it in {}/jars/)",
r.key,
work.display()
));
}
continue;
};
if !chosen {
continue;
}
// The oracle's facts for the mods it ran; a mod it did not load (a
// library missing) keeps the guesses from its blockstates.
let prefix = format!("{}:", info.mod_id);
let seen = |f: &&oracle::Facts| {
f.blocks
.keys()
.chain(f.items.keys())
.any(|k| k.starts_with(&prefix))
};
match carry::carry(
jar,
info,
&work.join("mods").join(&r.key),
facts.as_ref().filter(seen),
&allowed,
) {
Ok(report) => {
done += 1;
log(format!(
"{}: {} files, {} recipes upgraded ({} kept), {} loot tables upgraded, {} item definitions added, {} blocks ({} left out, {} with differences), {} items ({} left out), {} convention tags, {} outside",
r.key,
report.copied,
report.recipes_upgraded,
report.recipes_kept.len(),
report.loot_tables_upgraded,
report.item_definitions_added,
report.blocks.len(),
report.blocks_unknown.len(),
report.differences.len(),
report.items,
report.items_unknown.len(),
report.convention_tags,
report.outside.len()
));
}
Err(e) => log(format!("{}: {e}", r.key)),
}
}
log(format!(
"{done} mods carried over into {}",
work.join("mods").display()
));
Ok(done)
}
/// The pack's title as the report heads it.
pub fn title(pack: &import::Pack) -> String {
format!(
"{} ({} {}, Minecraft {})",
pack.name, pack.loader, pack.loader_version, pack.minecraft
)
}
/// Step 7: `<work>/coverage.json` and `coverage.md`.
pub fn report(work: &Path, log: Log) -> Result<Vec<report::Row>, String> {
let pack: import::Pack = read_json(&work.join("pack.json"))?;
let records: Vec<inventory::Record> = read_json(&work.join("inventory.json"))?;
let rows = report::build(&records, work);
write_json(&work.join("coverage.json"), &rows)?;
let title = title(&pack);
fs::write(work.join("coverage.md"), report::markdown(&title, &rows))
.map_err(|e| format!("coverage.md: {e}"))?;
log(format!(
"{title}: {} files: {:?}",
rows.len(),
report::counts(&rows)
));
Ok(rows)
}
/// What a player's machine can port today without an agent: content mods
/// of the data tier (carry-over only).
pub fn portable(r: &inventory::Record) -> bool {
r.class == "content" && r.tier == "data"
}
/// Everything after the import, for the portable mods: their jars (`fetch`,
/// from `from` when the player has them), the inventory again with the jars
/// read, the carry-over and the report. `resources` is the prepared
/// version the ports will play on.
pub fn port(
work: &Path,
resources: Option<&Path>,
from: Option<&Path>,
log: Log,
) -> Result<(fetch::Fetched, Vec<report::Row>), String> {
let records = match read_json::<Vec<inventory::Record>>(&work.join("inventory.json")) {
Ok(r) => r,
Err(_) => inventory(work, false, log)?,
};
let fetched = fetch::fetch(work, &records, from, &portable, log)?;
// The jars tell classes and tiers better than metadata alone.
let records = inventory(work, true, log)?;
let only: Vec<String> = records
.iter()
.filter(|r| portable(r) && r.jar.is_some())
.map(|r| r.key.clone())
.collect();
if only.is_empty() {
log("no portable mod has its jar: nothing to carry over".into());
} else {
carry(work, resources, &only, log)?;
}
Ok((fetched, report(work, log)?))
}
+1 -1
View File
@@ -83,7 +83,7 @@ pub fn license_kind(license: &str) -> &'static str {
/// What still blocks a mod of this tier that has not been carried over.
fn not_yet(tier: &str) -> &'static str {
match tier {
"data" => "data tier: carry-over only, no agent; its jar is not in the work folder",
"data" => "data tier: carry-over only, no agent; its jar is not here yet (fetch gets it)",
"logic" => {
"needs mod API 0.3: behaviour callbacks (use, place, break, ticks) and server events"
}
+84
View File
@@ -114,6 +114,67 @@ impl Paletted {
/// Pack values the way the server's container would have grown:
/// the smallest configuration for the number of distinct values.
pub fn from_values(values: &[i32], strategy: Strategy, global_bits: u8) -> Self {
// Palette indices by value, in first-seen order: a table over the
// value range (registry ids are small), kept per thread and cleared
// after use, with the previous value remembered, since neighbouring
// blocks repeat.
thread_local! {
static INDEX: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) };
}
let max = values.iter().copied().max().unwrap_or(0);
if values.iter().any(|&v| v < 0) || max >= 1 << 20 {
return Self::from_values_slow(values, strategy, global_bits);
}
let mut palette: Vec<i32> = Vec::new();
let mut ids = Vec::with_capacity(values.len());
INDEX.with_borrow_mut(|index| {
if index.len() <= max as usize {
index.resize(max as usize + 1, u32::MAX);
}
let (mut last, mut last_id) = (-1i32, 0u32);
for &v in values {
if v != last {
let slot = &mut index[v as usize];
if *slot == u32::MAX {
*slot = palette.len() as u32;
palette.push(v);
}
(last, last_id) = (v, *slot);
}
ids.push(last_id);
}
for &v in &palette {
index[v as usize] = u32::MAX;
}
});
let needed = if palette.len() <= 1 {
0
} else {
(usize::BITS - (palette.len() - 1).leading_zeros()) as u8
};
let (has_palette, bits) = strategy.configuration(needed, global_bits);
if bits == 0 {
return Self {
bits: 0,
palette: vec![palette.first().copied().unwrap_or(0)],
data: Vec::new(),
};
}
let mut data = vec![0i64; storage_len(bits, values.len())];
let per = 64 / bits as usize;
for (i, (&v, &id)) in values.iter().zip(&ids).enumerate() {
let id = if has_palette { u64::from(id) } else { v as u64 };
data[i / per] |= (id << ((i % per) * bits as usize)) as i64;
}
Self {
bits,
palette: if has_palette { palette } else { Vec::new() },
data,
}
}
/// `from_values` for any values: linear palette searches.
fn from_values_slow(values: &[i32], strategy: Strategy, global_bits: u8) -> Self {
let mut palette: Vec<i32> = Vec::new();
for &v in values {
if !palette.contains(&v) {
@@ -290,6 +351,29 @@ pub fn nibble(layer: &[u8], i: usize) -> u8 {
mod tests {
use super::*;
#[test]
fn from_values_matches_the_linear_search() {
let mut seed = 12345u64;
let mut next = |n: u64| {
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((seed >> 33) % n) as i32
};
for distinct in [1u64, 2, 16, 17, 200, 300, 5000] {
let values: Vec<i32> = (0..BLOCKS).map(|_| next(distinct) * 7).collect();
assert_eq!(
Paletted::from_values(&values, Strategy::Blocks, 16),
Paletted::from_values_slow(&values, Strategy::Blocks, 16)
);
let biomes: Vec<i32> = values[..BIOMES].to_vec();
assert_eq!(
Paletted::from_values(&biomes, Strategy::Biomes, 7),
Paletted::from_values_slow(&biomes, Strategy::Biomes, 7)
);
}
}
#[test]
fn bit_storage_matches_simple_bit_storage() {
// 5 bits: 12 values per long, the top 4 bits of each long unused.
+36
View File
@@ -218,6 +218,42 @@ impl Codec<Option<Stack>> for Slot {
}
}
/// ItemStackTemplate.STREAM_CODEC: the item, the count, then the patch.
pub struct Template;
impl Codec<Stack> for Template {
fn read(r: &mut Reader) -> Result<Stack> {
let item = r.varint()?;
let count = r.varint()?;
let positive = r.count(65536)?;
let negative = r.count(65536)?;
let mut added = Vec::with_capacity(positive.min(64));
for _ in 0..positive {
let kind = r.varint()?;
added.push((kind, Component::read(kind, r)?));
}
let removed = (0..negative).map(|_| r.varint()).collect::<Result<_>>()?;
Ok(Stack {
item,
count,
added,
removed,
})
}
fn write(s: &Stack, w: &mut Writer) {
w.varint(s.item);
w.varint(s.count);
w.varint(s.added.len() as i32);
w.varint(s.removed.len() as i32);
for (kind, c) in &s.added {
w.varint(*kind);
c.write(*kind, w);
}
for kind in &s.removed {
w.varint(*kind);
}
}
}
/// HashedStack: what the client believes a slot holds. Component values are
/// sent as hashes; Horizon sends patches without hashes, so a server whose
/// stack carries components resynchronises that slot (as it does for any
+385
View File
@@ -577,6 +577,14 @@ packet!(
);
packet!(Text { text: Tag => Nbt });
packet!(SetChunkCacheCenter { x: i32 => VarInt, z: i32 => VarInt });
packet!(
/// ClientboundTickingStatePacket: the tick rate and whether the level is frozen.
TickingState { rate: f32 => Float, frozen: bool => Bool }
);
packet!(
/// ClientboundTickingStepPacket: the ticks a frozen level runs (`/tick step`).
TickingStep { steps: i32 => VarInt }
);
packet!(Distance { distance: i32 => VarInt });
packet!(SetCursorItem { item: Option<Stack> => Slot });
packet!(SetDefaultSpawnPosition { pos: GlobalPos => GlobalPos, yaw: f32 => Float, pitch: f32 => Float });
@@ -977,10 +985,200 @@ impl Codec<Commands> for Commands {
}
}
/// `DisplayInfo` of an advancement as sent.
#[derive(Clone, Debug, PartialEq)]
pub struct AdvancementDisplay {
pub title: Tag,
pub description: Tag,
pub icon: crate::item::Stack,
/// `AdvancementType` ordinal: task, challenge, goal.
pub frame: i32,
pub show_toast: bool,
pub hidden: bool,
pub background: Option<String>,
}
/// `ClientboundUpdateAdvancementsPacket.PositionedAdvancement`.
#[derive(Clone, Debug, PartialEq)]
pub struct Advancement {
pub id: String,
pub parent: Option<String>,
pub display: Option<AdvancementDisplay>,
pub requirements: Vec<Vec<String>>,
pub telemetry: bool,
pub x: f32,
pub y: f32,
}
/// `ClientboundUpdateAdvancementsPacket`: whether it replaces what the
/// client has, the advancements added and removed, the progress of each
/// changed one (criterion, when obtained in epoch milliseconds), and whether
/// to show toasts.
#[derive(Clone, Debug, PartialEq)]
pub struct UpdateAdvancements {
pub reset: bool,
pub added: Vec<Advancement>,
pub removed: Vec<String>,
pub progress: Vec<(String, Vec<(String, Option<i64>)>)>,
pub show: bool,
}
impl Codec<UpdateAdvancements> for UpdateAdvancements {
fn read(r: &mut Reader) -> Result<Self> {
let reset = r.bool()?;
let n = r.count(r.remaining())?;
let mut added = Vec::with_capacity(n.min(1024));
for _ in 0..n {
let id = r.string(32767)?;
let parent = if r.bool()? {
Some(r.string(32767)?)
} else {
None
};
let display = if r.bool()? {
let title = r.nbt()?;
let description = r.nbt()?;
let icon = crate::item::Template::read(r)?;
let frame = r.varint()?;
let flags = r.i32()?;
let background = if flags & 1 != 0 {
Some(r.string(32767)?)
} else {
None
};
Some(AdvancementDisplay {
title,
description,
icon,
frame,
show_toast: flags & 2 != 0,
hidden: flags & 4 != 0,
background,
})
} else {
None
};
let groups = r.count(r.remaining())?;
let mut requirements = Vec::with_capacity(groups.min(256));
for _ in 0..groups {
let k = r.count(r.remaining())?;
requirements.push((0..k).map(|_| r.string(32767)).collect::<Result<_>>()?);
}
let telemetry = r.bool()?;
let (x, y) = (r.f32()?, r.f32()?);
added.push(Advancement {
id,
parent,
display,
requirements,
telemetry,
x,
y,
});
}
let n = r.count(r.remaining())?;
let removed = (0..n).map(|_| r.string(32767)).collect::<Result<_>>()?;
let n = r.count(r.remaining())?;
let mut progress = Vec::with_capacity(n.min(1024));
for _ in 0..n {
let id = r.string(32767)?;
let k = r.count(r.remaining())?;
let mut criteria = Vec::with_capacity(k.min(256));
for _ in 0..k {
let name = r.string(32767)?;
let at = if r.bool()? { Some(r.i64()?) } else { None };
criteria.push((name, at));
}
progress.push((id, criteria));
}
let show = r.bool()?;
Ok(Self {
reset,
added,
removed,
progress,
show,
})
}
fn write(v: &Self, w: &mut Writer) {
w.bool(v.reset);
w.varint(v.added.len() as i32);
for a in &v.added {
w.string(&a.id);
w.bool(a.parent.is_some());
if let Some(p) = &a.parent {
w.string(p);
}
w.bool(a.display.is_some());
if let Some(d) = &a.display {
w.nbt(&d.title);
w.nbt(&d.description);
crate::item::Template::write(&d.icon, w);
w.varint(d.frame);
w.i32(
i32::from(d.background.is_some())
| i32::from(d.show_toast) << 1
| i32::from(d.hidden) << 2,
);
if let Some(b) = &d.background {
w.string(b);
}
}
w.varint(a.requirements.len() as i32);
for g in &a.requirements {
w.varint(g.len() as i32);
for c in g {
w.string(c);
}
}
w.bool(a.telemetry);
w.f32(a.x);
w.f32(a.y);
}
w.varint(v.removed.len() as i32);
for id in &v.removed {
w.string(id);
}
w.varint(v.progress.len() as i32);
for (id, criteria) in &v.progress {
w.string(id);
w.varint(criteria.len() as i32);
for (name, at) in criteria {
w.string(name);
w.bool(at.is_some());
if let Some(at) = at {
w.i64(*at);
}
}
}
w.bool(v.show);
}
}
packet!(
/// ClientboundAwardStatsPacket: (stat type, value, count) by network id.
AwardStats { stats: Vec<(i32, i32, i32)> => StatList }
);
/// `Object2IntMap<Stat<?>>`: each stat's type and value ids, then its count.
pub struct StatList;
impl Codec<Vec<(i32, i32, i32)>> for StatList {
fn read(r: &mut Reader) -> Result<Vec<(i32, i32, i32)>> {
let n = r.count(r.remaining())?;
(0..n)
.map(|_| Ok((r.varint()?, r.varint()?, r.varint()?)))
.collect()
}
fn write(v: &Vec<(i32, i32, i32)>, w: &mut Writer) {
w.varint(v.len() as i32);
for &(a, b, c) in v {
w.varint(a);
w.varint(b);
w.varint(c);
}
}
}
packet_enum!(Clientbound, crate::ids::play::clientbound {
BundleDelimiter(Empty) = BUNDLE_DELIMITER,
AddEntity(AddEntity) = ADD_ENTITY,
Animate(Animate) = ANIMATE,
AwardStats(AwardStats) = AWARD_STATS,
BlockChangedAck(BlockChangedAck) = BLOCK_CHANGED_ACK,
BlockDestruction(BlockDestruction) = BLOCK_DESTRUCTION,
BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA,
@@ -1066,14 +1264,131 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
TabList(TabList) = TAB_LIST,
TakeItemEntity(TakeItemEntity) = TAKE_ITEM_ENTITY,
TeleportEntity(TeleportEntity) = TELEPORT_ENTITY,
TickingState(TickingState) = TICKING_STATE,
TickingStep(TickingStep) = TICKING_STEP,
UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS,
UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT,
UpdateTags(UpdateTags) = UPDATE_TAGS,
TrackedWaypoint(TrackedWaypoint) = WAYPOINT,
});
packet!(
/// ClientboundClearTitlesPacket: whether to also reset the timings.
Bool1 { value: bool => Bool }
);
/// ClientboundTrackedWaypointPacket.Operation, by ordinal.
pub mod waypoint_operation {
pub const TRACK: i32 = 0;
pub const UNTRACK: i32 = 1;
pub const UPDATE: i32 = 2;
}
/// TrackedWaypoint's identifier: `Either<UUID, String>`.
#[derive(Clone, Debug, PartialEq)]
pub enum WaypointId {
Uuid(u128),
Name(String),
}
/// What a TrackedWaypoint points at (its `Type` and contents).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WaypointTarget {
/// `TrackedWaypoint.empty`: an untracked waypoint.
Empty,
/// A block position (`Vec3iWaypoint`).
Block([i32; 3]),
/// A chunk (`ChunkWaypoint`).
Chunk([i32; 2]),
/// An angle in radians (`AzimuthWaypoint`).
Azimuth(f32),
}
/// ClientboundTrackedWaypointPacket: the locator bar's waypoints.
#[derive(Clone, Debug, PartialEq)]
pub struct TrackedWaypoint {
/// `waypoint_operation`.
pub operation: i32,
pub id: WaypointId,
/// Waypoint.Icon: the style (a `waypoint_style_asset` key) and an RGB colour.
pub style: String,
pub color: Option<i32>,
pub target: WaypointTarget,
}
impl Codec<TrackedWaypoint> for TrackedWaypoint {
fn read(r: &mut Reader) -> Result<TrackedWaypoint> {
let operation = r.varint()?;
if !(0..=2).contains(&operation) {
return Err(Error::new(format!("waypoint operation {operation}")));
}
let id = if r.bool()? {
WaypointId::Uuid(r.uuid()?)
} else {
WaypointId::Name(r.string(32767)?)
};
let style = Ident::read(r)?;
// ByteBufCodecs.RGB_COLOR: three bytes, read back as an opaque ARGB colour.
let color = if r.bool()? {
let [red, green, blue] = [r.u8()?, r.u8()?, r.u8()?].map(i32::from);
Some(-16_777_216 | red << 16 | green << 8 | blue)
} else {
None
};
let target = match r.varint()? {
0 => WaypointTarget::Empty,
1 => WaypointTarget::Block([r.varint()?, r.varint()?, r.varint()?]),
2 => WaypointTarget::Chunk([r.varint()?, r.varint()?]),
3 => WaypointTarget::Azimuth(r.f32()?),
other => return Err(Error::new(format!("waypoint type {other}"))),
};
Ok(TrackedWaypoint {
operation,
id,
style,
color,
target,
})
}
fn write(v: &TrackedWaypoint, w: &mut Writer) {
w.varint(v.operation);
match &v.id {
WaypointId::Uuid(uuid) => {
w.bool(true);
w.uuid(*uuid);
}
WaypointId::Name(name) => {
w.bool(false);
w.string(name);
}
}
w.string(&v.style);
w.bool(v.color.is_some());
if let Some(color) = v.color {
for shift in [16, 8, 0] {
w.u8((color >> shift) as u8);
}
}
match v.target {
WaypointTarget::Empty => w.varint(0),
WaypointTarget::Block([x, y, z]) => {
w.varint(1);
w.varint(x);
w.varint(y);
w.varint(z);
}
WaypointTarget::Chunk([x, z]) => {
w.varint(2);
w.varint(x);
w.varint(z);
}
WaypointTarget::Azimuth(angle) => {
w.varint(3);
w.f32(angle);
}
}
}
}
// ---- serverbound -------------------------------------------------------
packet!(AcceptTeleportation { id: i32 => VarInt, x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float });
@@ -1288,6 +1603,42 @@ mod tests {
}
}
#[test]
fn tracked_waypoint_bytes() {
// TRACK, a UUID, the default style, red (#FF5555), a block position.
let track = Clientbound::TrackedWaypoint(TrackedWaypoint {
operation: waypoint_operation::TRACK,
id: WaypointId::Uuid(0x0102_0304_0506_0708_090a_0b0c_0d0e_0f10),
style: "minecraft:default".into(),
color: Some(0xFFFF_5555_u32 as i32),
target: WaypointTarget::Block([1, -2, 300]),
});
let mut expected = vec![141, 1, 0, 1];
expected.extend(1..=16u8);
expected.push(17);
expected.extend(b"minecraft:default");
expected.extend([
1, 0xFF, 0x55, 0x55, 1, 1, 0xFE, 0xFF, 0xFF, 0xFF, 0x0F, 0xAC, 0x02,
]);
assert_eq!(track.encode(), expected);
assert_eq!(Clientbound::decode(141, &expected[2..]).unwrap(), track);
for target in [
WaypointTarget::Empty,
WaypointTarget::Chunk([-3, 4]),
WaypointTarget::Azimuth(-1.25),
] {
let packet = Clientbound::TrackedWaypoint(TrackedWaypoint {
operation: waypoint_operation::UPDATE,
id: WaypointId::Name("spawn".into()),
style: "minecraft:bowtie".into(),
color: None,
target,
});
let bytes = packet.encode();
assert_eq!(Clientbound::decode(141, &bytes[2..]).unwrap(), packet);
}
}
#[test]
fn clientbound_round_trips() {
let packets = vec![
@@ -1573,6 +1924,40 @@ mod tests {
relatives: 0,
on_ground: true,
}),
Clientbound::TickingState(TickingState {
rate: 40.0,
frozen: true,
}),
Clientbound::TickingStep(TickingStep { steps: 7 }),
Clientbound::AwardStats(AwardStats {
stats: vec![(8, 3, 120), (0, 1, 2)],
}),
Clientbound::UpdateAdvancements(UpdateAdvancements {
reset: true,
added: vec![Advancement {
id: "minecraft:story/root".into(),
parent: None,
display: Some(AdvancementDisplay {
title: literal("Minecraft"),
description: literal("The heart and story of the game"),
icon: crate::item::Stack::new(42, 1),
frame: 0,
show_toast: false,
hidden: false,
background: Some("minecraft:block/stone".into()),
}),
requirements: vec![vec!["crafting_table".into()]],
telemetry: false,
x: 0.0,
y: 1.5,
}],
removed: vec!["minecraft:story/gone".into()],
progress: vec![(
"minecraft:story/root".into(),
vec![("crafting_table".into(), Some(1_792_216_800_000))],
)],
show: true,
}),
];
for p in packets {
round_trip(p, Clientbound::encode, Clientbound::decode);
+279 -1
View File
@@ -1,7 +1,9 @@
//! RSA for the online-mode login: the server's X.509 public key
//! (Crypt.byteToPublicKey) and PKCS#1 v1.5 encryption of the shared secret
//! and challenge (Crypt.encryptUsingKey, Java's "RSA" cipher =
//! RSA/ECB/PKCS1Padding). Modular exponentiation uses Montgomery
//! RSA/ECB/PKCS1Padding), and on the server's side the key pair it makes at
//! startup (Crypt.generateKeyPair: 1024 bits) and the decryption
//! (Crypt.decryptUsingKey). Modular exponentiation uses Montgomery
//! multiplication on 32-bit limbs; RSA moduli are always odd.
use crate::{Error, Result};
@@ -43,6 +45,46 @@ impl Big {
}
true
}
/// self · other, as many limbs as both together.
fn mul(&self, other: &Self) -> Self {
let mut out = vec![0u32; self.0.len() + other.0.len()];
for (i, &a) in self.0.iter().enumerate() {
let mut carry = 0u64;
for (j, &b) in other.0.iter().enumerate() {
let t = u64::from(out[i + j]) + u64::from(a) * u64::from(b) + carry;
out[i + j] = t as u32;
carry = t >> 32;
}
out[i + other.0.len()] = carry as u32;
}
Self(out)
}
/// self · m + a, one limb longer.
fn mul_small_add(&self, m: u32, a: u32) -> Self {
let mut out = Vec::with_capacity(self.0.len() + 1);
let mut carry = u64::from(a);
for &l in &self.0 {
let t = u64::from(l) * u64::from(m) + carry;
out.push(t as u32);
carry = t >> 32;
}
out.push(carry as u32);
Self(out)
}
/// (self / d, self mod d).
fn div_small(&self, d: u32) -> (Self, u32) {
let mut out = vec![0u32; self.0.len()];
let mut rem = 0u64;
for i in (0..self.0.len()).rev() {
let t = rem << 32 | u64::from(self.0[i]);
out[i] = (t / u64::from(d)) as u32;
rem = t % u64::from(d);
}
(Self(out), rem as u32)
}
fn is_one(&self) -> bool {
self.0.first() == Some(&1) && self.0[1..].iter().all(|&l| l == 0)
}
fn sub_assign(&mut self, other: &Self) {
let mut borrow = 0i64;
for (a, b) in self.0.iter_mut().zip(&other.0) {
@@ -249,6 +291,198 @@ impl RsaPublicKey {
}
}
/// Small odd primes for sieving prime candidates.
const SMALL_PRIMES: [u32; 53] = [
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
197, 199, 211, 223, 227, 229, 233, 239, 241, 251,
];
/// Miller-Rabin rounds: a composite passes all of them with odds below 2⁻⁸⁰.
const ROUNDS: usize = 40;
const E: u32 = 65537;
/// A random odd number of `limbs` limbs with its two top bits set, so two of
/// them multiply to exactly twice the bits.
fn candidate(limbs: usize) -> Result<Big> {
let mut bytes = vec![0u8; limbs * 4];
crate::crypto::random_bytes(&mut bytes)?;
bytes[0] |= 0xC0;
bytes[limbs * 4 - 1] |= 1;
Ok(Big::from_be_bytes(&bytes, limbs))
}
/// Miller-Rabin with random bases.
fn probably_prime(p: &Big) -> Result<bool> {
if SMALL_PRIMES.iter().any(|&q| p.div_small(q).1 == 0) {
return Ok(false);
}
let k = p.0.len();
let mont = Mont::new(p.clone());
let mut p_minus_one = p.clone();
p_minus_one.0[0] -= 1; // p is odd
let s = (0..k * 32).find(|&i| p_minus_one.bit(i)).unwrap_or(0);
// d = (p - 1) >> s
let mut d = Big(vec![0; k]);
for i in 0..k * 32 - s {
if p_minus_one.bit(i + s) {
d.0[i / 32] |= 1 << (i % 32);
}
}
let mut two = Big(vec![0; k]);
two.0[0] = 2;
'rounds: for _ in 0..ROUNDS {
// A random base in [2, p - 2].
let mut a = candidate(k)?;
a.0[k - 1] %= p.0[k - 1];
if !a.ge(&two) || a.ge(&p_minus_one) {
continue;
}
let mut x = mont.pow(&a, &d);
if x.is_one() || x == p_minus_one {
continue;
}
for _ in 1..s {
x = mont.pow(&x, &two);
if x == p_minus_one {
continue 'rounds;
}
if x.is_one() {
return Ok(false);
}
}
return Ok(false);
}
Ok(true)
}
/// A prime of `limbs` limbs whose p - 1 is prime to E.
fn prime(limbs: usize) -> Result<Big> {
loop {
let p = candidate(limbs)?;
if p.div_small(E).1 != 1 && probably_prime(&p)? {
return Ok(p);
}
}
}
/// DER: a tag and its length, then the contents.
fn der_element(tag: u8, contents: &[u8]) -> Vec<u8> {
let mut out = vec![tag];
let len = contents.len();
if len < 0x80 {
out.push(len as u8);
} else {
let bytes: Vec<u8> = len
.to_be_bytes()
.into_iter()
.skip_while(|&b| b == 0)
.collect();
out.push(0x80 | bytes.len() as u8);
out.extend(bytes);
}
out.extend_from_slice(contents);
out
}
/// A DER INTEGER from big-endian magnitude bytes (a leading zero keeps it positive).
fn der_integer(magnitude: &[u8]) -> Vec<u8> {
let mut v = strip(magnitude);
if v.first().is_none_or(|b| b & 0x80 != 0) {
v.insert(0, 0);
}
der_element(0x02, &v)
}
/// The server's key pair (Crypt.generateKeyPair).
pub struct RsaPrivateKey {
pub public: RsaPublicKey,
/// The private exponent, big-endian.
exponent: Vec<u8>,
}
impl std::fmt::Debug for RsaPrivateKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RsaPrivateKey")
.field("public", &self.public)
.finish_non_exhaustive()
}
}
impl RsaPrivateKey {
/// A new key pair with a `bits`-bit modulus (a multiple of 64) and
/// public exponent 65537, as Java's RSA KeyPairGenerator makes.
pub fn generate(bits: usize) -> Result<Self> {
let limbs = bits / 64;
let p = prime(limbs)?;
let q = loop {
let q = prime(limbs)?;
if q != p {
break q;
}
};
let n = p.mul(&q);
// d = (1 + k·φ) / E with k making it whole: k ≡ -φ⁻¹ (mod E).
let (mut p1, mut q1) = (p, q);
p1.0[0] -= 1;
q1.0[0] -= 1;
let phi = p1.mul(&q1);
let r = u64::from(phi.div_small(E).1);
let inverse = (1..u64::from(E))
.find(|k| k * r % u64::from(E) == 1)
.ok_or_else(|| Error::new("RSA key generation failed"))?;
let k = (u64::from(E) - inverse) as u32;
let (d, rem) = phi.mul_small_add(k, 1).div_small(E);
if rem != 0 {
return Err(Error::new("RSA key generation failed"));
}
let size = bits / 8;
Ok(Self {
public: RsaPublicKey {
modulus: strip(&n.to_be_bytes(size)),
exponent: strip(&E.to_be_bytes()),
},
exponent: d.to_be_bytes(size),
})
}
/// PublicKey.getEncoded: X.509 SubjectPublicKeyInfo.
pub fn public_der(&self) -> Vec<u8> {
let key = der_element(
0x30,
&[
der_integer(&self.public.modulus),
der_integer(&self.public.exponent),
]
.concat(),
);
let algorithm = der_element(
0x30,
&[der_element(0x06, RSA_ENCRYPTION), vec![0x05, 0x00]].concat(),
);
let bits = der_element(0x03, &[&[0u8][..], &key].concat());
der_element(0x30, &[algorithm, bits].concat())
}
/// Crypt.decryptUsingKey: RSAES-PKCS1-v1_5 decryption (RFC 8017 7.2.2).
pub fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>> {
let bad = || Error::new("Decryption error");
let k = self.public.size();
// The modulus has no leading zero, so equal lengths compare as numbers.
if ciphertext.len() != k || ciphertext >= self.public.modulus.as_slice() {
return Err(bad());
}
let block = self.public.apply(ciphertext, &self.exponent);
if block[0] != 0 || block[1] != 2 {
return Err(bad());
}
let zero = block[2..].iter().position(|&b| b == 0).ok_or_else(bad)? + 2;
if zero < 10 {
return Err(bad());
}
Ok(block[zero + 1..].to_vec())
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
@@ -316,6 +550,50 @@ pub(crate) mod tests {
assert!(key.encrypt(&[0; 118]).is_err());
}
/// A key made here: Java-style DER that parses back, and what its public
/// half encrypts its private half decrypts.
#[test]
fn generated_keys_round_trip() {
let key = RsaPrivateKey::generate(1024).unwrap();
assert_eq!(key.public.size(), 128);
assert_eq!(key.public.exponent, vec![1, 0, 1]);
let der = key.public_der();
assert_eq!(
&der[..3],
&[0x30, 0x81, 0x9f],
"a 1024-bit SubjectPublicKeyInfo"
);
assert_eq!(RsaPublicKey::from_der(&der).unwrap(), key.public);
for message in [&[0x5au8; 16][..], &[1, 2, 3, 4], &[]] {
let c = key.public.encrypt(message).unwrap();
assert_eq!(key.decrypt(&c).unwrap(), message);
}
assert!(key.decrypt(&[0u8; 128]).is_err());
assert!(key.decrypt(&[1u8; 64]).is_err());
}
#[test]
fn decrypts_with_a_known_key() {
let key = RsaPrivateKey {
public: RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(),
exponent: hex(TEST_D),
};
let c = key.public.encrypt(b"secret").unwrap();
assert_eq!(key.decrypt(&c).unwrap(), b"secret");
}
#[test]
fn finds_primes() {
let p = Big(vec![0xFFFF_FFFB]); // 2^32 - 5 is prime
assert!(probably_prime(&p).unwrap());
assert!(!probably_prime(&Big(vec![0xFFFF_FFFD])).unwrap()); // 3 · 1431655765
// 2^61 - 1 (prime) and a Carmichael-free composite 2^61 + 1.
let m61 = (1u64 << 61) - 1;
assert!(probably_prime(&Big(vec![m61 as u32, (m61 >> 32) as u32])).unwrap());
let c = (1u64 << 61) + 1;
assert!(!probably_prime(&Big(vec![c as u32, (c >> 32) as u32])).unwrap());
}
/// An OpenSSL signature checked with the public exponent: the block ends
/// with SHA-256("hello"), so the modular arithmetic agrees with OpenSSL's.
#[test]
+3 -1
View File
@@ -4,13 +4,15 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
rust-version = "1.90"
description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans"
description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans, and account lookups"
[dependencies]
horizon-core = { path = "../horizon-core" }
horizon-protocol = { path = "../horizon-protocol" }
horizon-world = { path = "../horizon-world" }
log = "0.4"
# Online mode: finding accounts by name (the services' profiles endpoint).
ureq = { version = "2", default-features = false, features = ["tls"] }
[lints]
workspace = true
+37
View File
@@ -78,6 +78,43 @@ impl Json {
}
}
/// `new GsonBuilder().create().toJson(element)`: compact, HTML-safe
/// strings, null members skipped.
pub fn gson(&self) -> String {
let mut out = String::new();
self.write_gson(&mut out);
out
}
fn write_gson(&self, out: &mut String) {
match self {
Json::String(s) => quote(out, s, true),
Json::Array(items) => {
out.push('[');
for (i, v) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
v.write_gson(out);
}
out.push(']');
}
Json::Object(m) => {
out.push('{');
let members = m.iter().filter(|(_, v)| *v != Json::Null);
for (i, (k, v)) in members.enumerate() {
if i > 0 {
out.push(',');
}
quote(out, k, true);
out.push(':');
v.write_gson(out);
}
out.push('}');
}
other => other.write_compact(out),
}
}
/// `new GsonBuilder().setPrettyPrinting().create().toJson(element, writer)`:
/// two-space indents, HTML-safe strings, null members skipped.
pub fn pretty(&self) -> String {
+6 -3
View File
@@ -1,10 +1,13 @@
//! The dedicated server's files and settings, ported from
//! net.minecraft.server.dedicated and net.minecraft.server.players:
//! server.properties, eula.txt and the four user lists. The game's dedicated
//! server (`horizon-client --dedicated`) reads them, and `horizon-server`
//! manages them; this crate needs neither a window nor the game.
//! server.properties, eula.txt, the four user lists, usercache.json and
//! looking players up by name. The game's dedicated server
//! (`horizon-client --dedicated`) reads them, and `horizon-server` manages
//! them; this crate needs neither a window nor the game.
pub mod eula;
pub mod java_properties;
pub mod json;
pub mod profiles;
pub mod properties;
pub mod user_cache;
pub mod user_lists;
+100
View File
@@ -0,0 +1,100 @@
//! Finding a player's account by name, as an online-mode server does for the
//! names given to `op`, `whitelist` and `ban` (CachedUserNameToIdResolver,
//! MinecraftServicesProfileRepository.findProfileByName): the services'
//! `profiles` / `getByName` endpoint, found through the discovery document.
use crate::{
json::{self, Json},
user_lists::NameAndId,
};
use std::time::Duration;
/// Mojang's services discovery document.
pub const DEFAULT_DISCOVERY: &str = "https://discovery.minecraftservices.com/minecraft/client";
/// The discovery document's URL: `HORIZON_API_DISCOVERY` overrides it like
/// authlib's `-Dminecraft.api.discovery.host`.
pub fn discovery_url() -> String {
std::env::var("HORIZON_API_DISCOVERY")
.ok()
.filter(|u| !u.is_empty())
.unwrap_or_else(|| DEFAULT_DISCOVERY.to_owned())
}
/// StringUtil.isValidPlayerName: at most 16 UTF-16 units, none a control
/// character, a space or above ASCII.
pub fn valid_player_name(name: &str) -> bool {
name.encode_utf16().count() <= 16 && name.encode_utf16().all(|c| c > 32 && c < 127)
}
/// How a server resolves a name it was given (CachedUserNameToIdResolver.get,
/// without the usercache.json cache): an offline server makes the offline
/// profile; an online one asks the services (for the name in lower case) and
/// knows nobody they don't.
pub fn resolve(name: &str, online: bool) -> Option<NameAndId> {
if online && valid_player_name(name) {
find_by_name(&discovery_url(), &name.to_ascii_lowercase())
} else {
(!online).then(|| NameAndId::offline(name))
}
}
/// MinecraftServicesProfileRepository.findProfileByName: the account named
/// `name` (any case), or None when there is none or the services don't
/// answer (vanilla logs both as "Couldn't find profile with name").
pub fn find_by_name(discovery: &str, name: &str) -> Option<NameAndId> {
let agent = ureq::AgentBuilder::new()
.timeout(Duration::from_secs(15))
.user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION")))
.build();
let doc = json::parse(&agent.get(discovery).call().ok()?.into_string().ok()?, true).ok()?;
let url = endpoint(&doc, "profiles", "getByName")?.replace("{name}", &name.to_lowercase());
found(&agent.get(&url).call().ok()?.into_string().ok()?, name)
}
/// MinecraftServicesDiscoveryService.getUrl(service, endpoint).
fn endpoint(doc: &Json, service: &str, name: &str) -> Option<String> {
doc.get("discovery")?
.get(service)?
.get("endpoints")?
.get(name)?
.get("uri")?
.as_string()
}
/// The answer, authlib's NameAndId: `{"id", "name"}`, the id undashed.
pub fn found(answer: &str, name: &str) -> Option<NameAndId> {
let profile = json::parse(answer, true).ok()?;
let found = profile.get("name")?.as_string()?;
let id = profile.get("id")?.as_string()?.replace('-', "");
(found.eq_ignore_ascii_case(name) && id.len() == 32).then_some(())?;
Some(NameAndId {
id: u128::from_str_radix(&id, 16).ok()?,
name: found,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_and_answers() {
assert!(valid_player_name("Alex_123"));
assert!(!valid_player_name("two words"));
assert!(!valid_player_name("ThisNameIsTooLong"));
assert!(!valid_player_name("caf\u{e9}"));
assert_eq!(resolve("Alex", false), Some(NameAndId::offline("Alex")));
assert_eq!(resolve("not valid", true), None);
let answer = r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch"}"#;
assert_eq!(
found(answer, "notch"),
Some(NameAndId {
id: 0x069a79f444e94726a5befca90e38aaf5,
name: "Notch".into()
})
);
assert_eq!(found(answer, "Steve"), None);
assert_eq!(found("{}", "Notch"), None);
assert_eq!(found("", "Notch"), None);
}
}
@@ -0,0 +1,318 @@
//! usercache.json (CachedUserNameToIdResolver): the players the server has
//! seen join or has looked up by name, so commands find a player by name
//! without asking the profile service again. Each entry expires a month after
//! it was added; the file keeps the 1000 most recently used.
use crate::{
java_properties::{civil_from_days, days_from_civil, now_millis},
json::{self, Json},
profiles::valid_player_name,
user_lists::{NameAndId, format_date, parse_date},
};
use std::{collections::HashMap, path::PathBuf};
const MRU_LIMIT: usize = 1000;
#[derive(Clone, Debug)]
struct Info {
user: NameAndId,
expires: i64,
last_access: u64,
}
/// `Calendar.add(MONTH, 1)` on a UTC time: the same day and time a month
/// later, the day clamped to the end of a shorter month.
pub fn one_month_later(millis: i64) -> i64 {
let days = millis.div_euclid(86_400_000);
let time = millis.rem_euclid(86_400_000);
let (y, m, d) = civil_from_days(days);
let (y, m) = if m == 12 { (y + 1, 1) } else { (y, m + 1) };
let last = days_from_civil(
if m == 12 { y + 1 } else { y },
if m == 12 { 1 } else { m + 1 },
1,
) - days_from_civil(y, m, 1);
let d = d.min(last as u32);
days_from_civil(y, m, d) * 86_400_000 + time
}
pub struct UserCache {
file: PathBuf,
/// Every entry ever added; the maps point into it, as vanilla's two maps
/// share their GameProfileInfo objects.
infos: Vec<Info>,
by_name: HashMap<String, usize>,
by_uuid: HashMap<u128, usize>,
operations: u64,
/// Off on an online-mode server: a name the profile service doesn't know
/// is then no player at all, rather than an offline one.
pub resolve_offline_users: bool,
}
impl UserCache {
/// The cache in `file`, loaded; also returns the warnings vanilla logs.
pub fn load(file: impl Into<PathBuf>) -> (Self, Vec<String>) {
let mut cache = Self {
file: file.into(),
infos: Vec::new(),
by_name: HashMap::new(),
by_uuid: HashMap::new(),
operations: 0,
resolve_offline_users: true,
};
let mut warnings = Vec::new();
let entries = match std::fs::read_to_string(&cache.file) {
Ok(text) => cache.parse(&text, &mut warnings),
Err(_) => Vec::new(),
};
for info in entries.into_iter().rev() {
cache.safe_add(info);
}
(cache, warnings)
}
fn parse(&self, text: &str, warnings: &mut Vec<String>) -> Vec<Info> {
let items = match json::parse(text, false) {
Ok(Json::Array(items)) => items,
// An empty file is Gson's null.
Ok(Json::Null) => return Vec::new(),
_ if text.trim().is_empty() => return Vec::new(),
_ => {
warnings.push(format!(
"Failed to load profile cache {}",
self.file.display()
));
return Vec::new();
}
};
let mut out = Vec::new();
for item in &items {
if !matches!(item, Json::Object(_)) {
continue;
}
let Some(user) = NameAndId::from_json(item) else {
continue;
};
let Some(date) = item.get("expiresOn").and_then(Json::as_string) else {
continue;
};
match parse_date(&date) {
Some(expires) => out.push(Info {
user,
expires,
last_access: 0,
}),
None => warnings.push(format!("Failed to parse date {date}")),
}
}
out
}
fn safe_add(&mut self, mut info: Info) -> usize {
self.operations += 1;
info.last_access = self.operations;
let index = self.infos.len();
self.by_name.insert(info.user.name.to_lowercase(), index);
self.by_uuid.insert(info.user.id, index);
self.infos.push(info);
index
}
/// `add`: a player who joined, remembered for a month; saves the file.
pub fn add(&mut self, user: NameAndId) {
self.add_internal(user, now_millis());
}
fn add_internal(&mut self, user: NameAndId, now: i64) -> NameAndId {
let index = self.safe_add(Info {
user,
expires: one_month_later(now),
last_access: 0,
});
self.save();
self.infos[index].user.clone()
}
/// `get(String)`: the player with this name (any case). An expired entry is
/// dropped; a name not cached is asked of `lookup` (the profile service,
/// given the lower-case name) and, failing that, made an offline player
/// when offline users resolve. What is found is cached.
pub fn get_by_name(
&mut self,
name: &str,
lookup: impl FnOnce(&str) -> Option<NameAndId>,
) -> Option<NameAndId> {
self.get_by_name_at(name, now_millis(), lookup)
}
fn get_by_name_at(
&mut self,
name: &str,
now: i64,
lookup: impl FnOnce(&str) -> Option<NameAndId>,
) -> Option<NameAndId> {
let name = name.to_lowercase();
let mut found = self.by_name.get(&name).copied();
let mut needs_save = false;
if let Some(index) = found
&& now >= self.infos[index].expires
{
let user = self.infos[index].user.clone();
self.by_uuid.remove(&user.id);
self.by_name.remove(&user.name.to_lowercase());
needs_save = true;
found = None;
}
let result = if let Some(index) = found {
self.operations += 1;
self.infos[index].last_access = self.operations;
Some(self.infos[index].user.clone())
} else {
let profile = if valid_player_name(&name) {
lookup(&name)
} else {
None
};
let profile = profile.or_else(|| {
self.resolve_offline_users
.then(|| NameAndId::offline(&name))
});
match profile {
Some(profile) => {
needs_save = false;
Some(self.add_internal(profile, now))
}
None => None,
}
};
if needs_save {
self.save();
}
result
}
/// `get(UUID)`: a cached player by id (expired or not).
pub fn get_by_id(&mut self, id: u128) -> Option<NameAndId> {
let index = *self.by_uuid.get(&id)?;
self.operations += 1;
self.infos[index].last_access = self.operations;
Some(self.infos[index].user.clone())
}
/// The file's text: the 1000 most recently used entries, most recent
/// first, as Gson writes them (compact, HTML-safe).
pub fn to_json(&self) -> String {
let mut entries: Vec<&Info> = self.by_uuid.values().map(|&i| &self.infos[i]).collect();
entries.sort_by_key(|info| std::cmp::Reverse(info.last_access));
let items = entries
.into_iter()
.take(MRU_LIMIT)
.map(|info| {
let mut o = Json::Object(Vec::new());
info.user.append_to(&mut o);
o.add("expiresOn", Json::String(format_date(info.expires)));
o
})
.collect();
Json::Array(items).gson()
}
/// `save`: errors are ignored, as vanilla does.
pub fn save(&self) {
let _ = std::fs::write(&self.file, self.to_json());
}
}
#[cfg(test)]
mod tests {
use super::*;
const DAY: i64 = 86_400_000;
fn cache(text: &str) -> (UserCache, Vec<String>) {
let dir = std::env::temp_dir().join(format!(
"horizon-usercache-{}-{}",
std::process::id(),
text.len()
));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("usercache.json");
std::fs::write(&file, text).unwrap();
UserCache::load(file)
}
#[test]
fn months() {
let jan31 = days_from_civil(2026, 1, 31) * DAY + 3_723_000;
assert_eq!(
format_date(one_month_later(jan31)),
"2026-02-28 01:02:03 +0000"
);
let dec15 = days_from_civil(2026, 12, 15) * DAY;
assert_eq!(
format_date(one_month_later(dec15)),
"2027-01-15 00:00:00 +0000"
);
let jan31_leap = days_from_civil(2028, 1, 31) * DAY;
assert_eq!(
format_date(one_month_later(jan31_leap)),
"2028-02-29 00:00:00 +0000"
);
}
#[test]
fn keeps_order_and_skips_bad_entries() {
let (c, warnings) = cache(
r#"[{"uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","name":"Notch","expiresOn":"2099-01-01 00:00:00 +0000"},
1, {"name":"NoId"}, {"uuid":"853c80ef-3c37-49fd-aa49-938b674adae6","name":"NoDate"},
{"uuid":"853c80ef-3c37-49fd-aa49-938b674adae6","name":"BadDate","expiresOn":"soon"},
{"uuid":"61699b2e-d327-4a01-9f1e-0ea8c3f06bc6","name":"Alex","expiresOn":"2099-01-01 00:00:00 +0000"}]"#,
);
assert_eq!(warnings, vec!["Failed to parse date soon".to_owned()]);
assert_eq!(
c.to_json(),
r#"[{"uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","name":"Notch","expiresOn":"2099-01-01 00:00:00 +0000"},{"uuid":"61699b2e-d327-4a01-9f1e-0ea8c3f06bc6","name":"Alex","expiresOn":"2099-01-01 00:00:00 +0000"}]"#
);
}
#[test]
fn names_resolve_through_the_cache() {
let (mut c, _) = cache(
r#"[{"uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","name":"Notch","expiresOn":"2099-01-01 00:00:00 +0000"},
{"uuid":"61699b2e-d327-4a01-9f1e-0ea8c3f06bc6","name":"Old","expiresOn":"2000-01-01 00:00:00 +0000"}]"#,
);
let now = days_from_civil(2026, 10, 17) * DAY;
let never = |_: &str| -> Option<NameAndId> { panic!("looked up") };
// A hit in any case, and it becomes the most recent.
let notch = c.get_by_name_at("NOTCH", now, never).unwrap();
assert_eq!(notch.name, "Notch");
// Expired: dropped and looked up again, by its lower-case name.
let mut asked = Vec::new();
let old = c
.get_by_name_at("Old", now, |n| {
asked.push(n.to_owned());
None
})
.unwrap();
assert_eq!(asked, ["old"]);
assert_eq!(old, NameAndId::offline("old"));
// Not a valid name: never looked up.
let odd = c.get_by_name_at("a b", now, never).unwrap();
assert_eq!(odd, NameAndId::offline("a b"));
c.resolve_offline_users = false;
assert_eq!(c.get_by_name_at("Nobody", now, |_| None), None);
let found = NameAndId {
id: 7,
name: "Steve".into(),
};
let steve = c.get_by_name_at("steve", now, |_| Some(found.clone()));
assert_eq!(steve, Some(found));
let json = c.to_json();
let names: Vec<&str> = json
.split("\"name\":\"")
.skip(1)
.map(|s| s.split('"').next().unwrap())
.collect();
assert_eq!(names, ["Steve", "a b", "old", "Notch"]);
assert!(json.contains(r#""name":"Steve","expiresOn":"2026-11-17 00:00:00 +0000"}"#));
}
}
@@ -39,7 +39,7 @@ impl NameAndId {
name: name.to_owned(),
}
}
fn from_json(o: &Json) -> Option<Self> {
pub(crate) fn from_json(o: &Json) -> Option<Self> {
let uuid = o.get("uuid")?.as_string()?;
let name = o.get("name")?.as_string()?;
Some(Self {
@@ -47,7 +47,7 @@ impl NameAndId {
name,
})
}
fn append_to(&self, o: &mut Json) {
pub(crate) fn append_to(&self, o: &mut Json) {
o.add("uuid", Json::String(uuid_string(self.id)));
o.add("name", Json::String(self.name.clone()));
}
+1 -1
View File
@@ -23,7 +23,7 @@ motd = "A Minecraft Server"
port = 25565
bind = "" # listen on every address, or only on this one (server-ip)
max_players = 20
online_mode = true # not supported by Horizon yet: the server runs offline and says so
online_mode = true # check players' Minecraft accounts (false: anyone joins under any name)
whitelist = true # only whitelisted players and operators can join
enforce_whitelist = false # kick online players taken off the whitelist
view_distance = 10
+25 -11
View File
@@ -6,7 +6,7 @@ use crate::{config, config::Config, engine};
use horizon_server_files::{
eula,
java_properties::now_millis,
user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList},
user_lists::{OpEntry, OpList, WhiteEntry, WhiteList},
};
use std::{
io::{BufRead, IsTerminal, Write},
@@ -23,6 +23,8 @@ pub struct Answers {
pub whitelist: Option<bool>,
pub players: Vec<String>,
pub op: Option<String>,
/// online-mode (true unless set): players' Minecraft accounts are checked.
pub online: Option<bool>,
/// Take the default for every question not answered by a flag.
pub yes: bool,
}
@@ -30,7 +32,7 @@ pub struct Answers {
impl Answers {
/// The answers in the environment, for containers: `HORIZON_EULA=true`, `HORIZON_WORLD`,
/// `HORIZON_SEED`, `HORIZON_PORT`, `HORIZON_WHITELIST=true|false`, `HORIZON_PLAYERS` (names separated by
/// commas) and `HORIZON_OP`. Flags given on the command line win.
/// commas), `HORIZON_OP` and `HORIZON_ONLINE=true|false`. Flags given on the command line win.
pub fn from_env() -> Result<Self, String> {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
let flag = |name: &str| var(name).map(|v| v.eq_ignore_ascii_case("true"));
@@ -54,6 +56,7 @@ impl Answers {
})
.unwrap_or_default(),
op: var("HORIZON_OP"),
online: flag("HORIZON_ONLINE"),
yes: false,
})
}
@@ -172,6 +175,9 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> {
}
// 4. Who may join.
if let Some(online) = answers.online {
cfg.server.online_mode = online;
}
cfg.server.whitelist = answers.whitelist.unwrap_or_else(|| {
prompt.yes(
"Only let in players you list (whitelist)?",
@@ -193,7 +199,7 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> {
.yes(&format!("Make {first} an operator?"), true)
.then(|| first.clone())
});
add_players(dir, &players, op.as_deref())?;
add_players(dir, &players, op.as_deref(), cfg.server.online_mode)?;
// 5. The game and its files.
match engine::program(&cfg, dir) {
@@ -213,24 +219,29 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> {
toml_path.display(),
dir.display()
);
if cfg.server.online_mode {
if !cfg.server.online_mode {
println!(
"Note: Horizon's server doesn't check Mojang accounts yet (online mode), so it runs offline: \
keep the whitelist on, or play on a LAN or a tailnet."
"Note: online mode is off, so anyone can join under any name: keep the whitelist on, or play on a \
LAN or a tailnet."
);
}
Ok(())
}
/// Adds players to the whitelist (and one as an operator) in vanilla's files, with offline UUIDs as the
/// server runs offline.
fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), String> {
/// Adds players to the whitelist (and one as an operator) in vanilla's files, with the profiles the server
/// will see: offline ones, or in online mode their accounts.
fn add_players(
dir: &Path,
players: &[String],
op: Option<&str>,
online: bool,
) -> Result<(), String> {
if !players.is_empty() {
let mut white = WhiteList::new(dir.join("whitelist.json"));
let _ = white.load();
for name in players {
white.add(WhiteEntry {
user: NameAndId::offline(name),
user: crate::lists::account(name, online)?,
});
}
println!("Whitelisted: {}", players.join(", "));
@@ -239,7 +250,7 @@ fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), S
let mut ops = OpList::new(dir.join("ops.json"));
let _ = ops.load();
ops.add(OpEntry {
user: NameAndId::offline(name),
user: crate::lists::account(name, online)?,
level: 4,
bypasses_player_limit: false,
});
@@ -264,6 +275,8 @@ mod tests {
whitelist: Some(true),
players: vec!["Alex".into(), "Steve".into()],
op: Some("Alex".into()),
// Offline: no account lookups in a test.
online: Some(false),
yes: true,
};
run(&dir, answers).unwrap();
@@ -277,6 +290,7 @@ mod tests {
("survival", "12345", 25599)
);
assert!(eula::agreed(&dir.join("eula.txt")).unwrap());
assert!(!cfg.server.online_mode);
let white = std::fs::read_to_string(dir.join("whitelist.json")).unwrap();
assert!(
white.contains("\"Alex\"") && white.contains("\"Steve\""),
+23 -4
View File
@@ -20,7 +20,7 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> {
let message = match (command, args.as_slice()) {
("op", [name]) => {
let mut ops = load(OpList::new(ops_path))?;
let user = NameAndId::offline(name);
let user = account(name, config.server.online_mode)?;
if ops.contains(&user) {
"Nothing changed. The player already is an operator".to_owned()
} else {
@@ -34,7 +34,8 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> {
}
("deop", [name]) => {
let mut ops = load(OpList::new(ops_path))?;
if ops.remove(&NameAndId::offline(name)) {
let user = listed(ops.entries().iter().map(|e| &e.user), name);
if user.is_some_and(|user| ops.remove(&user)) {
format!("Made {name} no longer a server operator")
} else {
"Nothing changed. The player is not an operator".to_owned()
@@ -42,7 +43,7 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> {
}
("whitelist", ["add", name]) => {
let mut white = load(WhiteList::new(white_path))?;
let user = NameAndId::offline(name);
let user = account(name, config.server.online_mode)?;
if white.contains(&user) {
"Player is already whitelisted".to_owned()
} else {
@@ -52,7 +53,8 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> {
}
("whitelist", ["remove", name]) => {
let mut white = load(WhiteList::new(white_path))?;
if white.remove(&NameAndId::offline(name)) {
let user = listed(white.entries().iter().map(|e| &e.user), name);
if user.is_some_and(|user| white.remove(&user)) {
format!("Removed {name} from the whitelist")
} else {
"Player is not whitelisted".to_owned()
@@ -97,6 +99,23 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> {
Ok(())
}
/// The profile a running server would store for `name`: the offline one, or in online mode the account the
/// services know by that name.
pub fn account(name: &str, online: bool) -> Result<NameAndId, String> {
horizon_server_files::profiles::resolve(name, online).ok_or_else(|| {
if online {
format!("That player does not exist (no Minecraft account is named {name}, or the services didn't answer)")
} else {
"That player does not exist".to_owned()
}
})
}
/// The entry already on a list under `name` (any case), so removing needs no lookup.
fn listed<'a>(mut users: impl Iterator<Item = &'a NameAndId>, name: &str) -> Option<NameAndId> {
users.find(|u| u.name.eq_ignore_ascii_case(name)).cloned()
}
/// A list from its file; a missing file is an empty list, a broken one an error (vanilla would replace it).
fn load<E: horizon_server_files::user_lists::Entry>(
mut list: horizon_server_files::user_lists::UserList<E>,
+2 -1
View File
@@ -23,7 +23,7 @@ Usage: horizon-server [--dir DIR] <command>
init Set up a server here: the EULA, the world, the port, who may join (asks, or takes flags:
--eula --world NAME --seed SEED --port N --whitelist/--no-whitelist --player NAME... --op NAME
--yes)
--offline --yes)
run Run the server in the foreground; type console commands, Ctrl-C stops it cleanly. It
restarts the game if it crashes.
start Run the server in the background (its output goes to logs/supervisor.log)
@@ -150,6 +150,7 @@ fn init_answers(args: &[String]) -> Result<init::Answers, String> {
"--no-whitelist" => answers.whitelist = Some(false),
"--player" => answers.players.push(value(arg)?),
"--op" => answers.op = Some(value(arg)?),
"--offline" => answers.online = Some(false),
other => return Err(format!("init: unknown option {other}")),
}
}
+3
View File
@@ -9,6 +9,9 @@ description = "Horizon vanilla world data, NBT, regions and chunk storage"
[dependencies]
libm = "=0.2.16"
serde_json = { version = "1.0.151", features = ["raw_value"] }
serde = { version = "1", features = ["derive"] }
sha2 = "0.10"
postcard = { version = "=1.1.3", default-features = false, features = ["alloc"] }
horizon-core = { path = "../horizon-core" }
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
lz4_flex = { version = "0.14", default-features = false, features = ["std", "safe-encode", "safe-decode", "checked-decode"] }
@@ -0,0 +1,32 @@
//! Measure registry and behaviour load times using prepared client resources.
//! `behaviour_load_profile RESOURCES [CACHE_DIR]`: with CACHE_DIR, loads use and
//! refresh the snapshot there, as the client does with its `.horizon-cache`.
use horizon_world::level::{Behaviours, data::load_registry};
use std::{path::Path, time::Instant};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let root = std::env::args()
.nth(1)
.expect("resource directory argument");
let root = Path::new(&root);
if let Some(dir) = std::env::args().nth(2) {
Behaviours::set_cache_dir(dir.into());
}
let started = Instant::now();
let registry = load_registry(root)?;
eprintln!(
"registry_ms={:.3}",
started.elapsed().as_secs_f64() * 1000.0
);
for iteration in 0..3 {
let started = Instant::now();
let behaviours = Behaviours::load(&registry, root)?;
eprintln!(
"behaviours_{}_ms={:.3}",
iteration,
started.elapsed().as_secs_f64() * 1000.0
);
std::hint::black_box(behaviours);
}
Ok(())
}
+52 -7
View File
@@ -21,6 +21,9 @@ use std::{
path::Path,
sync::Arc,
};
#[path = "data/cache.rs"]
mod cache;
pub(super) use cache::set_dir as set_cache_dir;
/// Per-state flags read from vanilla accessors over an empty level.
pub mod state_flags {
@@ -251,7 +254,7 @@ macro_rules! named_blocks {
#[derive(Clone, Copy, Debug)]
pub struct Named { $(pub $field: BlockId,)* }
impl Named {
fn resolve(table: &StateTable) -> io::Result<Self> {
pub(super) fn resolve(table: &StateTable) -> io::Result<Self> {
Ok(Self { $($field: table.block_by_name(concat!("minecraft:", $name)).ok_or_else(|| invalid(concat!("missing block ", $name)))?,)* })
}
}
@@ -393,7 +396,7 @@ macro_rules! tags {
#[derive(Clone, Debug, Default)]
pub struct Tags { $(pub $field: Arc<BlockSet>,)* }
impl Tags {
fn resolve(all: &HashMap<String, Arc<BlockSet>>) -> Self {
pub(super) fn resolve(all: &HashMap<String, Arc<BlockSet>>) -> Self {
Self { $($field: all.get(concat!("minecraft:", $name)).cloned().unwrap_or_default(),)* }
}
}
@@ -487,7 +490,7 @@ macro_rules! props {
#[derive(Clone, Copy, Debug)]
pub struct Props { $(pub $field: PropKey,)* }
impl Props {
fn resolve(table: &mut StateTable) -> Self {
pub(super) fn resolve(table: &mut StateTable) -> Self {
Self { $($field: table.key($name),)* }
}
}
@@ -653,23 +656,65 @@ pub fn load_registry(root: &Path) -> io::Result<BlockRegistry> {
}
pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours> {
let behaviour = read_json(&root.join("block-behaviours.json"))?;
load_with_behaviour_json(registry, root, &behaviour)
cached(registry, root, || load_uncached(registry, root))
}
/// [`load`] with `block-behaviours.json` already parsed by the caller.
pub(super) fn load_with_behaviour_json(
registry: &BlockRegistry,
root: &Path,
behaviour: &Value,
) -> io::Result<Behaviours> {
cached(registry, root, || {
build_with_behaviour_json(registry, root, behaviour)
})
}
/// [`load`] with the client's typed gameplay projection. The snapshot is
/// still tried first: on a hit the projection is not needed.
pub(super) fn load_with_gameplay<G: GameplayStateSource>(
registry: &BlockRegistry,
root: &Path,
behaviour: &Value,
gameplay_states: &[G],
) -> io::Result<Behaviours> {
cached(registry, root, || {
build_with_gameplay(registry, root, behaviour, gameplay_states)
})
}
/// The snapshot when it matches, else `build` and refresh the snapshot.
fn cached(
registry: &BlockRegistry,
root: &Path,
build: impl FnOnce() -> io::Result<Behaviours>,
) -> io::Result<Behaviours> {
if let Some(behaviours) = cache::load(registry, root) {
return Ok(behaviours);
}
let behaviours = build()?;
cache::store(registry, root, &behaviours);
Ok(behaviours)
}
fn load_uncached(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours> {
let behaviour = read_json(&root.join("block-behaviours.json"))?;
build_with_behaviour_json(registry, root, &behaviour)
}
fn build_with_behaviour_json(
registry: &BlockRegistry,
root: &Path,
behaviour: &Value,
) -> io::Result<Behaviours> {
let gameplay = read_json(&root.join("gameplay-facts.json"))?;
let gameplay_states = gameplay["states"]
.as_array()
.ok_or_else(|| fail("missing gameplay states"))?;
load_with_gameplay(registry, root, behaviour, gameplay_states)
build_with_gameplay(registry, root, behaviour, gameplay_states)
}
pub(super) fn load_with_gameplay<G: GameplayStateSource>(
fn build_with_gameplay<G: GameplayStateSource>(
registry: &BlockRegistry,
root: &Path,
behaviour: &Value,
@@ -0,0 +1,867 @@
//! A disposable, versioned snapshot of resolved behaviour tables.
//!
//! The source resources remain authoritative. Failed reads, unsupported
//! versions, corrupt payloads and write failures always use the normal loader.
//! The snapshot lives in the game's own cache folder ([`set_dir`]), never in the
//! resource folder: that one is shared by worktrees and copied between installed
//! versions by the launcher. Its key includes the running executable, so a build
//! that resolves the tables differently never reads another build's snapshot.
use super::*;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
io::Write,
path::PathBuf,
sync::{
OnceLock,
atomic::{AtomicU64, Ordering},
},
time::UNIX_EPOCH,
};
const MAGIC: &[u8; 8] = b"HZBEHAV\0";
const VERSION: u32 = 2;
const FILE_NAME: &str = "behaviours-v2.bin";
const MAX_FILE_BYTES: usize = 128 * 1024 * 1024;
const MAX_DECODED_BYTES: usize = 256 * 1024 * 1024;
static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
static DIR: OnceLock<PathBuf> = OnceLock::new();
/// Keep snapshots in `dir` (the client passes `<game folder>/.horizon-cache`).
/// Without it (tests, tools, servers), `Behaviours::load` always uses the source loader.
pub(in crate::level) fn set_dir(dir: PathBuf) {
let _ = DIR.set(dir);
}
#[derive(Serialize, Deserialize)]
struct Snapshot {
tags: HashMap<String, Vec<u64>>,
facts: Vec<Fact>,
shapes: Vec<Shape>,
shape_info: Vec<[u8; 3]>,
fluid_tags: [u8; 6],
blocks: Vec<Block>,
items: HashMap<String, Item>,
}
#[derive(Serialize, Deserialize)]
struct Fact {
flags: u32,
sturdy: u32,
weak: u32,
strong: u32,
fluid_kind: u8,
fluid_amount: u8,
fluid_falling: bool,
emission: u8,
dampening: u8,
hardness: f32,
push: u8,
instrument: u8,
shape: i32,
}
#[derive(Serialize, Deserialize)]
struct Shape {
coords: [Vec<f64>; 3],
occupied: Vec<bool>,
cube: bool,
coordinate_cubes: [bool; 3],
min: [i32; 3],
max: [i32; 3],
/// Preserve the shared singleton identities used by vanilla shape shortcuts.
singleton: u8,
}
#[derive(Serialize, Deserialize)]
struct SetTypeSnapshot {
name: String,
can_open_by_hand: bool,
can_open_by_wind_charge: bool,
arrows: bool,
mobs_only: bool,
door_open: String,
door_close: String,
trapdoor_open: String,
trapdoor_close: String,
plate_on: String,
plate_off: String,
button_on: String,
button_off: String,
}
#[derive(Serialize, Deserialize)]
struct SoundsSnapshot {
volume: f32,
pitch: f32,
place: String,
break_: String,
fall: String,
}
#[derive(Serialize, Deserialize)]
struct Block {
chain: Vec<u16>,
interfaces: u16,
set_type: Option<SetTypeSnapshot>,
gate_open: Option<String>,
gate_close: Option<String>,
open_sound: Option<String>,
close_sound: Option<String>,
ticks_to_stay_pressed: i32,
max_weight: i32,
link: Option<u16>,
link2: Option<u16>,
support_tag: Option<Vec<u64>>,
support_tag2: Option<Vec<u64>>,
feature: Option<String>,
grow_probability: f64,
growth_direction: u8,
schedule_fluid_ticks: bool,
weather: u8,
ignite_odds: i32,
burn_odds: i32,
sounds: SoundsSnapshot,
item: String,
dynamic_shape: bool,
}
#[derive(Serialize, Deserialize)]
struct Item {
block: u16,
wall_block: Option<u16>,
attachment: Option<u8>,
kind: u8,
game_master: bool,
}
fn fingerprint(registry: &BlockRegistry, root: &Path) -> io::Result<[u8; 32]> {
let mut hasher = Sha256::new();
hasher.update(b"horizon resolved behaviours 2");
// The build that resolved the tables: the version constant alone misses
// loader changes that keep the snapshot layout.
let exe = std::env::current_exe()?;
let built = fs::metadata(&exe)?;
hash_str(&mut hasher, &exe.to_string_lossy());
hasher.update(built.len().to_le_bytes());
let modified = built
.modified()?
.duration_since(UNIX_EPOCH)
.map_err(|e| invalid(e.to_string()))?;
hasher.update(modified.as_nanos().to_le_bytes());
for relative in [
"facts.json",
"block-behaviours.json",
"gameplay-facts.json",
"block-tags.json",
"cached-collision.nbt",
] {
hash_file(&mut hasher, root, &root.join(relative))?;
}
let mut fluids: Vec<PathBuf> = fs::read_dir(root.join("data/minecraft/tags/fluid"))?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<io::Result<_>>()?;
fluids.sort();
for path in fluids {
hash_file(&mut hasher, root, &path)?;
}
// The registry argument may be modified independently of facts.json.
hasher.update((registry.len() as u64).to_le_bytes());
let mut seen = std::collections::HashSet::new();
for index in 0..registry.len() {
let state = registry
.state(BlockStateId(index as u32))
.ok_or_else(|| invalid("missing registry state"))?;
hash_str(&mut hasher, &state.name);
let mut props: Vec<_> = state.properties.iter().collect();
props.sort_by_key(|(key, _)| *key);
hasher.update((props.len() as u32).to_le_bytes());
for (key, value) in props {
hash_str(&mut hasher, key);
hash_str(&mut hasher, value);
}
if seen.insert(state.name.as_str()) {
let default = registry
.default_state(&state.name)
.ok_or_else(|| invalid("missing default state"))?;
hasher.update(default.0.to_le_bytes());
}
}
Ok(hasher.finalize().into())
}
fn hash_str(hasher: &mut Sha256, text: &str) {
hasher.update((text.len() as u64).to_le_bytes());
hasher.update(text.as_bytes());
}
fn hash_file(hasher: &mut Sha256, root: &Path, path: &Path) -> io::Result<()> {
let relative = path
.strip_prefix(root)
.map_err(|e| invalid(e.to_string()))?;
hash_str(hasher, &relative.to_string_lossy());
let bytes = fs::read(path)?;
hasher.update((bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
Ok(())
}
fn direction(index: u8) -> io::Result<Direction> {
Direction::ALL
.get(index as usize)
.copied()
.ok_or_else(|| invalid("cached direction out of range"))
}
fn direction_index(direction: Direction) -> u8 {
Direction::ALL.iter().position(|d| *d == direction).unwrap() as u8
}
fn class(index: u16) -> io::Result<Class> {
Class::ALL
.get(index as usize)
.copied()
.ok_or_else(|| invalid("cached block class out of range"))
}
fn kind(index: u8) -> io::Result<ItemKind> {
Ok(match index {
0 => ItemKind::Block,
1 => ItemKind::DoubleHigh,
2 => ItemKind::StandingAndWall,
3 => ItemKind::Scaffolding,
4 => ItemKind::PlaceOnWater,
5 => ItemKind::HangingSign,
6 => ItemKind::SolidBucket,
7 => ItemKind::Other,
_ => return Err(invalid("cached item kind out of range")),
})
}
fn kind_index(kind: ItemKind) -> u8 {
match kind {
ItemKind::Block => 0,
ItemKind::DoubleHigh => 1,
ItemKind::StandingAndWall => 2,
ItemKind::Scaffolding => 3,
ItemKind::PlaceOnWater => 4,
ItemKind::HangingSign => 5,
ItemKind::SolidBucket => 6,
ItemKind::Other => 7,
}
}
fn push(index: u8) -> io::Result<PushReaction> {
Ok(match index {
0 => PushReaction::PushPull,
1 => PushReaction::Push,
2 => PushReaction::Popped,
3 => PushReaction::Immoveable,
4 => PushReaction::IgnoreEntity,
_ => return Err(invalid("cached push reaction out of range")),
})
}
fn push_index(push: PushReaction) -> u8 {
match push {
PushReaction::PushPull => 0,
PushReaction::Push => 1,
PushReaction::Popped => 2,
PushReaction::Immoveable => 3,
PushReaction::IgnoreEntity => 4,
}
}
impl From<&SetType> for SetTypeSnapshot {
fn from(value: &SetType) -> Self {
Self {
name: value.name.to_string(),
can_open_by_hand: value.can_open_by_hand,
can_open_by_wind_charge: value.can_open_by_wind_charge,
arrows: value.arrows,
mobs_only: value.mobs_only,
door_open: value.door_open.to_string(),
door_close: value.door_close.to_string(),
trapdoor_open: value.trapdoor_open.to_string(),
trapdoor_close: value.trapdoor_close.to_string(),
plate_on: value.plate_on.to_string(),
plate_off: value.plate_off.to_string(),
button_on: value.button_on.to_string(),
button_off: value.button_off.to_string(),
}
}
}
impl From<SetTypeSnapshot> for SetType {
fn from(value: SetTypeSnapshot) -> Self {
Self {
name: value.name.into(),
can_open_by_hand: value.can_open_by_hand,
can_open_by_wind_charge: value.can_open_by_wind_charge,
arrows: value.arrows,
mobs_only: value.mobs_only,
door_open: Arc::from(value.door_open),
door_close: Arc::from(value.door_close),
trapdoor_open: Arc::from(value.trapdoor_open),
trapdoor_close: Arc::from(value.trapdoor_close),
plate_on: Arc::from(value.plate_on),
plate_off: Arc::from(value.plate_off),
button_on: Arc::from(value.button_on),
button_off: Arc::from(value.button_off),
}
}
}
impl From<&Sounds> for SoundsSnapshot {
fn from(value: &Sounds) -> Self {
Self {
volume: value.volume,
pitch: value.pitch,
place: value.place.to_string(),
break_: value.break_.to_string(),
fall: value.fall.to_string(),
}
}
}
impl From<SoundsSnapshot> for Sounds {
fn from(value: SoundsSnapshot) -> Self {
Self {
volume: value.volume,
pitch: value.pitch,
place: Arc::from(value.place),
break_: Arc::from(value.break_),
fall: Arc::from(value.fall),
}
}
}
impl Snapshot {
fn capture(behaviours: &Behaviours) -> Self {
let tags = behaviours
.all_tags
.iter()
.map(|(key, value)| (key.clone(), value.0.clone()))
.collect();
let facts = behaviours
.facts
.iter()
.map(|fact| Fact {
flags: fact.flags,
sturdy: fact.sturdy,
weak: fact.weak,
strong: fact.strong,
fluid_kind: fact.fluid.kind() as u8,
fluid_amount: fact.fluid.amount(),
fluid_falling: fact.fluid.falling(),
emission: fact.emission,
dampening: fact.dampening,
hardness: fact.hardness,
push: push_index(fact.push),
instrument: fact.instrument,
shape: fact.shape,
})
.collect();
let shapes = behaviours
.shapes
.iter()
.map(|shape| {
let sizes = shape.sizes();
let mut occupied = Vec::with_capacity(sizes.iter().product());
for x in 0..sizes[0] {
for y in 0..sizes[1] {
for z in 0..sizes[2] {
occupied.push(shape.is_full(x as i32, y as i32, z as i32));
}
}
}
let (min, max) = shape.discrete_bounds();
Shape {
coords: std::array::from_fn(|axis| {
shape
.coordinates(
[
horizon_core::geometry::Axis::X,
horizon_core::geometry::Axis::Y,
horizon_core::geometry::Axis::Z,
][axis],
)
.to_vec()
}),
occupied,
cube: shape.is_cube(),
coordinate_cubes: shape.cube_coordinate_axes(),
min,
max,
singleton: if shape.same_identity(&VoxelShape::block()) {
1
} else if shape.same_identity(&VoxelShape::empty()) {
2
} else {
0
},
}
})
.collect();
let shape_info = behaviours
.shape_info
.iter()
.map(|info| [info.full_faces, info.nonempty_faces, info.wall_cover])
.collect();
let f = behaviours.fluid_tags;
let fluid_tags = [
f.water,
f.lava,
f.supports_frogspawn,
f.supports_lily_pad,
f.supports_sugar_cane_adjacently,
f.bubble_column_can_occupy,
];
let blocks = behaviours
.blocks
.iter()
.map(|block| Block {
chain: block.chain.iter().map(|class| *class as u16).collect(),
interfaces: block.interfaces,
set_type: block
.set_type
.as_ref()
.map(|value| SetTypeSnapshot::from(value.as_ref())),
gate_open: block.gate_open.as_ref().map(|v| v.to_string()),
gate_close: block.gate_close.as_ref().map(|v| v.to_string()),
open_sound: block.open_sound.as_ref().map(|v| v.to_string()),
close_sound: block.close_sound.as_ref().map(|v| v.to_string()),
ticks_to_stay_pressed: block.ticks_to_stay_pressed,
max_weight: block.max_weight,
link: block.link.map(|v| v.0),
link2: block.link2.map(|v| v.0),
support_tag: block.support_tag.as_ref().map(|v| v.0.clone()),
support_tag2: block.support_tag2.as_ref().map(|v| v.0.clone()),
feature: block.feature.as_ref().map(|v| v.to_string()),
grow_probability: block.grow_probability,
growth_direction: direction_index(block.growth_direction),
schedule_fluid_ticks: block.schedule_fluid_ticks,
weather: block.weather,
ignite_odds: block.ignite_odds,
burn_odds: block.burn_odds,
sounds: SoundsSnapshot::from(block.sounds.as_ref()),
item: block.item.to_string(),
dynamic_shape: block.dynamic_shape,
})
.collect();
let items = behaviours
.items
.iter()
.map(|(name, item)| {
(
name.clone(),
Item {
block: item.block.0,
wall_block: item.wall_block.map(|v| v.0),
attachment: item.attachment.map(direction_index),
kind: kind_index(item.kind),
game_master: item.game_master,
},
)
})
.collect();
Self {
tags,
facts,
shapes,
shape_info,
fluid_tags,
blocks,
items,
}
}
fn restore(self, registry: &BlockRegistry) -> io::Result<Behaviours> {
let mut table = StateTable::new(registry)?;
let props = Props::resolve(&mut table);
let named = Named::resolve(&table)?;
if self.facts.len() != table.state_count()
|| self.blocks.len() != table.block_count()
|| self.shape_info.len() != self.shapes.len()
{
return Err(invalid("cached behaviour table size mismatch"));
}
let all_tags: HashMap<String, Arc<BlockSet>> = self
.tags
.into_iter()
.map(|(key, value)| (key, Arc::new(BlockSet(value))))
.collect();
let tags = Tags::resolve(&all_tags);
let shapes = self
.shapes
.into_iter()
.map(|wire| {
let shape = match wire.singleton {
1 => VoxelShape::block(),
2 => VoxelShape::empty(),
0 => {
if wire.cube {
let sizes = std::array::from_fn(|axis| {
wire.coords[axis].len().saturating_sub(1)
});
VoxelShape::from_cube(sizes, &wire.occupied)
.map_err(|e| invalid(e.to_string()))?
} else {
VoxelShape::from_mixed_grid(
wire.coords,
&wire.occupied,
wire.coordinate_cubes,
)
.map_err(|e| invalid(e.to_string()))?
}
}
_ => return Err(invalid("invalid cached shape identity")),
};
shape
.with_discrete_bounds(wire.min, wire.max)
.map_err(|e| invalid(e.to_string()))
})
.collect::<io::Result<Vec<_>>>()?;
let shape_info = self
.shape_info
.into_iter()
.map(|row| ShapeInfo {
full_faces: row[0],
nonempty_faces: row[1],
wall_cover: row[2],
})
.collect();
let facts = self
.facts
.into_iter()
.map(|wire| {
if wire.shape < -1 || wire.shape >= shapes.len() as i32 {
return Err(invalid("cached shape index out of range"));
}
let fluid_kind = FluidKind::ALL
.get(wire.fluid_kind as usize)
.copied()
.ok_or_else(|| invalid("cached fluid kind out of range"))?;
Ok(StateFacts {
flags: wire.flags,
sturdy: wire.sturdy,
weak: wire.weak,
strong: wire.strong,
fluid: FluidState::new(fluid_kind, wire.fluid_amount, wire.fluid_falling),
emission: wire.emission,
dampening: wire.dampening,
hardness: wire.hardness,
push: push(wire.push)?,
instrument: wire.instrument,
shape: wire.shape,
})
})
.collect::<io::Result<Vec<_>>>()?;
let f = self.fluid_tags;
let fluid_tags = FluidTags {
water: f[0],
lava: f[1],
supports_frogspawn: f[2],
supports_lily_pad: f[3],
supports_sugar_cane_adjacently: f[4],
bubble_column_can_occupy: f[5],
};
let blocks = self
.blocks
.into_iter()
.map(|wire| {
let chain = wire
.chain
.into_iter()
.map(class)
.collect::<io::Result<Vec<_>>>()?;
let mut classes = ClassSet::default();
for class in &chain {
classes.insert(*class);
}
let class = chain.first().copied().unwrap_or(Class::Block);
for link in [wire.link, wire.link2].into_iter().flatten() {
if link as usize >= table.block_count() {
return Err(invalid("cached block link out of range"));
}
}
Ok(BlockData {
class,
chain,
classes,
interfaces: wire.interfaces,
set_type: wire.set_type.map(|v| Arc::new(SetType::from(v))),
gate_open: wire.gate_open.map(Arc::from),
gate_close: wire.gate_close.map(Arc::from),
open_sound: wire.open_sound.map(Arc::from),
close_sound: wire.close_sound.map(Arc::from),
ticks_to_stay_pressed: wire.ticks_to_stay_pressed,
max_weight: wire.max_weight,
link: wire.link.map(BlockId),
link2: wire.link2.map(BlockId),
support_tag: wire.support_tag.map(|v| Arc::new(BlockSet(v))),
support_tag2: wire.support_tag2.map(|v| Arc::new(BlockSet(v))),
feature: wire.feature.map(Arc::from),
grow_probability: wire.grow_probability,
growth_direction: direction(wire.growth_direction)?,
schedule_fluid_ticks: wire.schedule_fluid_ticks,
weather: wire.weather,
ignite_odds: wire.ignite_odds,
burn_odds: wire.burn_odds,
sounds: Arc::new(Sounds::from(wire.sounds)),
item: Arc::from(wire.item),
dynamic_shape: wire.dynamic_shape,
})
})
.collect::<io::Result<Vec<_>>>()?;
let items = self
.items
.into_iter()
.map(|(name, wire)| {
if wire.block as usize >= table.block_count()
|| wire
.wall_block
.is_some_and(|id| id as usize >= table.block_count())
{
return Err(invalid("cached item block out of range"));
}
Ok((
name,
ItemBinding {
block: BlockId(wire.block),
wall_block: wire.wall_block.map(BlockId),
attachment: wire.attachment.map(direction).transpose()?,
kind: kind(wire.kind)?,
game_master: wire.game_master,
},
))
})
.collect::<io::Result<HashMap<_, _>>>()?;
let liquid_blocks = FluidBlockBindings::new(registry)?;
let mut dynamic = HashMap::new();
for (id, fact) in facts.iter().enumerate() {
if fact.shape < 0 {
let state = BlockStateId(id as u32);
if let Some(support) = crate::dynamic_support::DynamicSupport::from_state(
registry.state(state).unwrap(),
)? {
dynamic.insert(state, support);
}
}
}
Ok(Behaviours {
table,
props,
named,
tags,
all_tags,
facts,
shapes,
shape_info,
fluid_tags,
blocks,
items,
liquid_blocks,
dynamic,
occlusion_cache: Default::default(),
growth: Default::default(),
})
}
}
pub(super) fn load(registry: &BlockRegistry, root: &Path) -> Option<Behaviours> {
load_from(DIR.get()?, registry, root)
}
fn load_from(dir: &Path, registry: &BlockRegistry, root: &Path) -> Option<Behaviours> {
let bytes = fs::read(dir.join(FILE_NAME)).ok()?;
let fingerprint = fingerprint(registry, root).ok()?;
// Validate bounds before decoding untrusted cache contents.
if bytes.len() < 8 + 4 + 32 + 32 || bytes.len() > MAX_FILE_BYTES {
return None;
}
if &bytes[..8] != MAGIC
|| u32::from_le_bytes(bytes[8..12].try_into().ok()?) != VERSION
|| bytes[12..44] != fingerprint
{
return None;
}
let body = &bytes[76..];
if Sha256::digest(body).as_slice() != &bytes[44..76] {
return None;
}
let expanded_len = u32::from_le_bytes(body.get(..4)?.try_into().ok()?) as usize;
if expanded_len > MAX_DECODED_BYTES {
return None;
}
let expanded = lz4_flex::decompress_size_prepended(body).ok()?;
let snapshot: Snapshot = postcard::from_bytes(&expanded).ok()?;
snapshot.restore(registry).ok()
}
pub(super) fn store(registry: &BlockRegistry, root: &Path, behaviours: &Behaviours) {
if let Some(dir) = DIR.get() {
let _ = write(dir, registry, root, behaviours);
}
}
fn write(
dir: &Path,
registry: &BlockRegistry,
root: &Path,
behaviours: &Behaviours,
) -> io::Result<()> {
let fingerprint = fingerprint(registry, root)?;
let snapshot = Snapshot::capture(behaviours);
let serialized = postcard::to_allocvec(&snapshot).map_err(|e| invalid(e.to_string()))?;
let body = lz4_flex::compress_prepend_size(&serialized);
if body.len() + 76 > MAX_FILE_BYTES {
return Err(invalid("behaviour cache too large"));
}
let mut bytes = Vec::with_capacity(76 + body.len());
bytes.extend_from_slice(MAGIC);
bytes.extend_from_slice(&VERSION.to_le_bytes());
bytes.extend_from_slice(&fingerprint);
bytes.extend_from_slice(&Sha256::digest(&body));
bytes.extend_from_slice(&body);
fs::create_dir_all(dir)?;
let path = dir.join(FILE_NAME);
let tmp = dir.join(format!(
"{FILE_NAME}.tmp-{}-{}",
std::process::id(),
NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
));
let result = (|| {
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)?;
file.write_all(&bytes)?;
file.sync_all()?;
fs::rename(&tmp, &path)
})();
if result.is_err() {
let _ = fs::remove_file(&tmp);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicU64;
static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0);
struct FixtureDir(PathBuf);
impl Drop for FixtureDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn fixture() -> Option<FixtureDir> {
let source = std::env::var_os("HORIZON_RESOURCES")
.map(PathBuf::from)
.unwrap_or_else(|| {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3")
});
if !source.join("block-behaviours.json").exists() {
eprintln!("skipping behaviour cache tests: no client resources");
return None;
}
let dir = std::env::temp_dir().join(format!(
"horizon-behaviour-cache-test-{}-{}",
std::process::id(),
NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed),
));
fs::create_dir_all(dir.join("data/minecraft/tags/fluid")).unwrap();
for file in [
"facts.json",
"block-behaviours.json",
"gameplay-facts.json",
"block-tags.json",
"cached-collision.nbt",
] {
fs::copy(source.join(file), dir.join(file)).unwrap();
}
for entry in fs::read_dir(source.join("data/minecraft/tags/fluid")).unwrap() {
let entry = entry.unwrap();
if entry.file_type().unwrap().is_file() {
fs::copy(
entry.path(),
dir.join("data/minecraft/tags/fluid")
.join(entry.file_name()),
)
.unwrap();
}
}
Some(FixtureDir(dir))
}
#[test]
fn resolved_snapshot_roundtrips_all_fields() {
let Some(root) = fixture() else {
return;
};
let registry = super::super::load_registry(&root.0).unwrap();
let original = super::super::load_uncached(&registry, &root.0).unwrap();
let captured = Snapshot::capture(&original);
let restored = captured.restore(&registry).unwrap();
assert_eq!(
serde_json::to_value(Snapshot::capture(&original)).unwrap(),
serde_json::to_value(Snapshot::capture(&restored)).unwrap(),
"all resolved fields, shape grids and identities should roundtrip",
);
}
#[test]
fn cache_invalidates_sources_and_recovers_from_corruption() {
let Some(root) = fixture() else {
return;
};
// The game's cache folder, apart from the resources.
let dir = root.0.join("game/.horizon-cache");
let registry = super::super::load_registry(&root.0).unwrap();
// What `data::load` does once `set_dir` gave it a folder.
let load_or_build = || {
load_from(&dir, &registry, &root.0).unwrap_or_else(|| {
let built = super::super::load_uncached(&registry, &root.0).unwrap();
write(&dir, &registry, &root.0, &built).unwrap();
built
})
};
assert!(load_from(&dir, &registry, &root.0).is_none());
let initial = load_or_build();
assert!(dir.join(FILE_NAME).is_file());
assert!(
!root.0.join(FILE_NAME).exists(),
"the resource folder stays untouched"
);
let hit = load_from(&dir, &registry, &root.0).expect("cache hit");
assert_eq!(initial.table.state_count(), hit.table.state_count());
let tags = root.0.join("block-tags.json");
fs::OpenOptions::new()
.append(true)
.open(&tags)
.unwrap()
.write_all(b"\n")
.unwrap();
assert!(
load_from(&dir, &registry, &root.0).is_none(),
"changed resource must invalidate"
);
load_or_build();
assert!(
load_from(&dir, &registry, &root.0).is_some(),
"fallback should replace cache"
);
let cache_file = dir.join(FILE_NAME);
let mut bytes = fs::read(&cache_file).unwrap();
bytes[80] ^= 0x80;
fs::write(&cache_file, bytes).unwrap();
assert!(
load_from(&dir, &registry, &root.0).is_none(),
"checksum failure must invalidate"
);
load_or_build();
assert!(load_from(&dir, &registry, &root.0).is_some());
// A snapshot written under another key (another build of the game,
// other resources) is never trusted.
let mut other = fs::read(&cache_file).unwrap();
other[12] ^= 1;
fs::write(&cache_file, other).unwrap();
assert!(load_from(&dir, &registry, &root.0).is_none());
}
}
+7
View File
@@ -484,6 +484,13 @@ impl Behaviours {
) -> io::Result<Self> {
data::load_with_behaviour_json(registry, resources_dir, behaviour)
}
/// Keep a snapshot of the resolved tables in `dir` (a game folder's
/// `.horizon-cache`), so later launches of the same build restore it instead
/// of resolving the resources again. Without it, [`Self::load`] never caches.
pub fn set_cache_dir(dir: std::path::PathBuf) {
data::set_cache_dir(dir);
}
pub fn facts(&self, state: BlockStateId) -> &StateFacts {
&self.facts[state.0 as usize]
}
@@ -229,8 +229,9 @@ impl StructureState {
if cache.len() >= START_CACHE_LIMIT {
cache.clear();
}
cache.insert((chunk.x, chunk.z), starts.clone());
starts
// Another thread may have built the same starts meanwhile: everyone
// keeps the first, so placement state on its pieces is shared.
cache.entry((chunk.x, chunk.z)).or_insert(starts).clone()
}
/// ChunkGenerator.findNearestMapStructure: the nearest start of one of
/// `names` from block `from` (rings: every ring chunk; random spreads:
+24 -4
View File
@@ -275,16 +275,32 @@ inspected:
└── coverage.json, coverage.md
```
**Status.** `import`, `inventory`, `carry` and `report` run today:
**Status.** `import`, `inventory`, `fetch`, `carry` and `report` run today, and `port` runs
them all for what a player's machine can port (content mods of the data tier), as the
launcher's "Import modpack" does:
```
cargo run -p horizon-port-pack -- import ~/Downloads/pack.mrpack ~/.horizon/ports/pack
cargo run -p horizon-port-pack -- inventory ~/.horizon/ports/pack # --offline reuses modrinth.json
cargo run -p horizon-port-pack -- fetch ~/.horizon/ports/pack # the portable mods' jars, or name them
# --from <folder>: copy the player's own jars (an installed instance, a downloads folder)
cargo run -p horizon-port-pack -- carry ~/.horizon/ports/pack # content mods with a jar, or name them
# --resources <prepared root>: only templates Horizon's tables have
cargo run -p horizon-port-pack -- report ~/.horizon/ports/pack # coverage.json and coverage.md
cargo run -p horizon-port-pack -- port ~/Downloads/pack.zip ~/.horizon/ports/pack [--from <folder>] [--resources <root>]
```
`fetch` gets each jar the player's way, never from us: copied from a folder they have (matched
by SHA-1, or through a CurseForge app instance's `minecraftinstance.json`), else downloaded from
the link the pack itself gives (a `.mrpack`'s, on the format's hosts only) or, for a CurseForge
pack, the same file on Modrinth's public CDN, found by its SHA-1. A jar is kept only when its
hash matches. A file only CurseForge has is listed as needing a CurseForge API key (Ludovic's
decision; open question below), with the player's installed instance as the way round it.
`<work>/fetch.json` says what happened to each file. On All the Mods 10 8.3's CurseForge zip
(2026-10-17): of the 54 data-tier content mods, 42 come from Modrinth's CDN (84 MB) and 12 need
the key or the instance; `port` then carries the 42 over (0 ported, 42 partial: the harness is a
dev step).
`inventory` reads metadata only: Modrinth answers by file hash, and the jars only if the user's
instance has them (an imported instance folder, or jars put in `<work>/jars/`). Without jars,
classes come from the reviewed table, Modrinth categories and sides; with jars, from their
@@ -294,8 +310,12 @@ only): content 54, library 33, client-ui 26, performance 25, other 14, unknown 2
`carry` copies a jar's `assets/<id>/`, `data/<id>/`, `data/minecraft/tags/` and `data/c/tags/`
into `mods/<id>/carry/`, a folder content mod (API 0.2) the game loads with `--dev-mod`, and
keeps what a content mod may not hold (other namespaces, vanilla data) in `outside/`. No class
file is copied. It upgrades from 1.21.1 to 26.3: vanilla-type recipes (ingredients), loot tables
keeps what a content mod may not hold (other namespaces, vanilla data) in `outside/`. Files of
the mod's own content that the game's content loader would refuse whole also go to `outside/`,
listed with the reason in the report's `unreadable`: paths vanilla does not read (upper case),
JSON that does not parse, and shared tags with `"replace": true`. Vanilla skips them one by one.
A byte-order mark is dropped. For ATM10's 42 mods that is 19 files in 7 mods, and the 42 load as
carried. No class file is copied. It upgrades from 1.21.1 to 26.3: vanilla-type recipes (ingredients), loot tables
(`conditions` lists become one `condition`, `functions` become `modifier`, kinds move to `type`,
tool matches on silk touch or shears become `minecraft:tool/can_silk_touch` and
`minecraft:tool/can_shear`), and the `items/` definitions 1.21.4 introduced.
@@ -318,7 +338,7 @@ block's name breaking ties (`_pane`, `_gate`, `_trapdoor`).
| Format | Read | Jars come from |
|---|---|---|
| Modrinth `.mrpack` | `modrinth.index.json`: `dependencies` (minecraft, neoforge / fabric-loader / forge / quilt-loader), `files[]` with path, sha1/sha512, `env` (client/server), download URLs; `overrides/`, `client-overrides/`, `server-overrides/` | downloaded from the listed Modrinth URLs, hash-checked |
| CurseForge zip | `manifest.json`: `minecraft.version`, `modLoaders[]`, `files[]` (`projectID`, `fileID`, `required`), `overrides` | the user's installed instance (CurseForge app `minecraftinstance.json` + `mods/`). CurseForge's API needs a key, so we take what the user already downloaded |
| CurseForge zip | `manifest.json`: `minecraft.version`, `modLoaders[]`, `files[]` (`projectID`, `fileID`, `required`), `overrides`. When the overrides hold Crash Assistant's `config/crash_assistant/modlist.json` (All the Mods 10 does), its jar names, mod ids and SHA-1s replace the bare ids | the user's installed instance (CurseForge app `minecraftinstance.json` + `mods/`), or the same file on Modrinth by SHA-1. CurseForge's API needs a key, so we take what the user already downloaded |
| Prism / MultiMC instance | `mmc-pack.json` components (`net.minecraft`, `net.neoforged`, `net.fabricmc.fabric-loader`), `instance.cfg`, `.minecraft/mods/*.jar`, packwiz `.pw.toml` files if present | the instance folder |
| packwiz | `pack.toml`, `index.toml`, `mods/*.pw.toml` | as listed |
| Crash Assistant `modlist.json` | jar name → mod id, name, version, Modrinth SHA-1; the loader entry (NeoForge `21.1.x` is Minecraft 1.21.1). Packs such as ATM10 publish it in their repository | metadata only; jars put in `<work>/jars/` |
+12 -6
View File
@@ -33,6 +33,12 @@ The dedicated server is the game itself, run headless:
`whitelist on|off|list|reload|add|remove`, `ban`, `ban-ip`, `pardon`, `pardon-ip`, `banlist`, `kick` and
`say` behave as in `DedicatedServer`. Every other command goes to the game's own dispatcher as the server
(permission level 4). The log follows vanilla's Log4j pattern, in `logs/latest.log` and on stdout.
- **Player names.** `usercache.json` in the universe folder works as vanilla's `CachedUserNameToIdResolver`.
Players are added when they join and kept for a month, and the file keeps the 1000 most recently used,
newest first. The console finds a player by name in it, in any case. A name it doesn't hold is asked of the
profile service (`getByName`). If the service doesn't know the name, an offline server uses the offline
player of the lower-case name; an online server answers "That player does not exist".
`tools/test_user_cache_parity.py` checks this against vanilla, with a mock profile service.
### Measured (2026-10-16, Mac mini M4 Pro, main at bd8dff20, release build)
@@ -76,9 +82,9 @@ not tick cost, so it is in scope here (see section 9).
| Area | Status |
|---|---|
| `online-mode=true` | **Not supported.** The server logs a warning and runs offline: no session `hasJoined` check, no encryption, no secure chat. (The client side of online mode works and is tested by `test_online_mode_parity.py` against vanilla's server.) A public server must not run like this. This is the top engine item. |
| `online-mode=true` | **Works** (ServerLoginPacketListenerImpl): a 1024-bit RSA key pair at start ("Generating keypair"), the encryption request, the shared secret and challenge, AES/CFB8, and the session service's `hasJoined` check (with the address when `prevent-proxy-connections` is on), with vanilla's log lines and messages. `test_online_mode_parity.py` runs the same logins against vanilla's server and Horizon's with a mock session service. Not yet: secure chat (chat is unsigned, as on a server that doesn't enforce it). |
| Nether and End | **Players can't change dimension.** The engine keeps one dimension loaded (`Game::enter_dimension` moves only the local single-player player), and the hub serves one `dimension` to everyone. |
| Refused logins | Nothing is logged. Vanilla logs `Disconnecting <name>: <reason>` (`ServerLoginPacketListenerImpl.disconnect`) and `<name> lost connection: …`. |
| Refused logins | Logged as vanilla does: `Disconnecting <name> (/address): <reason>`, then `<name> (/address) lost connection: <reason>`, and the session errors (`Username '<name>' tried to join with an invalid session`, `Couldn't verify username because servers are unavailable`). |
| Gameplay for remote players | The LAN guest leftovers apply: an item used on a block is used twice, the recipe book doesn't work, status effects don't apply to guests, arrows don't record their owner, team friendly fire is ignored (#484). Block desync and short freezes are reported on a same-machine server (#500). |
| Defaults that surprise owners | `white-list=true` is vanilla 26.3's default, so a fresh server refuses everyone until they are added. That matches vanilla, so the first-run flow (section 3) asks about the whitelist up front. |
| Management | Only stdin. There is no service, no backups, no status beyond `list`, no restart after a crash, and a server can't be managed while it runs in the background. |
@@ -239,7 +245,7 @@ motd = "A Minecraft Server"
port = 25565
bind = "" # listen on every address, or only on this one (server-ip)
max_players = 20
online_mode = true # not supported by Horizon yet: the server runs offline and says so
online_mode = true # check players' Minecraft accounts (false: anyone joins under any name)
whitelist = true # only whitelisted players and operators can join
enforce_whitelist = false # kick online players taken off the whitelist
view_distance = 10
@@ -487,7 +493,7 @@ machine, then published in `benchmarks/`; and item 5.
**Out (next):**
- online mode on the server side (session `hasJoined`, encryption, secure chat);
- secure chat on the server (online mode itself works);
- the Nether and End for remote players;
- the headless engine and its RAM win;
- a server-only prepare without a JDK;
@@ -497,8 +503,8 @@ machine, then published in `benchmarks/`; and item 5.
- the website's "host a server" page;
- retiring `tools/server.py` and `docs/server-quickstart.txt` (once the benchmark replaces them).
Until online mode works, the docs say to run Horizon's server only on a LAN, a tailnet, or behind a
whitelist.
Online mode works, so a public server can check accounts. An offline server should still run only on a
LAN, a tailnet, or behind a whitelist.
## 11. Pull requests
+13
View File
@@ -2664,6 +2664,7 @@ dependencies = [
"gpui",
"horizon-bench",
"horizon-friends",
"horizon-port-pack",
"horizon-prepare",
"horizon-telemetry",
"horizon-theme",
@@ -2680,6 +2681,18 @@ dependencies = [
"zip",
]
[[package]]
name = "horizon-port-pack"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"sha1",
"toml 1.1.8+spec-1.1.0",
"ureq",
"zip",
]
[[package]]
name = "horizon-prepare"
version = "0.1.0"
+2
View File
@@ -26,6 +26,8 @@ horizon-prepare = { path = "../crates/horizon-prepare" }
# Join a friend: invite codes (the game does the joining).
horizon-friends = { path = "../crates/horizon-friends" }
horizon-bench = { path = "../crates/horizon-bench" }
# Import modpack: the porting pipeline, run on the player's own files (docs/modpacks.md).
horizon-port-pack = { path = "../crates/horizon-port-pack" }
# Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md).
horizon-telemetry = { path = "../crates/horizon-telemetry" }
# The session file's random name.
+17 -1
View File
@@ -25,6 +25,16 @@ The opening, then Play ([clip](docs/opening.webm)):
preparation reuses checksum-verified game jars and libraries from the current
or another installed Horizon version, so the original Minecraft install is
only required when no valid imported copy exists.
- **Modpacks**: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, or a Prism,
MultiMC or CurseForge instance folder) and see its coverage report: per mod, ported, partial,
not yet or not needed, with the reason ([docs/modpacks.md](../docs/modpacks.md)). **Port**
gets the jars of what this computer can port today (content mods with data and assets only)
the player's own way: copied from a folder they have, or downloaded from the pack's own links
or the same file on Modrinth's CDN, hash checked; files only CurseForge has need its API key, so
they come from your installed instance. It carries them over for the selected version, and
**Play** starts the game as the pack's own profile (`ports/<pack>/home/` in the game's home:
its own saves and options) with those mods. Nothing is uploaded or shared: mod jars and ports
stay on this computer.
- **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer.
Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux,
@@ -83,6 +93,11 @@ The same binary is a command-line tool; without a subcommand it opens the window
horizon-launcher account sign-out <name>
horizon-launcher account select <name> play as this account
horizon-launcher account offline play without an account
horizon-launcher modpack [list] the imported packs and their coverage
horizon-launcher modpack import <pack> a .mrpack, CurseForge zip or instance folder
horizon-launcher modpack port <pack> [--from <dir>] [--version <tag>] get the jars and carry them over
horizon-launcher modpack play <pack> [--version <tag>] play it as its own profile
horizon-launcher modpack remove <pack>
horizon-launcher benchmark [--repeats N] measure the launcher (see Performance log)
horizon-launcher data [status] what data collection is allowed, the install ID, what waits
horizon-launcher data allow|deny <kinds|all> performance, crashes, bugs, benchmarks
@@ -92,7 +107,7 @@ The same binary is a command-line tool; without a subcommand it opens the window
horizon-launcher data benchmark <report.json> upload a benchmark report, printed first
`--json` prints JSON where there is something to report (`versions`, `install`, `notes`,
`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`, `data`). Errors go to stderr with exit code 1. `server` runs in the terminal,
`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal,
so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for
scripts and tests).
@@ -192,6 +207,7 @@ bundled so the type is the same on every platform.
## Screenshots
![Server](docs/server.png)
![Modpacks](docs/modpacks.png)
![Versions](docs/versions.png)
![Patch notes](docs/patch-notes.png)
![Settings](docs/settings.png)
Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

+4
View File
@@ -1709,6 +1709,10 @@ pub enum Msg {
/// The selected account's session file for the game about to start (none = offline), or
/// why it could not be renewed.
Session(Result<Option<PathBuf>, String>),
/// A modpack step's line (`modpacks`).
PackLine(String),
/// A modpack step ended: the pack as it now is.
PackDone(Result<Box<crate::modpacks::Imported>, String>),
}
/// A running process; its output arrives as `Msg::Line`, its end as `Msg::Exit`.
+104
View File
@@ -76,6 +76,33 @@ enum DataCmd {
},
}
#[derive(Subcommand)]
enum ModpackCmd {
/// The imported packs and their coverage (the default)
List,
/// Import a .mrpack, a CurseForge zip or an instance folder, and write its coverage report
Import { path: PathBuf },
/// Get the jars of what this computer can port and carry them over
Port {
/// The pack's folder name, as list shows it
pack: String,
/// A folder with your own jars (an installed instance, a downloads folder)
#[arg(long)]
from: Option<PathBuf>,
/// The installed version the ports are for (default: the selected one)
#[arg(long)]
version: Option<String>,
},
/// Play a ported pack as its own profile
Play {
pack: String,
#[arg(long)]
version: Option<String>,
},
/// Remove an imported pack: its jars, ports and the profile's saves
Remove { pack: String },
}
#[derive(Subcommand)]
enum Cmd {
/// List Horizon releases, or the installed versions
@@ -161,6 +188,12 @@ enum Cmd {
#[command(subcommand)]
action: Option<DataCmd>,
},
/// Modpacks: import a Java pack, see its coverage report, port what this computer can and
/// play it as its own profile (docs/modpacks.md)
Modpack {
#[command(subcommand)]
action: Option<ModpackCmd>,
},
/// Serve the Model Context Protocol on stdin and stdout, for AI agents
Mcp,
/// Measure the launcher: starts (the first is the cold one), page switching, idle CPU and
@@ -400,6 +433,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
println!("Horizon is in the applications menu.");
}
}
Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?,
Cmd::Mcp => unreachable!(),
}
Ok(())
@@ -591,3 +625,73 @@ fn data(action: DataCmd, as_json: bool) -> Result<(), String> {
}
Ok(())
}
fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::modpacks::{self, Imported};
use horizon_port_pack::report::Status;
let log = &|line: String| eprintln!("{line}");
let work = |pack: &str| {
let work = modpacks::ports_dir().join(pack);
modpacks::load(&work).map(|_| work)
};
let show = |p: &Imported| {
let counts: Vec<String> = Status::ALL
.iter()
.map(|s| format!("{} {}", p.count(*s), s.label()))
.collect();
if as_json {
json(serde_json::json!({
"pack": p.slug, "name": p.title(), "summary": p.summary(),
"counts": Status::ALL.iter().map(|s| (s.label(), p.count(*s))).collect::<std::collections::BTreeMap<_, _>>(),
"portable": p.portable, "ported_mods": p.mods.len(), "jars": p.jars(),
"report": p.work.join("coverage.md"),
}));
} else {
println!(
"{} ({})\n {}\n {}",
p.title(),
p.slug,
p.summary(),
counts.join(", ")
);
println!(" {} portable, {} carried over", p.portable, p.mods.len());
if let Some(jars) = p.jars() {
println!(" {jars}");
}
println!(" {}", p.work.join("coverage.md").display());
}
};
match action {
ModpackCmd::List => {
let packs = modpacks::list();
if packs.is_empty() && !as_json {
println!("No modpack imported yet: horizon-launcher modpack import <pack>");
}
packs.iter().for_each(show);
}
ModpackCmd::Import { path } => show(&modpacks::import(&path, log)?),
ModpackCmd::Port {
pack,
from,
version,
} => {
let tag = backend::resolve_version(version.as_deref()).ok();
let resources = tag
.filter(|t| backend::is_prepared(t))
.map(|t| backend::resources(&t));
show(&modpacks::port(
&work(&pack)?,
resources.as_deref(),
from.as_deref(),
log,
)?)
}
ModpackCmd::Play { pack, version } => {
let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?;
modpacks::apply_profile(&mut cmd, &work(&pack)?)?;
attached(cmd)?
}
ModpackCmd::Remove { pack } => modpacks::remove(&work(&pack)?)?,
}
Ok(())
}
+1
View File
@@ -2,6 +2,7 @@
pub mod account;
pub mod backend;
pub mod desktop;
pub mod modpacks;
pub mod mojang;
pub mod sources;
pub mod telemetry;
+73 -32
View File
@@ -6,6 +6,7 @@ mod collection;
mod game_tools;
mod markdown;
mod mcp;
mod modpacks_page;
mod perf;
mod theme;
@@ -29,14 +30,16 @@ use theme::Theme;
enum Page {
Play,
Versions,
Modpacks,
Notes,
Settings,
}
impl Page {
const ALL: [(Page, &'static str); 4] = [
const ALL: [(Page, &'static str); 5] = [
(Page::Play, "Play"),
(Page::Versions, "Versions"),
(Page::Modpacks, "Modpacks"),
(Page::Notes, "Patch notes"),
(Page::Settings, "Settings"),
];
@@ -161,6 +164,17 @@ struct Launcher {
play_pressed: Option<Instant>,
/// `horizon-launcher benchmark` started this window to measure it.
bench: Option<perf::Bench>,
/// The Modpacks page: the imported packs (read when the page first opens), the one shown,
/// the report's filter, and the pipeline step running now with its log.
packs: Vec<horizon_launcher::modpacks::Imported>,
packs_loaded: Option<Instant>,
pack_open: Option<String>,
pack_filter: Option<horizon_port_pack::report::Status>,
pack_busy: bool,
pack_log: VecDeque<String>,
pack_error: Option<String>,
/// The game starting now plays this pack's profile (its work folder).
starting_pack: Option<std::path::PathBuf>,
}
impl Launcher {
@@ -266,6 +280,14 @@ impl Launcher {
prepare_started: None,
play_pressed: None,
bench: perf::Bench::from_env(),
packs: Vec::new(),
packs_loaded: None,
pack_open: None,
pack_filter: None,
pack_busy: false,
pack_log: VecDeque::new(),
pack_error: None,
starting_pack: None,
};
if this.bench.is_some() {
this.perf.keep_local_log(false);
@@ -406,6 +428,14 @@ impl Launcher {
Err(e) => self.client_error = Some(format!("Playing offline: {e}")),
}
self.accounts = Accounts::load();
if let Some(work) = self.starting_pack.take() {
if let Err(e) =
horizon_launcher::modpacks::apply_profile(&mut cmd, &work)
{
self.client_error = Some(e);
continue;
}
}
if let Some(code) = self.joining.take() {
if let Err(e) = backend::join_friend(&mut cmd, &code) {
self.client_error = Some(e);
@@ -473,6 +503,13 @@ impl Launcher {
Err(e) => SelfUpdate::Failed(e),
};
}
Msg::PackLine(line) => {
self.pack_log.push_back(line);
if self.pack_log.len() > LOG_LINES {
self.pack_log.pop_front();
}
}
Msg::PackDone(result) => self.pack_done(result),
Msg::Line(job, line) => {
if job == Job::Client && line.starts_with(perf::GAME_FIRST_FRAME) {
if let Some(pressed) = self.play_pressed.take() {
@@ -671,37 +708,8 @@ impl Launcher {
if self.client.is_some() || self.starting_client.is_some() {
return;
}
self.client_error = None;
self.crash = None;
self.prepare_log.clear();
// A little earlier than the spawn: file times can be coarse.
self.client_started =
Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2));
// The session (a network round trip when the token needs renewing) comes first;
// `drain` starts the game when it arrives.
self.starting_client = Some(tag);
self.play_pressed = Some(Instant::now());
let tx = self.tx.clone();
std::thread::spawn(move || {
let session = (|| {
let mut accounts = Accounts::load();
let Some((a, secrets)) = account::session_for_launch(
&account::Endpoints::live(),
account::store(),
&mut accounts,
)?
else {
return Ok(None);
};
account::write_session_file(
&backend::game_home().join("sessions"),
&a,
&secrets,
)
.map(Some)
})();
let _ = tx.send(Msg::Session(session));
});
self.starting_pack = None;
self.start_client(tag);
}
Mode::Server => {
if let Some(server) = &mut self.server {
@@ -729,6 +737,38 @@ impl Launcher {
}
}
/// Starts the game: the session first (a network round trip when the token needs
/// renewing), then `drain` starts the process when it arrives.
fn start_client(&mut self, tag: String) {
self.client_error = None;
self.crash = None;
self.prepare_log.clear();
// A little earlier than the spawn: file times can be coarse.
self.client_started =
Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2));
// The session (a network round trip when the token needs renewing) comes first;
// `drain` starts the game when it arrives.
self.starting_client = Some(tag);
self.play_pressed = Some(Instant::now());
let tx = self.tx.clone();
std::thread::spawn(move || {
let session = (|| {
let mut accounts = Accounts::load();
let Some((a, secrets)) = account::session_for_launch(
&account::Endpoints::live(),
account::store(),
&mut accounts,
)?
else {
return Ok(None);
};
account::write_session_file(&backend::game_home().join("sessions"), &a, &secrets)
.map(Some)
})();
let _ = tx.send(Msg::Session(session));
});
}
fn choose_folder(&mut self, server: bool, cx: &mut Context<Self>) {
let paths = cx.prompt_for_paths(PathPromptOptions {
files: false,
@@ -2774,6 +2814,7 @@ impl Render for Launcher {
let content = match self.page {
Page::Play => self.play_page(cx),
Page::Versions => self.versions_page(cx),
Page::Modpacks => self.modpacks_page(cx),
Page::Notes => self.notes_page(cx),
Page::Settings => self.settings_page(cx),
};
+249
View File
@@ -0,0 +1,249 @@
//! Modpacks: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, an instance folder),
//! show what Horizon runs of it, port that on this computer from the player's own downloads, and
//! play it as a profile of its own (docs/modpacks.md).
//!
//! Each pack lives in `ports/<slug>/` in the game's home: the work folder `horizon-port-pack`
//! writes (pack.json, inventory, the jars, the carried-over mods, the coverage report) and
//! `home/`, the profile's own saves and options. Nothing is uploaded or shared: mod jars are
//! often All Rights Reserved, so the ports stay on the player's machine.
use crate::backend;
use horizon_port_pack::{
fetch::{Fetched, How},
import::Pack,
pipeline::{self, Log},
report::{Row, Status},
};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Where imported packs live.
pub fn ports_dir() -> PathBuf {
backend::game_home().join("ports")
}
/// A pack's folder name: its name in lowercase words joined by dashes.
pub fn slug(name: &str) -> String {
let words: Vec<String> = name
.split(|c: char| !c.is_ascii_alphanumeric())
.filter(|w| !w.is_empty())
.map(str::to_ascii_lowercase)
.collect();
if words.is_empty() {
"pack".into()
} else {
words.join("-")
}
}
/// An imported pack, as its work folder has it.
pub struct Imported {
pub slug: String,
pub work: PathBuf,
pub pack: Pack,
pub rows: Vec<Row>,
pub fetched: Fetched,
/// The carried-over mods the profile loads.
pub mods: Vec<PathBuf>,
/// The mods the port step gets and carries over (content, data tier).
pub portable: usize,
}
impl Imported {
pub fn title(&self) -> &str {
if self.pack.name.is_empty() {
&self.slug
} else {
&self.pack.name
}
}
pub fn count(&self, status: Status) -> usize {
self.rows.iter().filter(|r| r.status == status).count()
}
/// "Minecraft 1.21.1 · neoforge 21.1.259 · 496 mods".
pub fn summary(&self) -> String {
let mut parts = Vec::new();
if !self.pack.minecraft.is_empty() {
parts.push(format!("Minecraft {}", self.pack.minecraft));
}
if !self.pack.loader.is_empty() {
parts.push(format!("{} {}", self.pack.loader, self.pack.loader_version));
}
parts.push(format!("{} files", self.pack.files.len()));
parts.join(" · ")
}
/// What getting the jars did, in one line, or None before it ran.
pub fn jars(&self) -> Option<String> {
if self.fetched.files.is_empty() {
return None;
}
let mut parts = Vec::new();
for (how, what) in [
(How::Downloaded, "downloaded"),
(How::Local, "copied from your folder"),
(How::Present, "already here"),
(
How::NeedsKey,
"only on CurseForge (needs its API key: choose your installed instance instead)",
),
(How::NotFound, "not found"),
(How::Failed, "failed"),
] {
let n = self.fetched.count(how);
if n > 0 {
parts.push(format!("{n} {what}"));
}
}
Some(format!("Jars: {}.", parts.join(", ")))
}
}
/// Reads the pack in `work`.
pub fn load(work: &Path) -> Result<Imported, String> {
let pack: Pack = pipeline::read_json(&work.join("pack.json"))?;
let rows: Vec<Row> = pipeline::read_json(&work.join("coverage.json")).unwrap_or_default();
let records: Vec<horizon_port_pack::inventory::Record> =
pipeline::read_json(&work.join("inventory.json")).unwrap_or_default();
Ok(Imported {
slug: work
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
work: work.to_path_buf(),
pack,
rows,
fetched: Fetched::load(work),
mods: carried(work),
portable: records.iter().filter(|r| pipeline::portable(r)).count(),
})
}
/// Every imported pack, by name.
pub fn list() -> Vec<Imported> {
let mut packs: Vec<Imported> = fs::read_dir(ports_dir())
.into_iter()
.flatten()
.flatten()
.filter_map(|e| load(&e.path()).ok())
.collect();
packs.sort_by_key(|p| p.title().to_ascii_lowercase());
packs
}
/// The carried-over mods in a work folder (`mods/<id>/carry/` with its manifest).
pub fn carried(work: &Path) -> Vec<PathBuf> {
let mut mods: Vec<PathBuf> = fs::read_dir(work.join("mods"))
.into_iter()
.flatten()
.flatten()
.map(|e| e.path().join("carry"))
.filter(|c| c.join("horizon-mod.toml").is_file())
.collect();
mods.sort();
mods
}
/// Imports the pack at `path` into `ports/<slug>/` and writes its coverage report from
/// metadata (Modrinth answers by file hash; nothing is downloaded yet). Importing the same pack
/// again keeps the jars and ports it already has.
pub fn import(path: &Path, log: Log) -> Result<Imported, String> {
let pack = horizon_port_pack::import::import(path)?;
let name = if pack.name.is_empty() || pack.name == "modlist" {
path.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default()
} else {
pack.name.clone()
};
let work = ports_dir().join(slug(&name));
log(format!("Importing {name} into {}", work.display()));
pipeline::import(path, &work, log)?;
pipeline::inventory(&work, false, log)?;
pipeline::report(&work, log)?;
load(&work)
}
/// Ports what this computer can: the portable mods' jars (from `from` when the player has them,
/// else the pack's links or Modrinth), carried over for `resources`, then the report again.
pub fn port(
work: &Path,
resources: Option<&Path>,
from: Option<&Path>,
log: Log,
) -> Result<Imported, String> {
pipeline::port(work, resources, from, log)?;
load(work)
}
/// Removes an imported pack: its jars, ports and the profile's saves.
pub fn remove(work: &Path) -> Result<(), String> {
if work.parent() != Some(ports_dir().as_path()) {
return Err(format!("{} is not an imported pack", work.display()));
}
fs::remove_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))
}
/// The profile's own game home: saves, options.txt, logs.
pub fn profile_home(work: &Path) -> PathBuf {
work.join("home")
}
/// Turns the game's command into this pack's profile: its own home (the player's options.txt
/// copied in the first time, so keys and video settings carry over) and its carried-over mods.
pub fn apply_profile(cmd: &mut Command, work: &Path) -> Result<(), String> {
let mods = carried(work);
if mods.is_empty() {
return Err("Nothing is ported yet: port the pack first.".into());
}
let home = profile_home(work);
fs::create_dir_all(&home).map_err(|e| format!("{}: {e}", home.display()))?;
let options = home.join("options.txt");
let own = backend::game_home().join("options.txt");
if !options.exists() && own.is_file() {
let _ = fs::copy(own, &options);
}
cmd.current_dir(&home).env("HORIZON_HOME", &home);
for m in mods {
cmd.arg("--dev-mod").arg(m);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugs() {
assert_eq!(slug("All the Mods 10"), "all-the-mods-10");
assert_eq!(slug("Create: Above & Beyond!"), "create-above-beyond");
assert_eq!(slug(" "), "pack");
}
#[test]
fn a_profile_has_its_own_home_and_mods() {
let root =
std::env::temp_dir().join(format!("horizon-launcher-pack-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let work = root.join("ports/small");
let mut cmd = Command::new("true");
assert!(apply_profile(&mut cmd, &work).is_err());
for id in ["a", "b"] {
let carry = work.join("mods").join(id).join("carry");
fs::create_dir_all(&carry).unwrap();
fs::write(carry.join("horizon-mod.toml"), "").unwrap();
}
// Left out: no manifest.
fs::create_dir_all(work.join("mods/c/carry")).unwrap();
apply_profile(&mut cmd, &work).unwrap();
let args: Vec<String> = cmd
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
assert_eq!(args.len(), 4);
assert!(args[1].ends_with("a/carry") && args[3].ends_with("b/carry"));
assert_eq!(cmd.get_current_dir(), Some(profile_home(&work).as_path()));
assert!(profile_home(&work).is_dir());
fs::remove_dir_all(&root).unwrap();
}
}
+412
View File
@@ -0,0 +1,412 @@
//! The Modpacks page: import a pack, read its coverage report, port what this computer can and
//! play it as its own profile (`horizon_launcher::modpacks`).
use super::*;
use horizon_launcher::modpacks::{self, Imported};
use horizon_port_pack::report::Status;
use std::path::PathBuf;
/// The report's filter: every row, or one status.
pub(super) const FILTERS: [(Option<Status>, &str); 5] = [
(None, "All"),
(Some(Status::Ported), "Ported"),
(Some(Status::Partial), "Partial"),
(Some(Status::NotYet), "Not yet"),
(Some(Status::NotNeeded), "Not needed"),
];
/// Lines of the pipeline's log the page shows while it works.
const LOG_SHOWN: usize = 6;
impl Launcher {
fn open_pack(&self) -> Option<&Imported> {
let slug = self.pack_open.as_ref()?;
self.packs.iter().find(|p| &p.slug == slug)
}
/// Runs a pipeline step on a thread; its lines and its end arrive as messages.
fn pack_job(
&mut self,
job: impl FnOnce(&dyn Fn(String)) -> Result<Imported, String> + Send + 'static,
) {
if self.pack_busy {
return;
}
self.pack_busy = true;
self.pack_log.clear();
self.pack_error = None;
let tx = self.tx.clone();
std::thread::spawn(move || {
let lines = tx.clone();
let log = move |line: String| {
let _ = lines.send(Msg::PackLine(line));
};
let result = job(&log);
let _ = tx.send(Msg::PackDone(result.map(Box::new)));
});
}
/// A finished step: the pack's new state, opened.
pub(super) fn pack_done(&mut self, result: Result<Box<Imported>, String>) {
self.pack_busy = false;
match result {
Ok(pack) => {
self.pack_open = Some(pack.slug.clone());
self.packs.retain(|p| p.slug != pack.slug);
self.packs.push(*pack);
self.packs.sort_by_key(|p| p.title().to_ascii_lowercase());
}
Err(e) => self.pack_error = Some(e),
}
}
fn choose_pack(&mut self, folder: bool, cx: &mut Context<Self>) {
let paths = cx.prompt_for_paths(PathPromptOptions {
files: !folder,
directories: folder,
multiple: false,
prompt: Some("Import".into()),
});
cx.spawn(async move |this, cx| {
if let Ok(Ok(Some(mut paths))) = paths.await {
if let Some(path) = paths.pop() {
let _ = this.update(cx, |this, cx| {
this.pack_job(move |log| modpacks::import(&path, log));
cx.notify();
});
}
}
})
.detach();
}
/// Ports the open pack; `from` is a folder of the player's jars, chosen when `ask`.
fn port_pack(&mut self, ask: bool, cx: &mut Context<Self>) {
let Some(work) = self.open_pack().map(|p| p.work.clone()) else {
return;
};
let resources = self
.selected()
.filter(|tag| backend::is_prepared(tag))
.map(|tag| backend::resources(tag));
if !ask {
self.pack_job(move |log| modpacks::port(&work, resources.as_deref(), None, log));
return;
}
let paths = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Use these jars".into()),
});
cx.spawn(async move |this, cx| {
if let Ok(Ok(Some(mut paths))) = paths.await {
if let Some(from) = paths.pop() {
let _ = this.update(cx, |this, cx| {
this.pack_job(move |log| {
modpacks::port(&work, resources.as_deref(), Some(&from), log)
});
cx.notify();
});
}
}
})
.detach();
}
fn play_pack(&mut self, work: PathBuf) {
let Some(tag) = self.selected().cloned() else {
return;
};
if self.client.is_some() || self.starting_client.is_some() {
return;
}
self.starting_pack = Some(work);
self.start_client(tag);
}
pub(super) fn modpacks_page(&mut self, cx: &mut Context<Self>) -> Div {
let t = self.theme;
if self.packs_loaded.is_none() {
self.packs = modpacks::list();
if self.pack_open.is_none() {
self.pack_open = self.packs.first().map(|p| p.slug.clone());
}
self.packs_loaded = Some(Instant::now());
}
let header = page_header(
"Modpacks",
"Bring a Java modpack: see what Horizon runs of it, port that on this computer from \
your own downloads, and play it as its own profile. Nothing is uploaded or shared.",
&t,
);
let busy = self.pack_busy;
let pick = |id: &'static str, label: &'static str, folder: bool| {
let b = button(id, label, Kind::Secondary, &t);
if busy {
disabled(b)
} else {
b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.choose_pack(folder, cx);
cx.notify();
}))
}
};
let actions = div()
.flex()
.flex_wrap()
.items_center()
.gap(px(8.))
.child(pick("import-file", "Import a pack file…", false))
.child(pick("import-folder", "Import an instance folder…", true))
.child(text(theme::CAPTION).text_color(t.muted).child(
".mrpack (Modrinth), .zip (CurseForge), or a Prism, MultiMC or CurseForge instance",
));
let mut page = div()
.flex()
.flex_col()
.gap(px(32.))
.child(header)
.child(actions);
if busy || !self.pack_log.is_empty() {
page = page.child(self.pack_log_plate(&t));
}
if let Some(e) = &self.pack_error {
page = page.child(notice(e.clone(), &t));
}
if self.packs.is_empty() {
return page.child(centered(
"No modpack yet. Import one to see what Horizon can run of it.",
&t,
));
}
if self.packs.len() > 1 {
let mut list = div().flex().flex_col().border_t_1().border_color(t.rule);
for (i, p) in self.packs.iter().enumerate() {
let open = self.pack_open.as_ref() == Some(&p.slug);
let slug = p.slug.clone();
let right = if open {
caps("Open").text_color(t.accent).into_any_element()
} else {
button(format!("open-{slug}"), "Open", Kind::Ghost, &t)
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.pack_open = Some(slug.clone());
cx.notify();
}))
.into_any_element()
};
list = list.child(index_row(
i + 1,
p.title().to_string(),
Some(p.summary().into_any_element()),
Some(right),
&t,
));
}
page = page.child(list);
}
match self.pack_detail(cx) {
Some(detail) => page.child(detail),
None => page,
}
}
fn pack_log_plate(&self, t: &Theme) -> Div {
let start = self.pack_log.len().saturating_sub(LOG_SHOWN);
plate(t)
.flex()
.flex_col()
.gap(px(4.))
.p(px(16.))
.child(
caps(if self.pack_busy { "Working" } else { "Done" })
.text_color(if self.pack_busy { t.accent } else { t.muted }),
)
.children(self.pack_log.iter().skip(start).map(|line| {
text(theme::CAPTION)
.font_family(theme::MONO)
.text_color(t.ink_soft)
.truncate()
.child(line.clone())
}))
}
fn pack_detail(&self, cx: &mut Context<Self>) -> Option<Div> {
let t = self.theme;
let p = self.open_pack()?;
let mut counts = div().flex().gap(px(12.));
for (status, label) in FILTERS.iter().skip(1) {
let status = status.expect("the first filter is All");
let color = match status {
Status::Ported => t.success,
Status::Partial => t.accent,
_ => t.ink,
};
counts = counts.child(
plate(&t)
.flex()
.flex_col()
.flex_1()
.gap(px(4.))
.p(px(16.))
.child(
text(theme::DISPLAY)
.text_color(color)
.child(p.count(status).to_string()),
)
.child(caps(*label).text_color(t.muted)),
);
}
let can_play = self.selected().is_some_and(|tag| backend::is_prepared(tag));
let running = self.client.is_some() || self.starting_client.is_some();
let mut buttons = div().flex().flex_wrap().items_center().gap(px(8.));
let play_label = if p.mods.is_empty() {
"Play".to_string()
} else {
format!("Play with {} mods", p.mods.len())
};
let mut play = button("pack-play", play_label, Kind::Primary, &t);
if p.mods.is_empty() || !can_play || running || self.pack_busy {
play = disabled(play);
} else {
let work = p.work.clone();
play = play.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.play_pack(work.clone());
cx.notify();
}));
}
let port_label = format!("Port {} mods", p.portable);
let mut port = button("pack-port", port_label, Kind::Secondary, &t);
let mut from = button("pack-from", "Use jars from my instance…", Kind::Ghost, &t);
if self.pack_busy || p.portable == 0 {
port = disabled(port);
from = disabled(from);
} else {
port = port.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.port_pack(false, cx);
cx.notify();
}));
from = from.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.port_pack(true, cx);
cx.notify();
}));
}
let confirming = self.confirm_remove.as_deref() == Some(p.slug.as_str());
let slug = p.slug.clone();
let work = p.work.clone();
let remove = button(
"pack-remove",
if confirming {
"Remove for good"
} else {
"Remove"
},
if confirming {
Kind::Secondary
} else {
Kind::Ghost
},
&t,
)
.when(confirming, |b| b.text_color(t.danger))
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
if this.confirm_remove.as_ref() == Some(&slug) {
match modpacks::remove(&work) {
Ok(()) => {
this.packs.retain(|p| p.slug != slug);
this.pack_open = this.packs.first().map(|p| p.slug.clone());
}
Err(e) => this.pack_error = Some(e),
}
this.confirm_remove = None;
} else {
this.confirm_remove = Some(slug.clone());
}
cx.notify();
}));
buttons = buttons.child(play).child(port).child(from).child(remove);
let mut notes = vec![format!(
"Port gets the jars of the {} mods this computer can port today (content with data \
and assets only) from the pack's own links, Modrinth, or your folder, and carries \
them over. The ports stay here, in {}.",
p.portable,
short(&p.work)
)];
if let Some(jars) = p.jars() {
notes.push(jars);
}
if !can_play {
notes.push("Playing needs a prepared Horizon version (Play page).".into());
}
let mut rows: Vec<&horizon_port_pack::report::Row> = p
.rows
.iter()
.filter(|r| self.pack_filter.is_none_or(|s| r.status == s))
.collect();
rows.sort_by(|a, b| (a.status, &a.key).cmp(&(b.status, &b.key)));
let filter = segments("pack-filter", &FILTERS, self.pack_filter, &t, {
let this = cx.entity().downgrade();
move |value, _, cx| {
let _ = this.update(cx, |this, cx| {
this.pack_filter = value;
cx.notify();
});
}
});
let mut list = div().flex().flex_col().border_t_1().border_color(t.rule);
for (i, r) in rows.iter().enumerate() {
let color = match r.status {
Status::Ported => t.success,
Status::Partial => t.accent,
Status::NotYet => t.ink_soft,
Status::NotNeeded => t.muted,
};
let name = if r.name.is_empty() || r.name == r.key {
r.key.clone()
} else {
format!("{} ({})", r.name, r.key)
};
let detail = format!("{} · {} · {}: {}", r.class, r.tier, r.license, r.reason);
list = list.child(index_row(
i + 1,
name,
Some(detail.into_any_element()),
Some(
caps(r.status.label())
.flex_none()
.text_color(color)
.into_any_element(),
),
&t,
));
}
Some(
div()
.flex()
.flex_col()
.gap(px(24.))
.child(
div()
.flex()
.flex_col()
.gap(px(4.))
.child(
text(theme::TITLE)
.text_color(t.ink)
.child(p.title().to_string()),
)
.child(text(theme::UI).text_color(t.muted).child(p.summary())),
)
.child(counts)
.child(buttons)
.children(self.client_error.clone().map(|e| notice(e, &t)))
.children(notes.into_iter().map(|n| {
text(theme::CAPTION)
.max_w(px(720.))
.text_color(t.muted)
.child(n)
}))
.child(div().flex().child(filter))
.child(list),
)
}
}
@@ -0,0 +1,382 @@
package dev.horizonlab.parity;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import net.minecraft.SharedConstants;
import net.minecraft.core.UUIDUtil;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.ProtocolInfo;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.common.ClientboundDisconnectPacket;
import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket;
import net.minecraft.network.protocol.common.ClientboundPingPacket;
import net.minecraft.network.protocol.common.ServerboundClientInformationPacket;
import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.ServerboundKeepAlivePacket;
import net.minecraft.network.protocol.common.ServerboundPongPacket;
import net.minecraft.network.protocol.common.custom.BrandPayload;
import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket;
import net.minecraft.network.protocol.configuration.ClientboundSelectKnownPacks;
import net.minecraft.network.protocol.configuration.ConfigurationProtocols;
import net.minecraft.network.protocol.configuration.ServerboundFinishConfigurationPacket;
import net.minecraft.network.protocol.configuration.ServerboundSelectKnownPacks;
import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket;
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
import net.minecraft.network.protocol.game.ClientboundSystemChatPacket;
import net.minecraft.network.protocol.game.ClientboundTrackedWaypointPacket;
import net.minecraft.network.protocol.game.GameProtocols;
import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket;
import net.minecraft.network.protocol.game.ServerboundChatCommandPacket;
import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket;
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket;
import net.minecraft.network.protocol.handshake.ClientIntent;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.handshake.HandshakeProtocols;
import net.minecraft.network.protocol.login.ClientboundLoginCompressionPacket;
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
import net.minecraft.network.protocol.login.ClientboundLoginFinishedPacket;
import net.minecraft.network.protocol.login.LoginProtocols;
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
import net.minecraft.network.protocol.login.ServerboundLoginAcknowledgedPacket;
import net.minecraft.server.level.ClientInformation;
import net.minecraft.world.entity.PositionMoveRotation;
import net.minecraft.world.entity.player.Input;
import net.minecraft.world.phys.Vec3;
/**
* Players made of vanilla's own protocol code, for the locator bar
* (tools/test_locator_bar_parity.py). Each joins in offline mode, answers
* keep-alives, pings, teleports and chunk batches, and records every
* ClientboundTrackedWaypointPacket it receives, decoded by vanilla's codec
* (a byte vanilla would not read is an error) and summarised from its bytes.
*
* <p>{@code LocatorBarClient HOST PORT OUT} takes its script on stdin, one
* line at a time: {@code step LABEL} (the label the next packets are recorded
* under), {@code join NAME}, {@code cmd NAME COMMAND...}, {@code shift NAME
* on|off} (the shift key, as ServerboundPlayerInputPacket), {@code fly NAME
* on|off} (ServerboundPlayerAbilitiesPacket), {@code quit NAME} and {@code
* end}, which writes each player's lines to OUT.
*/
public final class LocatorBarClient {
private static volatile String step = "start";
private static final Map<UUID, String> NAMES = new LinkedHashMap<>();
public static void main(String[] args) throws Exception {
ParityData.init();
String host = args[0];
int port = Integer.parseInt(args[1]);
Path output = Path.of(args[2]);
Map<String, Player> players = new LinkedHashMap<>();
BufferedReader script = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
String line;
while ((line = script.readLine()) != null) {
String[] w = line.trim().split(" ", 3);
try {
switch (w[0]) {
case "step" -> step = w[1];
case "join" -> {
Player p = new Player(w[1]);
players.put(w[1], p);
NAMES.put(UUIDUtil.createOfflinePlayerUUID(w[1]), w[1]);
p.join(host, port);
}
case "cmd" -> players.get(w[1]).command(w[2]);
case "shift" -> players.get(w[1]).send(new ServerboundPlayerInputPacket(
new Input(false, false, false, false, false, w[2].equals("on"), false)));
case "fly" -> {
net.minecraft.world.entity.player.Abilities abilities = new net.minecraft.world.entity.player.Abilities();
abilities.flying = w[2].equals("on");
players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket(abilities));
}
case "quit" -> players.get(w[1]).close();
case "end" -> {
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) {
for (Player p : players.values()) {
synchronized (p.lines) {
for (String l : p.lines) out.println(p.name + " " + l);
}
}
}
for (Player p : players.values()) p.close();
System.exit(0);
}
default -> throw new IllegalArgumentException("unknown script line " + line);
}
} catch (Exception e) {
Player p = w.length > 1 ? players.get(w[1]) : null;
if (p != null) p.record("error " + w[0] + " " + e);
else System.err.println("error " + line + ": " + e);
}
}
System.exit(1);
}
/** The waypoint packet's fields, read back from its bytes (the operation and type are private enums). */
static String waypoint(byte[] payload) {
FriendlyByteBuf b = new FriendlyByteBuf(Unpooled.wrappedBuffer(payload));
b.readVarInt(); // the packet id
String operation = switch (b.readVarInt()) {
case 0 -> "track";
case 1 -> "untrack";
case 2 -> "update";
default -> "operation?";
};
String id = b.readBoolean() ? NAMES.getOrDefault(b.readUUID(), "uuid?") : "name:" + b.readUtf();
String style = b.readUtf();
String color = b.readBoolean() ? String.format("#%02x%02x%02x", b.readUnsignedByte(), b.readUnsignedByte(), b.readUnsignedByte()) : "-";
String target = switch (b.readVarInt()) {
case 0 -> "empty";
case 1 -> "block " + b.readVarInt() + " " + b.readVarInt() + " " + b.readVarInt();
case 2 -> "chunk " + b.readVarInt() + " " + b.readVarInt();
case 3 -> "azimuth " + b.readFloat();
default -> "type?";
};
return operation + " " + id + " " + style + " " + color + " " + target;
}
/** One connection: login and configuration in the caller's thread, then play on its own. */
private static final class Player {
final String name;
final List<String> lines = new ArrayList<>();
private Socket socket;
private DataInputStream in;
private OutputStream out;
private int threshold = -1;
private ProtocolInfo<?> inbound;
private ProtocolInfo<?> outbound;
private PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0);
private boolean loaded;
private final Object replyLock = new Object();
private int replies;
Player(String name) {
this.name = name;
}
/** Runs a command and waits for its feedback, so a slow server still takes each step in its step. */
void command(String command) throws Exception {
synchronized (replyLock) {
int before = replies;
send(new ServerboundChatCommandPacket(command));
long until = System.nanoTime() + 30_000_000_000L;
while (replies == before) {
long left = (until - System.nanoTime()) / 1_000_000L;
if (left <= 0) {
record("error no reply to /" + command);
return;
}
replyLock.wait(left);
}
}
}
void record(String line) {
synchronized (lines) {
lines.add("step=" + step + " " + line);
}
}
void close() throws Exception {
if (socket != null) socket.close();
}
void join(String host, int port) throws Exception {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 10_000);
socket.setTcpNoDelay(true);
in = new DataInputStream(socket.getInputStream());
out = socket.getOutputStream();
outbound = HandshakeProtocols.SERVERBOUND;
send(new ClientIntentionPacket(SharedConstants.getProtocolVersion(), host, port, ClientIntent.LOGIN));
outbound = LoginProtocols.SERVERBOUND;
inbound = LoginProtocols.CLIENTBOUND;
send(new ServerboundHelloPacket(name, UUIDUtil.createOfflinePlayerUUID(name)));
while (true) {
Packet<?> p = read().packet;
if (p instanceof ClientboundLoginCompressionPacket c) {
threshold = c.getCompressionThreshold();
} else if (p instanceof ClientboundLoginFinishedPacket) {
send(ServerboundLoginAcknowledgedPacket.INSTANCE);
break;
} else if (p instanceof ClientboundLoginDisconnectPacket d) {
throw new IllegalStateException("login refused: " + d.reason().getString());
}
}
outbound = ConfigurationProtocols.SERVERBOUND;
inbound = ConfigurationProtocols.CLIENTBOUND;
send(new ServerboundCustomPayloadPacket(new BrandPayload("vanilla")));
send(new ServerboundClientInformationPacket(ClientInformation.createDefault()));
while (true) {
Packet<?> p = read().packet;
if (p instanceof ClientboundSelectKnownPacks k) {
send(new ServerboundSelectKnownPacks(k.knownPacks()));
} else if (p instanceof ClientboundKeepAlivePacket k) {
send(new ServerboundKeepAlivePacket(k.getId()));
} else if (p instanceof ClientboundPingPacket k) {
send(new ServerboundPongPacket(k.getId()));
} else if (p instanceof ClientboundFinishConfigurationPacket) {
send(ServerboundFinishConfigurationPacket.INSTANCE);
break;
} else if (p instanceof ClientboundDisconnectPacket d) {
throw new IllegalStateException("disconnected: " + d.reason().getString());
}
}
GameProtocols.Context context = new GameProtocols.Context() {
@Override
public boolean hasInfiniteMaterials() {
return true;
}
@Override
public boolean canUseCommandBlocks() {
return true;
}
};
outbound = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access), context);
inbound = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access));
Thread reader = new Thread(this::play, name);
reader.setDaemon(true);
reader.start();
}
private void play() {
try {
while (true) {
Received r = read();
Packet<?> p = r.packet;
if (p instanceof ClientboundTrackedWaypointPacket) {
record(waypoint(r.payload));
} else if (p instanceof ClientboundSystemChatPacket) {
synchronized (replyLock) {
replies++;
replyLock.notifyAll();
}
} else if (p instanceof ClientboundKeepAlivePacket k) {
send(new ServerboundKeepAlivePacket(k.getId()));
} else if (p instanceof ClientboundPingPacket k) {
send(new ServerboundPongPacket(k.getId()));
} else if (p instanceof ClientboundPlayerPositionPacket t) {
position = PositionMoveRotation.calculateAbsolute(position, t.change(), t.relatives());
Vec3 at = position.position();
send(new ServerboundAcceptTeleportationPacket(t.id(), at.x, at.y, at.z, position.yRot(), position.xRot()));
// Only the spawn teleport is answered with a position too (VanillaProtocolClient).
if (!loaded) {
send(new ServerboundMovePlayerPacket.PosRot(at, position.yRot(), position.xRot(), false, false));
send(new ServerboundPlayerLoadedPacket());
loaded = true;
}
} else if (p instanceof ClientboundChunkBatchFinishedPacket) {
send(new ServerboundChunkBatchReceivedPacket(64.0F));
} else if (p instanceof ClientboundDisconnectPacket d) {
record("disconnected " + d.reason().getString());
return;
}
}
} catch (Exception e) {
if (!socket.isClosed()) record("error play " + e);
}
}
private record Received(Packet<?> packet, byte[] payload) {}
private Received read() throws Exception {
byte[] payload = readFrame();
ByteBuf buf = Unpooled.wrappedBuffer(payload);
Packet<?> packet = inbound.codec().decode(buf);
if (buf.readableBytes() > 0) {
throw new IllegalStateException(packet.type().id() + " was larger than expected: " + buf.readableBytes() + " bytes left");
}
return new Received(packet, payload);
}
synchronized void send(Packet<?> packet) throws Exception {
ByteBuf body = Unpooled.buffer();
((ProtocolInfo) outbound).codec().encode(body, packet);
byte[] raw = new byte[body.readableBytes()];
body.readBytes(raw);
ByteBuf frame = Unpooled.buffer();
if (threshold >= 0) {
ByteBuf inner = Unpooled.buffer();
if (raw.length >= threshold) {
writeVarInt(inner, raw.length);
Deflater d = new Deflater();
d.setInput(raw);
d.finish();
byte[] tmp = new byte[raw.length + 64];
while (!d.finished()) inner.writeBytes(tmp, 0, d.deflate(tmp));
d.end();
} else {
writeVarInt(inner, 0);
inner.writeBytes(raw);
}
writeVarInt(frame, inner.readableBytes());
frame.writeBytes(inner);
} else {
writeVarInt(frame, raw.length);
frame.writeBytes(raw);
}
byte[] bytes = new byte[frame.readableBytes()];
frame.readBytes(bytes);
out.write(bytes);
out.flush();
}
private byte[] readFrame() throws Exception {
byte[] frame = new byte[readVarInt(in)];
in.readFully(frame);
if (threshold < 0) return frame;
ByteArrayInputStream header = new ByteArrayInputStream(frame);
int dataLength = readVarInt(header);
int skip = frame.length - header.available();
if (dataLength == 0) return java.util.Arrays.copyOfRange(frame, skip, frame.length);
Inflater inflater = new Inflater();
inflater.setInput(frame, skip, frame.length - skip);
byte[] raw = new byte[dataLength];
int n = inflater.inflate(raw);
inflater.end();
if (n != dataLength) throw new IllegalStateException("decompressed " + n + " of " + dataLength + " bytes");
return raw;
}
}
private static int readVarInt(InputStream in) throws Exception {
int value = 0;
for (int shift = 0; shift < 35; shift += 7) {
int b = in.read();
if (b < 0) throw new java.io.EOFException();
value |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) return value;
}
throw new IllegalStateException("VarInt too big");
}
private static void writeVarInt(ByteBuf buf, int value) {
while ((value & ~0x7F) != 0) {
buf.writeByte((value & 0x7F) | 0x80);
value >>>= 7;
}
buf.writeByte(value);
}
}
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Measure the resource-dependent Behaviours::load portion of client startup.
Build the behaviour_load_profile example in the checkout to be measured first:
cargo build --release -p horizon-world --example behaviour_load_profile
Run the profiler from the repository root with the matching example binary.
This measures behaviour loading, not time to first rendered frame. With
--cache-dir, the example reads and refreshes the resolved snapshot there, as the
client does with its .horizon-cache folder: the first load of a run builds it
when it is missing, the next loads restore it.
"""
import argparse
import json
import re
import statistics
import subprocess
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path, default=Path("target/release/examples/behaviour_load_profile"))
parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3"))
parser.add_argument("--cache-dir", type=Path,
help="snapshot folder (default: no snapshot, every load is uncached)")
parser.add_argument("--repeats", type=int, default=5)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.repeats < 1:
parser.error("--repeats must be at least one")
samples = []
for _ in range(args.repeats):
command = [str(args.binary.resolve()), str(args.resources.resolve())]
if args.cache_dir:
command.append(str(args.cache_dir.resolve()))
run = subprocess.run(command, text=True, capture_output=True, check=True)
values = {key: float(value) for key, value in
re.findall(r"^(registry_ms|behaviours_[0-2]_ms)=([\d.]+)$", run.stderr, re.M)}
if len(values) != 4:
raise RuntimeError(f"incomplete profile output: {run.stderr}")
samples.append(values)
summary = {key: {"median_ms": round(statistics.median(row[key] for row in samples), 3),
"samples_ms": [row[key] for row in samples]}
for key in samples[0]}
result = {"scope": "behaviour loader only; not full client startup",
"binary": str(args.binary), "resources": str(args.resources), "repeats": args.repeats,
"cache_dir": str(args.cache_dir) if args.cache_dir else None,
"metrics": summary}
print(json.dumps(result, indent=2))
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, indent=2) + "\n")
if __name__ == "__main__":
main()
+7 -2
View File
@@ -35,7 +35,8 @@ exactly:
shift-click changes and its lit and cooking totals;
- the console lines about the player, the chat, `list`, `say` and `stop`;
- the files the servers leave: server.properties (but the date line),
eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json.
eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json,
usercache.json (but the date the player's entry expires).
Online mode needs Mojang's session servers and is not tested.
"""
@@ -238,7 +239,8 @@ def console_lines(lines):
def server_files(directory):
out = []
for name in ['server.properties', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-players.json', 'banned-ips.json']:
for name in ['server.properties', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-players.json', 'banned-ips.json',
'usercache.json']:
path = directory / name
if not path.exists():
out.append(f'{name}: missing')
@@ -249,6 +251,9 @@ def server_files(directory):
text = re.sub(r'^(#[^\n]*\n)#[^\n]*\n', r'\1#<date>\n', text)
# Random per server, and each side has its own port.
text = re.sub(r'\n(management-server-secret|server-port)=[^\n]*', r'\n\1=<varies>', text)
if name == 'usercache.json':
# A month from when the player joined.
text = re.sub(r'"expiresOn":"[^"]*"', '"expiresOn":"<a month on>"', text)
out.append(f'{name}: {text!r}')
return out
+259
View File
@@ -0,0 +1,259 @@
#!/usr/bin/env python3
"""The locator bar on a dedicated server, against vanilla's, seen by vanilla clients.
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat
world vanilla generated first (players appear at its spawn), with the same server.properties (offline,
creative, view distance 4) and two operators. LocatorBarClient, two
players made of vanilla's protocol code (any byte vanilla would not read is an error), joins Alice and then
Bob, who fly as creative players do (a player floating without flying falls on the server every tick), and
records every ClientboundTrackedWaypointPacket each of them receives. Bob then:
- teleports one block, three blocks, out of Alice's view, one chunk on, really far (an azimuth) and turns
around her, and back;
- turns invisible and visible, joins a red team (by the console), has it turned blue, leaves it;
- crouches and stands up, wears a carved pumpkin and takes it off;
- turns spectator and moves, then creative again;
the console turns the `locator_bar` game rule off and on, and Bob leaves. The waypoint packets each player
received in each step are compared exactly: operation, player, style, colour and the block, chunk or angle.
"""
import os
from pathlib import Path
import platform
import shutil
import subprocess
import sys
import time
try:
from . import lab, test_rust_parity as base
from .test_dedicated_server_parity import Server, free_port
except ImportError:
import lab
import test_rust_parity as base
from test_dedicated_server_parity import Server, free_port
NAME = 'locator-bar-parity'
PROPERTIES = {
'online-mode': 'false',
'white-list': 'false',
'level-seed': '12345',
'level-type': 'minecraft\\:flat',
'generate-structures': 'false',
'gamemode': 'creative',
'force-gamemode': 'true',
'view-distance': '4',
'simulation-distance': '4',
'spawn-protection': '0',
'max-players': '5',
'pause-when-empty-seconds': '-1',
}
PLAYERS = ['Alice', 'Bob']
# (label, [what the console does], [what the players do]); every step then waits for its packets.
SCRIPT = [
('alice-joins', [], ['join Alice', 'fly Alice on', 'cmd Alice tp @s 0.5 100 0.5']),
('bob-joins', [], ['join Bob', 'fly Bob on', 'cmd Bob tp @s 2.5 100 0.5']),
('near', [], ['cmd Bob tp @s 5.5 100 0.5']),
('one-block', [], ['cmd Bob tp @s 6.5 100 0.5']),
('three-blocks', [], ['cmd Bob tp @s 9.5 100 0.5']),
('out-of-view', [], ['cmd Bob tp @s 100.5 100 0.5']),
('next-chunk', [], ['cmd Bob tp @s 116.5 100 0.5']),
('really-far', [], ['cmd Bob tp @s 1000.5 100 0.5']),
('turn-around', [], ['cmd Bob tp @s 1000.5 100 300.5']),
('half-degree', [], ['cmd Bob tp @s 1000.5 100 302.5']),
('invisible', [], ['cmd Bob effect give @s minecraft:invisibility infinite 0 true']),
('visible', [], ['cmd Bob effect clear @s']),
('back-near', [], ['cmd Bob tp @s 3.5 100 0.5']),
('red-team', ['team add red', 'team modify red color red', 'team join red Bob'], []),
('blue-team', ['team modify red color blue'], []),
('no-team', ['team leave Bob'], []),
# Crouching needs the ground: a flying player who holds shift goes down instead.
('landed', [], ['cmd Bob tp @s 3.5 -60 0.5', 'fly Bob off']),
('crouch', [], ['shift Bob on']),
('stand', [], ['shift Bob off']),
('flying-again', [], ['fly Bob on', 'cmd Bob tp @s 3.5 100 0.5']),
('pumpkin', [], ['cmd Bob item replace entity @s armor.head with minecraft:carved_pumpkin']),
('no-pumpkin', [], ['cmd Bob item replace entity @s armor.head with minecraft:air']),
('rule-off', ['gamerule locator_bar false'], []),
('moves-without', [], ['cmd Bob tp @s 4.5 100 0.5']),
('rule-on', ['gamerule locator_bar true'], []),
('spectator', [], ['cmd Bob gamemode spectator', 'cmd Bob tp @s 5.5 100 0.5']),
('creative', [], ['cmd Bob gamemode creative', 'cmd Bob tp @s 6.5 100 0.5']),
('bob-leaves', [], ['quit Bob']),
]
STEP_SECONDS = 2.0
# Vanilla's server moves a player who just joined on their own first ticks (a tiny step and back), which tracks
# them where they spawned; Horizon does not simulate its guests. These steps compare what the bar shows at
# their end (Bob has moved by then) rather than every packet.
SETTLING_STEPS = {'alice-joins', 'bob-joins'}
def shown(lines):
"""The transcript with each settling step reduced to what each player's bar shows at its end."""
out, state = [], {}
def flush(step):
for (receiver, source), rest in sorted(state.items()):
out.append(f'{receiver} step={step} shows {source} {rest}')
state.clear()
current = None
for line in lines:
receiver, step, *packet = line.split(' ')
step = step.removeprefix('step=')
if current in SETTLING_STEPS and step != current:
flush(current)
current = step
if step not in SETTLING_STEPS or len(packet) < 3:
out.append(line)
elif packet[0] == 'untrack':
state.pop((receiver, packet[1]), None)
else:
state[(receiver, packet[1])] = ' '.join(packet[2:])
if current in SETTLING_STEPS:
flush(current)
return out
def ops_json():
"""Both players at level 4, by their offline UUIDs."""
import hashlib
import json
import uuid as uuidlib
entries = []
for name in PLAYERS:
digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest())
digest[6] = (digest[6] & 0x0F) | 0x30
digest[8] = (digest[8] & 0x3F) | 0x80
entries.append({'uuid': str(uuidlib.UUID(bytes=bytes(digest))), 'name': name, 'level': 4,
'bypassesPlayerLimit': False})
return json.dumps(entries, indent=2)
def server_dir(directory, world=None):
if directory.exists():
shutil.rmtree(directory)
directory.mkdir(parents=True)
port = free_port()
props = dict(PROPERTIES, **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
encoding='iso-8859-1')
(directory / 'eula.txt').write_text('eula=true\n')
(directory / 'ops.json').write_text(ops_json())
if world is not None:
shutil.copytree(world, directory / 'world')
(directory / 'world' / 'session.lock').unlink(missing_ok=True)
return port
def generate_world(server_command, build):
"""The flat world both servers load, made once by vanilla: players appear at its spawn itself
(respawn_radius 0), on the ground at 0 -60 0, and the chunks around it are saved."""
directory = build / 'generate'
server_dir(directory)
server = Server(server_command, directory, 'generate')
try:
server.wait_for(r'Done \(')
for command, reply in [('gamerule respawn_radius 0', 'respawn_radius'),
('setworldspawn 0 -60 0', 'Set the world spawn'),
('forceload add -96 -96 96 96', 'force loaded'),
('save-all flush', 'Saved the game')]:
server.console(command)
server.wait_for(reply, timeout=120)
server.console('forceload remove all')
finally:
server.stop()
return directory / 'world'
def run_side(label, server_command, client_command, build, world):
directory = build / label
port = server_dir(directory, world)
out = build / f'{label}.txt'
out.unlink(missing_ok=True)
server = Server(server_command, directory, label)
try:
server.wait_for(r'Done \(')
with (build / f'{label}-client.log').open('w') as log:
client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
text=True)
try:
for step, console, actions in SCRIPT:
client.stdin.write(f'step {step}\n')
client.stdin.flush()
for command in console:
server.console(command)
for action in actions:
client.stdin.write(action + '\n')
client.stdin.flush()
if action.startswith('join'):
# Joining takes the world's first chunks: wait for the server to place the player.
server.wait_for(rf'{action.split()[1]} joined the game', timeout=120)
time.sleep(STEP_SECONDS)
client.stdin.write('end\n')
client.stdin.flush()
client.wait(timeout=60)
finally:
if client.poll() is None:
client.kill()
finally:
server.stop()
if not out.exists():
raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)')
return out.read_text(encoding='utf-8').splitlines()
def main():
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / NAME
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java'
classes = build / 'classes'
shutil.rmtree(classes, ignore_errors=True)
classes.mkdir()
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
cwd=lab.ROOT, check=True, capture_output=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
world = generate_world(vanilla_server, build)
vanilla = run_side('vanilla', vanilla_server, client, build, world)
horizon = run_side('horizon', horizon_server, client, build, world)
errors = [l for l in vanilla + horizon if ' error ' in f' {l} ' or 'disconnected' in l]
vanilla, horizon = shown(vanilla), shown(horizon)
# Each player's packets in their order; which player's line comes first in a step doesn't matter.
if errors or vanilla != horizon:
import difflib
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm=''))
raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n'
+ '\n'.join(errors[:10]) + '\n' + diff[:6000])
if len(vanilla) < 20:
raise AssertionError(f'only {len(vanilla)} waypoint packets: the script did not run (see {build})')
lab.write_json(report, dict(
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
packets=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
scope='Locator bar waypoints (ClientboundTrackedWaypointPacket) two vanilla-codec players receive on a '
'dedicated server: block, chunk and azimuth connections as one moves, invisibility, team colours, '
'crouching, a carved pumpkin, the locator_bar game rule, spectator mode and leaving.'))
print(f'locator bar: {len(vanilla)} waypoint packets identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')

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