Merge remote-tracking branch 'origin/wip/parity-net' into t3/minecraft-parity

# Conflicts:
#	crates/horizon-client/src/game.rs
This commit is contained in:
Ludovic Marie
2026-10-08 23:19:58 +02:00
32 changed files with 7802 additions and 6 deletions
+47 -2
View File
@@ -14,6 +14,7 @@ mod explosion;
mod growth;
mod machines;
mod tnt;
mod remote;
use horizon_client::{
Result,
assets::Assets,
@@ -90,6 +91,9 @@ struct Options {
no_pause: bool,
/// Control socket path (`--control`), for `horizon-ctl`.
control: Option<PathBuf>,
/// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name.
server: Option<String>,
player_name: String,
}
impl Options {
fn read() -> Result<Option<Self>> {
@@ -119,13 +123,15 @@ impl Options {
dimension: None,
no_pause: false,
control: None,
server: None,
player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()),
};
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--help" | "-h" => {
println!(
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
);
return Ok(None);
}
@@ -158,6 +164,8 @@ impl Options {
"--smoke-report" => o.report = Some(value.into()),
"--screenshot-after" => o.screenshot_after = Some(value.parse()?),
"--world" => o.world = Some(value),
"--server" => o.server = Some(value),
"--name" => o.player_name = value,
"--control-socket" => o.control = Some(value.into()),
"--time" => o.time = Some(value.parse()?),
"--weather" => o.weather = Some(value),
@@ -441,6 +449,8 @@ struct Game<'a> {
pending_screenshot: Option<std::sync::mpsc::Sender<String>>,
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
persist: persist::EntityMemory,
/// Connected to a server: the world comes from the network (game/remote.rs).
remote: Option<remote::Remote>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Dim {
@@ -1299,7 +1309,7 @@ impl Game<'_> {
None
}
fn spawn_player(&mut self) -> Result<()> {
if self.player.is_some() {
if self.player.is_some() || self.remote.is_some() {
return Ok(());
}
if let Some((_, target)) = &self.travelling {
@@ -1376,6 +1386,9 @@ impl Game<'_> {
Ok(())
}
fn tick(&mut self) -> Result<()> {
if self.remote.is_some() {
return self.tick_remote();
}
self.ticks += 1;
self.world.game_time += 1;
self.world.weather.tick(&mut self.world.random);
@@ -1674,6 +1687,9 @@ impl Game<'_> {
}
let atlas_ptr: *const HudAtlas = &self.res.atlas;
let _ = atlas_ptr;
if self.remote_overlay(&mut batch) {
return batch;
}
if self.player.is_none() {
let text = if self.spawn_search > 0 { "Finding a place to spawn..." } else { "Loading terrain..." };
let atlas = &self.res.atlas;
@@ -1824,6 +1840,7 @@ impl Game<'_> {
}
Screen::Playing | Screen::Options => {}
}
self.remote_hud(&mut batch);
batch
}
fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) {
@@ -1999,6 +2016,9 @@ impl Game<'_> {
}
fn close_container(&mut self) {
self.close_station();
if self.remote.is_some() {
return self.remote_close_container();
}
let mut returned: Vec<ItemStack> = self.carried.take().into_iter().collect();
returned.extend(self.craft_grid.iter_mut().filter_map(Option::take));
for stack in returned {
@@ -2021,6 +2041,8 @@ impl Game<'_> {
fn click_inventory(&mut self, right: bool) {
if self.station_click(right) {
return;
if self.remote.is_some() {
return self.remote_click(right);
}
let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return };
let batch = HudBatch::new(size);
@@ -3267,6 +3289,9 @@ impl Game<'_> {
Ok(())
}
fn close_world(&mut self) -> Result<()> {
if self.remote.is_some() {
return self.leave_server(None);
}
self.save_game()?;
self.streaming.paused = true;
self.world = World::new(self.res.facts.air, 0);
@@ -4165,6 +4190,9 @@ impl Game<'_> {
}
}
fn save_game(&mut self) -> Result<()> {
if self.remote.is_some() {
return Ok(());
}
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks: Vec<_> = keys
.iter()
@@ -4317,6 +4345,9 @@ impl Game<'_> {
}
/// A key press while a world is open (keyboard or control socket).
fn key_pressed(&mut self, key: KeyCode) -> Result<()> {
if self.remote.is_some() && self.remote_key(key)? {
return Ok(());
}
match key {
KeyCode::Escape => match self.screen {
Screen::Options => {
@@ -4383,6 +4414,9 @@ impl Game<'_> {
}
/// A mouse button while playing (window or control socket).
fn play_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
if self.remote.is_some() {
return self.remote_mouse(button, pressed);
}
match button {
MouseButton::Left => {
if pressed && self.attack() {
@@ -4414,6 +4448,9 @@ impl Game<'_> {
Ok(())
}
fn update_world(&mut self) {
if let Err(e) = self.poll_remote() {
eprintln!("Horizon: {e}");
}
if let Some(p) = &self.player {
self.streaming.center = ((p.position.x.floor() as i32) >> 4, (p.position.z.floor() as i32) >> 4);
}
@@ -4563,6 +4600,7 @@ impl ApplicationHandler for Game<'_> {
}
Action::Play { folder } => self.open_world(&folder, None, None, false)?,
Action::Create { folder, name, seed, creative } => self.open_world(&folder, Some(&name), seed, creative)?,
Action::Connect { address } => self.connect_server(&address, &self.options.player_name.clone())?,
Action::None => {}
}
}
@@ -4604,6 +4642,7 @@ impl ApplicationHandler for Game<'_> {
}
}
}
Screen::Dead if pressed && self.remote.is_some() => self.remote_respawn(),
Screen::Dead if pressed => {
self.respawn_out_of_end()?;
self.player = None;
@@ -4638,6 +4677,7 @@ impl ApplicationHandler for Game<'_> {
let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace);
self.station_text(event.text.as_deref(), backspace);
}
WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => self.remote_chat_key(&event),
WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => {
if event.state == ElementState::Pressed
&& let Some(title) = self.title.as_mut()
@@ -4936,6 +4976,7 @@ pub fn run() -> Result<()> {
pending_screenshot: None,
pending_bench: None,
persist: Default::default(),
remote: None,
};
if let Some(path) = &game.options.control {
let server = horizon_client::control::Server::start(path)
@@ -4944,6 +4985,10 @@ pub fn run() -> Result<()> {
game.control = Some(server);
}
match game.options.world.clone() {
_ if game.options.server.is_some() => {
let (address, name) = (game.options.server.clone().unwrap_or_default(), game.options.player_name.clone());
game.connect_server(&address, &name)?;
}
Some(folder) => {
let (seed, creative) = (game.options.seed, game.options.creative);
game.open_world(&folder, None, Some(seed), creative)?;
+35
View File
@@ -27,6 +27,10 @@ const HELP: &[&str] = &[
"bench SECONDS reset stats, wait, then reply with the summary",
"open WORLD [SEED] [creative] open or create a world from the title screen",
"save save the world",
"connect HOST[:PORT] [NAME] join a multiplayer server (offline mode) from the title screen",
"chat MESSAGE send chat or a /command to the server",
"disconnect leave the server for the server list",
"respawn respawn after death on a server",
"quit save and exit",
];
@@ -245,6 +249,36 @@ impl Game<'_> {
self.open_world(folder, Some(folder), seed, creative)?;
ok()
}
"connect" => {
if self.title.is_none() {
return Err("leave the current world first".into());
}
let name = words.get(2).map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned());
self.connect_server(arg(1)?, &name)?;
ok()
}
"chat" => {
if self.remote.is_none() {
return Err("not connected to a server".into());
}
let message = line.trim_start().strip_prefix("chat").unwrap_or("").trim();
self.send_chat(message);
ok()
}
"respawn" => {
if self.remote.is_none() || self.screen != Screen::Dead {
return Err("respawn needs the death screen on a server".into());
}
self.remote_respawn();
ok()
}
"disconnect" => {
if self.remote.is_none() {
return Err("not connected to a server".into());
}
self.leave_server(None)?;
ok()
}
"save" => {
self.require_world()?;
self.save_game()?;
@@ -338,6 +372,7 @@ impl Game<'_> {
"meshed_sections": self.streaming.meshed_total,
"renderer": renderer,
"uptime_seconds": self.started.elapsed().as_secs_f64(),
"server": self.remote_status(),
})
}
}
File diff suppressed because it is too large Load Diff
+2
View File
@@ -33,6 +33,8 @@ pub mod mesher;
pub mod mobs;
pub mod models;
pub mod motion;
pub mod multiplayer;
pub mod net;
pub mod particles;
pub mod pose;
pub mod save;
+276
View File
@@ -0,0 +1,276 @@
//! Multiplayer screens on the title: the server list (JoinMultiplayerScreen,
//! stored in servers.dat), Add/Edit Server, Direct Connection, and the
//! Disconnected screen. Entries are pinged in the background like
//! ServerStatusPinger to show the MOTD, player count and latency.
use crate::hud::{HudAtlas, HudBatch, rgba};
use horizon_protocol::servers::{self, ServerEntry};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
time::Duration,
};
/// The result of pinging one address.
#[derive(Clone, Debug)]
pub enum Ping {
Pinging,
Ok { motd: String, players: String, ms: u128, version: String },
Failed(String),
}
type Pings = Arc<Mutex<HashMap<String, Ping>>>;
#[derive(Clone, Debug)]
pub enum Screen {
List { servers: Vec<ServerEntry>, selected: Option<usize>, pings: Pings },
/// Add (index None) or edit a server entry.
Edit { index: Option<usize>, name: String, address: String, focus: u8 },
Direct { address: String },
Disconnected { reason: String },
}
/// What a click asks the title screen to do.
pub enum Outcome {
None,
Back,
Connect(String),
}
/// A button: x, y, width, label, enabled, id.
pub type ButtonSpec = (f32, f32, f32, String, bool, u8);
pub fn servers_file(saves: &Path) -> PathBuf {
saves.parent().map_or_else(|| PathBuf::from("servers.dat"), |p| p.join("servers.dat"))
}
fn ping_all(servers: &[ServerEntry], pings: &Pings) {
for s in servers {
let address = s.ip.clone();
pings.lock().unwrap().insert(address.clone(), Ping::Pinging);
let pings = pings.clone();
let _ = std::thread::Builder::new().name("horizon-ping".into()).spawn(move || {
let result = match crate::net::ping(&address, Duration::from_secs(5)) {
Ok((json, ms)) => {
let lang = Default::default();
let motd = crate::net::json_text(&json["description"], &lang);
let players = format!("{}/{}", json["players"]["online"].as_i64().unwrap_or(0), json["players"]["max"].as_i64().unwrap_or(0));
let version = json["version"]["name"].as_str().unwrap_or("?").to_owned();
Ping::Ok { motd, players, ms, version }
}
Err(e) => Ping::Failed(e),
};
pings.lock().unwrap().insert(address, result);
});
}
}
impl Screen {
pub fn list(saves: &Path) -> Self {
let servers = servers::load(&servers_file(saves));
let pings: Pings = Arc::default();
ping_all(&servers, &pings);
Self::List { servers, selected: None, pings }
}
pub fn buttons(&self, w: f32, h: f32) -> Vec<ButtonSpec> {
let b = |x: f32, y: f32, bw: f32, label: &str, enabled: bool, id: u8| (x, y, bw, label.to_owned(), enabled, id);
match self {
// JoinMultiplayerScreen's two button rows.
Self::List { selected, .. } => vec![
b(w / 2.0 - 154.0, h - 52.0, 100.0, "Join Server", selected.is_some(), 40),
b(w / 2.0 - 50.0, h - 52.0, 100.0, "Direct Connection", true, 41),
b(w / 2.0 + 54.0, h - 52.0, 100.0, "Add Server", true, 42),
b(w / 2.0 - 154.0, h - 28.0, 74.0, "Edit", selected.is_some(), 43),
b(w / 2.0 - 76.0, h - 28.0, 74.0, "Delete", selected.is_some(), 44),
b(w / 2.0 + 2.0, h - 28.0, 74.0, "Refresh", true, 45),
b(w / 2.0 + 80.0, h - 28.0, 74.0, "Back", true, 46),
],
Self::Edit { address, .. } => vec![
b(w / 2.0 - 100.0, h / 4.0 + 96.0 + 18.0, 200.0, "Done", servers::parse_address(address).is_some(), 50),
b(w / 2.0 - 100.0, h / 4.0 + 120.0 + 18.0, 200.0, "Cancel", true, 51),
],
Self::Direct { address } => vec![
b(w / 2.0 - 100.0, h / 4.0 + 96.0 + 12.0, 200.0, "Join Server", servers::parse_address(address).is_some(), 52),
b(w / 2.0 - 100.0, h / 4.0 + 120.0 + 12.0, 200.0, "Cancel", true, 53),
],
Self::Disconnected { .. } => vec![b(w / 2.0 - 100.0, h / 2.0 + 30.0, 200.0, "Back to Server List", true, 54)],
}
}
fn field(atlas: &HudAtlas, batch: &mut HudBatch, label: &str, value: &str, y: f32, focused: bool, blink: bool) {
let w = batch.width;
batch.text(atlas, label, w / 2.0 - 100.0, y, rgba(160, 160, 160, 255), true);
batch.fill(atlas, w / 2.0 - 100.0, y + 11.0, 200.0, 20.0, if focused { u32::MAX } else { rgba(160, 160, 160, 255) });
batch.fill(atlas, w / 2.0 - 99.0, y + 12.0, 198.0, 18.0, rgba(0, 0, 0, 255));
let shown = if focused && blink { format!("{value}_") } else { value.to_owned() };
batch.text(atlas, &shown, w / 2.0 - 96.0, y + 17.0, rgba(224, 224, 224, 255), true);
}
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) {
let (w, h) = (batch.width, batch.height);
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120));
let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| {
let tw = HudBatch::text_width(atlas, text);
batch.text(atlas, text, (w - tw) / 2.0, y, color, true);
};
match self {
Self::List { servers, selected, pings } => {
centered(batch, "Play Multiplayer", 8.0, u32::MAX);
batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100));
let pings = pings.lock().unwrap();
for (i, server) in servers.iter().enumerate() {
let y = 36.0 + i as f32 * 36.0;
if y + 36.0 > h - 64.0 {
break;
}
let x = w / 2.0 - 152.0;
if *selected == Some(i) {
batch.fill(atlas, x - 2.0, y - 2.0, 306.0, 36.0, rgba(128, 128, 128, 255));
batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255));
}
batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX);
batch.text(atlas, &server.name, x + 35.0, y + 1.0, u32::MAX, false);
let (line, right, color) = match pings.get(&server.ip) {
Some(Ping::Ok { motd, players, ms, .. }) => (motd.lines().next().unwrap_or("").to_owned(), format!("{players} {ms} ms"), rgba(128, 128, 128, 255)),
Some(Ping::Failed(_)) => ("Can't connect to server".to_owned(), String::new(), rgba(170, 0, 0, 255)),
_ => ("Pinging...".to_owned(), String::new(), rgba(128, 128, 128, 255)),
};
batch.text(atlas, &line, x + 35.0, y + 12.0, color, false);
batch.text(atlas, &server.ip, x + 35.0, y + 22.0, rgba(96, 96, 96, 255), false);
if !right.is_empty() {
let tw = HudBatch::text_width(atlas, &right);
batch.text(atlas, &right, x + 300.0 - tw, y + 1.0, rgba(128, 128, 128, 255), false);
}
}
if servers.is_empty() {
centered(batch, "No servers yet: add one or use Direct Connection", h / 2.0 - 20.0, rgba(160, 160, 160, 255));
}
}
Self::Edit { index, name, address, focus } => {
centered(batch, if index.is_some() { "Edit Server Info" } else { "Add Server" }, 17.0, u32::MAX);
Self::field(atlas, batch, "Server Name", name, 53.0, *focus == 0, blink);
Self::field(atlas, batch, "Server Address", address, 94.0, *focus == 1, blink);
}
Self::Direct { address } => {
centered(batch, "Direct Connection", 20.0, u32::MAX);
Self::field(atlas, batch, "Server Address", address, 100.0 - 11.0, true, blink);
}
Self::Disconnected { reason } => {
centered(batch, "Connection Lost", h / 2.0 - 40.0, rgba(170, 170, 170, 255));
for (i, line) in wrap(reason, 300.0, atlas).iter().enumerate() {
centered(batch, line, h / 2.0 - 16.0 + i as f32 * 9.0, u32::MAX);
}
}
}
}
pub fn click(&mut self, id: Option<u8>, x: f32, y: f32, size: (f32, f32), saves: &Path) -> Outcome {
let (w, h) = size;
match (&mut *self, id) {
(Self::List { servers, selected, .. }, Some(40)) => {
if let Some(s) = selected.and_then(|i| servers.get(i)) {
return Outcome::Connect(s.ip.clone());
}
}
(Self::List { .. }, Some(41)) => *self = Self::Direct { address: String::new() },
(Self::List { .. }, Some(42)) => *self = Self::Edit { index: None, name: "Minecraft Server".into(), address: String::new(), focus: 1 },
(Self::List { servers, selected, .. }, Some(43)) => {
if let Some((i, s)) = selected.and_then(|i| servers.get(i).map(|s| (i, s.clone()))) {
*self = Self::Edit { index: Some(i), name: s.name, address: s.ip, focus: 0 };
}
}
(Self::List { servers, selected, .. }, Some(44)) => {
if let Some(i) = selected.take()
&& i < servers.len()
{
servers.remove(i);
let _ = servers::save(&servers_file(saves), servers);
}
}
(Self::List { .. }, Some(45)) => *self = Self::list(saves),
(Self::List { .. }, Some(46)) => return Outcome::Back,
(Self::List { servers, selected, .. }, None) => {
let index = ((y - 36.0) / 36.0).floor();
if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 && (index as usize) < servers.len() {
let index = index as usize;
if *selected == Some(index) {
return Outcome::Connect(servers[index].ip.clone());
}
*selected = Some(index);
}
}
(Self::Edit { index, name, address, .. }, Some(50)) => {
let mut list = servers::load(&servers_file(saves));
let entry = ServerEntry::new(name.trim(), address.trim());
match index.and_then(|i| list.get_mut(i)) {
Some(e) => {
e.name = entry.name;
e.ip = entry.ip;
}
None => list.push(entry),
}
let _ = servers::save(&servers_file(saves), &list);
*self = Self::list(saves);
}
(Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. }, Some(51 | 53 | 54)) => *self = Self::list(saves),
(Self::Direct { address }, Some(52)) => return Outcome::Connect(address.trim().to_owned()),
(Self::Edit { focus, .. }, None) => {
for (i, fy) in [(0u8, 53.0 + 11.0), (1, 94.0 + 11.0)] {
if y >= fy && y < fy + 20.0 && (x - w / 2.0).abs() < 100.0 {
*focus = i;
}
}
}
_ => {}
}
Outcome::None
}
fn focused_field(&mut self) -> Option<&mut String> {
match self {
Self::Edit { name, address, focus, .. } => Some(if *focus == 0 { name } else { address }),
Self::Direct { address } => Some(address),
_ => None,
}
}
pub fn type_text(&mut self, text: &str) {
if let Some(field) = self.focused_field() {
for c in text.chars().filter(|c| !c.is_control()) {
if field.chars().count() < 128 {
field.push(c);
}
}
}
}
pub fn backspace(&mut self) {
if let Some(field) = self.focused_field() {
field.pop();
}
}
pub fn tab(&mut self) {
if let Self::Edit { focus, .. } = self {
*focus = (*focus + 1) % 2;
}
}
/// Escape: back to the list, or out of it (true).
pub fn escape(&mut self, saves: &Path) -> bool {
match self {
Self::List { .. } => true,
_ => {
*self = Self::list(saves);
false
}
}
}
}
/// Greedy word wrap to a pixel width.
pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec<String> {
let mut lines = Vec::new();
for paragraph in text.lines() {
let mut line = String::new();
for word in paragraph.split(' ') {
let candidate = if line.is_empty() { word.to_owned() } else { format!("{line} {word}") };
if HudBatch::text_width(atlas, &candidate) > width && !line.is_empty() {
lines.push(std::mem::take(&mut line));
line = word.to_owned();
} else {
line = candidate;
}
}
lines.push(line);
}
lines
}
+295
View File
@@ -0,0 +1,295 @@
//! Multiplayer session: a network thread that connects to a server, logs in
//! (offline mode only), runs the configuration phase and then forwards decoded
//! play packets to the game thread. Keep-alives and pings are answered on the
//! network thread like vanilla's connection handlers so a busy frame never
//! times the client out. Online-mode (authenticated) servers are refused:
//! Horizon never handles Microsoft credentials.
use horizon_protocol::{
PROTOCOL_VERSION,
connection::{ConnReader, ConnWriter, Connection, Counters},
crypto::offline_uuid,
packets::{Empty, configuration as cfg, handshake, login, play},
registry::Dynamic,
servers::parse_address,
text::{Language, plain},
};
use std::{
sync::{
Arc, Mutex,
mpsc::{Receiver, Sender, channel},
},
thread::JoinHandle,
time::Duration,
};
/// What the network thread reports to the game.
pub enum Event {
/// Progress text for the connecting screen.
Status(String),
/// Configuration finished: the play state begins with these registries.
Joined { registries: Arc<Dynamic>, uuid: u128, name: String },
Packet(Box<play::Clientbound>),
/// A packet that failed to decode (skipped, like vanilla's skippable packets).
DecodeError(String),
/// The server sent us back to configuration and finished it again.
Reconfigured(Arc<Dynamic>),
Disconnected(String),
}
pub struct Session {
events: Receiver<Event>,
writer: Arc<Mutex<Option<ConnWriter>>>,
thread: Option<JoinHandle<()>>,
pub address: String,
pub name: String,
pub counters: Arc<Mutex<Option<Arc<Counters>>>>,
/// HORIZON_NET_DEBUG=1 logs every packet sent from the game thread.
debug: bool,
}
impl Session {
/// Start connecting in the background.
pub fn connect(address: &str, name: &str, view_distance: i8, lang: Arc<Language>) -> Self {
let (send, events) = channel();
let writer = Arc::new(Mutex::new(None));
let counters = Arc::new(Mutex::new(None));
let (thread_writer, thread_counters) = (writer.clone(), counters.clone());
let (address_owned, name_owned) = (address.to_owned(), name.to_owned());
let thread = std::thread::Builder::new()
.name("horizon-net".into())
.spawn(move || {
let reason = match run(&address_owned, &name_owned, view_distance, &lang, &send, &thread_writer, &thread_counters) {
Ok(reason) => reason,
Err(e) => e,
};
if let Some(w) = thread_writer.lock().unwrap().take() {
w.shutdown();
}
let _ = send.send(Event::Disconnected(reason));
})
.ok();
let debug = std::env::var_os("HORIZON_NET_DEBUG").is_some();
Self { events, writer, thread, address: address.to_owned(), name: name.to_owned(), counters, debug }
}
/// Everything received since the last poll.
pub fn poll(&self) -> Vec<Event> {
self.events.try_iter().collect()
}
/// Send a play packet; silently dropped once the connection is gone.
pub fn send(&self, packet: play::Serverbound) {
if self.debug && !matches!(packet, play::Serverbound::ClientTickEnd(_) | play::Serverbound::MovePlayerPos(_) | play::Serverbound::MovePlayerPosRot(_)) {
eprintln!("[net] -> {packet:?}");
}
if let Some(w) = self.writer.lock().unwrap().as_mut()
&& w.send(&packet.encode()).is_err()
{
w.shutdown();
}
}
pub fn disconnect(&mut self) {
if let Some(w) = self.writer.lock().unwrap().take() {
w.shutdown();
}
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
impl Drop for Session {
fn drop(&mut self) {
self.disconnect();
}
}
fn status(send: &Sender<Event>, text: &str) {
let _ = send.send(Event::Status(text.to_owned()));
}
/// The whole connection; returns the disconnect reason.
fn run(
address: &str,
name: &str,
view_distance: i8,
lang: &Language,
send: &Sender<Event>,
shared_writer: &Mutex<Option<ConnWriter>>,
shared_counters: &Mutex<Option<Arc<Counters>>>,
) -> Result<String, String> {
let (host, port) = parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?;
status(send, "Connecting to the server...");
let mut c = Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?;
*shared_counters.lock().unwrap() = Some(c.reader.counters.clone());
let e = |e: horizon_protocol::Error| e.to_string();
c.send(
&handshake::Serverbound::Intention(handshake::Intention { protocol: PROTOCOL_VERSION, host: host.clone(), port, intent: handshake::LOGIN })
.encode(),
)
.map_err(e)?;
status(send, "Logging in...");
let uuid = offline_uuid(name);
c.send(&login::Serverbound::Hello(login::ServerHello { name: name.to_owned(), uuid }).encode()).map_err(e)?;
let profile = loop {
let (id, payload) = c.recv().map_err(e)?;
match login::Clientbound::decode(id, &payload).map_err(e)? {
login::Clientbound::Compression(p) => c.set_compression(p.threshold),
login::Clientbound::LoginFinished(p) => {
c.send(&login::Serverbound::LoginAcknowledged(Empty).encode()).map_err(e)?;
break p.profile;
}
login::Clientbound::Disconnect(p) => {
let reason = serde_json::from_str::<serde_json::Value>(&p.reason_json).map(|v| json_text(&v, lang)).unwrap_or(p.reason_json);
return Err(reason);
}
login::Clientbound::Hello(_) => {
return Err("This server is in online mode. Horizon only joins offline-mode servers (online-mode=false).".into());
}
login::Clientbound::CustomQuery(q) => {
c.send(&login::Serverbound::CustomQueryAnswer(login::CustomQueryAnswer { transaction: q.transaction, payload: None }).encode())
.map_err(e)?;
}
login::Clientbound::CookieRequest(q) => {
c.send(&login::Serverbound::CookieResponse(login::CookieResponse { key: q.key, payload: None }).encode()).map_err(e)?;
}
login::Clientbound::Unknown(..) => {}
}
};
status(send, "Joining world...");
c.send(&cfg::Serverbound::ClientInformation(cfg::ClientInformation::new(view_distance)).encode()).map_err(e)?;
c.send(&cfg::Serverbound::CustomPayload(cfg::CustomPayload { channel: "minecraft:brand".into(), data: brand() }).encode()).map_err(e)?;
let (mut reader, writer) = c.split();
*shared_writer.lock().unwrap() = Some(writer);
let registries = configure(&mut reader, shared_writer, lang)?;
let _ = send.send(Event::Joined { registries: Arc::new(registries), uuid: profile.uuid, name: profile.name });
loop {
let (id, payload) = reader.recv().map_err(e)?;
let packet = match play::Clientbound::decode(id, &payload) {
Ok(p) => p,
Err(err) => {
let name = horizon_protocol::ids::name(horizon_protocol::State::Play, horizon_protocol::Direction::Clientbound, id).unwrap_or("?");
let _ = send.send(Event::DecodeError(format!("{name}: {err}")));
continue;
}
};
let reply = |p: play::Serverbound| {
if let Some(w) = shared_writer.lock().unwrap().as_mut() {
let _ = w.send(&p.encode());
}
};
match packet {
play::Clientbound::KeepAlive(k) => reply(play::Serverbound::KeepAlive(k)),
play::Clientbound::Ping(p) => reply(play::Serverbound::Pong(p)),
play::Clientbound::BundleDelimiter(_) => {}
play::Clientbound::ResourcePackPush(p) => {
// Declined: Horizon has no server resource packs.
reply(play::Serverbound::ResourcePack(cfg::ResourcePackResponse { id: p.id, action: 1 }));
}
play::Clientbound::StartConfiguration(_) => {
reply(play::Serverbound::ConfigurationAcknowledged(Empty));
let registries = configure(&mut reader, shared_writer, lang)?;
let _ = send.send(Event::Reconfigured(Arc::new(registries)));
}
play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)),
other => {
if send.send(Event::Packet(Box::new(other))).is_err() {
return Ok("Disconnected".into());
}
}
}
}
}
/// The configuration phase: registries, tags and known packs until the
/// server finishes it (ClientConfigurationPacketListenerImpl).
fn configure(reader: &mut ConnReader, writer: &Mutex<Option<ConnWriter>>, lang: &Language) -> Result<Dynamic, String> {
let mut registries = Dynamic::default();
let reply = |p: cfg::Serverbound| -> Result<(), String> {
match writer.lock().unwrap().as_mut() {
Some(w) => w.send(&p.encode()).map_err(|e| e.to_string()),
None => Err("Disconnected".into()),
}
};
loop {
let (id, payload) = reader.recv().map_err(|e| e.to_string())?;
match cfg::Clientbound::decode(id, &payload).map_err(|e| e.to_string())? {
cfg::Clientbound::KeepAlive(k) => reply(cfg::Serverbound::KeepAlive(k))?,
cfg::Clientbound::Ping(p) => reply(cfg::Serverbound::Pong(p))?,
// Know no packs: the server then sends every registry entry in full.
cfg::Clientbound::SelectKnownPacks(_) => reply(cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { packs: vec![] }))?,
cfg::Clientbound::RegistryData(r) => registries.add(r),
cfg::Clientbound::CodeOfConduct(_) => reply(cfg::Serverbound::AcceptCodeOfConduct(Empty))?,
cfg::Clientbound::ResourcePackPush(p) => reply(cfg::Serverbound::ResourcePack(cfg::ResourcePackResponse { id: p.id, action: 1 }))?,
cfg::Clientbound::CookieRequest(q) => reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse { key: q.key, payload: None }))?,
cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)),
cfg::Clientbound::FinishConfiguration(_) => {
reply(cfg::Serverbound::FinishConfiguration(Empty))?;
return Ok(registries);
}
_ => {}
}
}
}
/// The minecraft:brand payload: a string naming the client.
fn brand() -> Vec<u8> {
let mut w = horizon_protocol::buf::Writer::new();
w.string("horizon");
w.data
}
/// Flatten a JSON chat component (login disconnects are JSON).
pub fn json_text(v: &serde_json::Value, lang: &Language) -> String {
match v {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Array(a) => a.iter().map(|e| json_text(e, lang)).collect(),
serde_json::Value::Object(o) => {
let mut out = if let Some(t) = o.get("text").and_then(|t| t.as_str()) {
t.to_owned()
} else if let Some(key) = o.get("translate").and_then(|t| t.as_str()) {
let args: Vec<String> = o.get("with").and_then(|w| w.as_array()).map(|a| a.iter().map(|e| json_text(e, lang)).collect()).unwrap_or_default();
let pattern = lang.get(key).cloned().or_else(|| o.get("fallback").and_then(|f| f.as_str()).map(str::to_owned)).unwrap_or_else(|| key.to_owned());
horizon_protocol::text::format_java(&pattern, &args)
} else {
String::new()
};
if let Some(extra) = o.get("extra").and_then(|e| e.as_array()) {
for e in extra {
out.push_str(&json_text(e, lang));
}
}
out
}
other => other.to_string(),
}
}
/// en_us.json from the prepared resources.
pub fn load_language(resources: &std::path::Path) -> Language {
std::fs::read(resources.join("assets/minecraft/lang/en_us.json"))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default()
}
/// Ask a server for its status (ServerStatusPinger): MOTD, players and the
/// round trip time in milliseconds.
pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128), String> {
use horizon_protocol::packets::status;
let (host, port) = parse_address(address).ok_or("Invalid address")?;
let mut c = Connection::connect(&host, port, timeout).map_err(|e| e.to_string())?;
c.reader.set_read_timeout(Some(timeout)).map_err(|e| e.to_string())?;
let e = |e: horizon_protocol::Error| e.to_string();
c.send(
&handshake::Serverbound::Intention(handshake::Intention { protocol: PROTOCOL_VERSION, host: host.clone(), port, intent: handshake::STATUS })
.encode(),
)
.map_err(e)?;
c.send(&status::Serverbound::StatusRequest(Empty).encode()).map_err(e)?;
let (id, payload) = c.recv().map_err(e)?;
let json = match status::Clientbound::decode(id, &payload).map_err(e)? {
status::Clientbound::StatusResponse(s) => serde_json::from_str(&s.json).map_err(|e| e.to_string())?,
_ => return Err("unexpected status reply".into()),
};
let start = std::time::Instant::now();
c.send(&status::Serverbound::PingRequest(status::Ping { time: 1 }).encode()).map_err(e)?;
let _ = c.recv().map_err(e)?;
Ok((json, start.elapsed().as_millis()))
}
+28 -2
View File
@@ -118,6 +118,9 @@ pub struct Streaming {
light_snapshots: HashMap<(i32, i32), u64>,
pub generated_total: u64,
pub meshed_total: u64,
/// Chunks come from a server (`insert_remote`/`forget`): nothing is
/// generated and columns are only unloaded when the server says so.
pub remote: bool,
}
pub struct WorkerContext {
pub assets: Arc<crate::assets::Assets>,
@@ -217,8 +220,31 @@ impl Streaming {
light_snapshots: HashMap::new(),
generated_total: 0,
meshed_total: 0,
remote: false,
}
}
/// A column received from a server: store it and relight it and its neighbours.
pub fn insert_remote(&mut self, world: &mut World, chunk: Chunk) {
let key = (chunk.x, chunk.z);
self.lit.remove(&key);
self.lighting.remove(&key);
world.chunks.insert(key, Arc::new(chunk));
self.generated_total += 1;
for dz in -1..=1 {
for dx in -1..=1 {
world.dirty_light.insert((key.0 + dx, key.1 + dz));
}
}
}
/// A column the server unloaded (ClientboundForgetLevelChunkPacket).
pub fn forget(&mut self, world: &mut World, x: i32, z: i32) -> Option<Arc<Chunk>> {
self.lit.remove(&(x, z));
self.meshed.remove(&(x, z));
self.lighting.remove(&(x, z));
self.meshing.retain(|k, _| (k.0, k.2) != (x, z));
world.dirty_sections.retain(|k| (k.0, k.2) != (x, z));
world.chunks.remove(&(x, z))
}
fn submit(&mut self, priority: i64, job: Job) {
self.order += 1;
self.shared.queue.lock().unwrap().push(Queued {
@@ -335,7 +361,7 @@ impl Streaming {
.chunks
.keys()
.copied()
.filter(|&(x, z)| !self.in_range(x, z, 3))
.filter(|&(x, z)| !self.remote && !self.in_range(x, z, 3))
.collect();
for key in &far {
self.decorated.remove(key);
@@ -409,7 +435,7 @@ impl Streaming {
}
// Generation (load or proto), closest first, bounded in flight.
let margin = if self.decorates { 3 } else { 1 };
if self.generating.len() < workers * 3 {
if !self.remote && self.generating.len() < workers * 3 {
let r = self.radius + margin;
let mut wanted = Vec::new();
for dz in -r..=r {
+31 -1
View File
@@ -18,6 +18,7 @@ pub enum Mode {
Main,
Select { worlds: Vec<WorldEntry>, selected: Option<usize> },
Create { name: String, seed: String, creative: bool, focus: u8 },
Multiplayer(crate::multiplayer::Screen),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Action {
@@ -26,6 +27,7 @@ pub enum Action {
Options,
Play { folder: String },
Create { folder: String, name: String, seed: Option<i64>, creative: bool },
Connect { address: String },
}
pub struct Title {
pub mode: Mode,
@@ -79,7 +81,7 @@ impl Title {
let y = h / 4.0 + 48.0;
vec![
b(w / 2.0 - 100.0, y, 200.0, "Singleplayer", true, 1),
b(w / 2.0 - 100.0, y + 24.0, 200.0, "Multiplayer", false, 0),
b(w / 2.0 - 100.0, y + 24.0, 200.0, "Multiplayer", true, 4),
b(w / 2.0 - 100.0, y + 48.0, 200.0, "Minecraft Realms", false, 0),
b(w / 2.0 - 100.0, y + 84.0, 98.0, "Options...", true, 3),
b(w / 2.0 + 2.0, y + 84.0, 98.0, "Quit Game", true, 2),
@@ -95,6 +97,7 @@ impl Title {
b(w / 2.0 - 155.0, h - 28.0, 150.0, "Create New World", true, 21),
b(w / 2.0 + 5.0, h - 28.0, 150.0, "Cancel", true, 22),
],
Mode::Multiplayer(screen) => screen.buttons(w, h).into_iter().map(|(x, y, bw, label, enabled, id)| b(x, y, bw, &label, enabled, id)).collect(),
}
}
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, cursor: (f32, f32)) {
@@ -155,6 +158,7 @@ impl Title {
batch.text(atlas, &shown, w / 2.0 - 96.0, y + 17.0, rgba(224, 224, 224, 255), true);
}
}
Mode::Multiplayer(screen) => screen.draw(atlas, batch, (self.started.elapsed().as_millis() / 300).is_multiple_of(2)),
}
for b in self.buttons(w, h) {
let hover = b.enabled && cursor.0 >= b.x && cursor.0 < b.x + b.w && cursor.1 >= b.y && cursor.1 < b.y + 20.0;
@@ -193,6 +197,18 @@ impl Title {
Action::None
}
(Mode::Main, Some(2)) => Action::Quit,
(Mode::Main, Some(4)) => {
self.mode = Mode::Multiplayer(crate::multiplayer::Screen::list(&self.saves));
Action::None
}
(Mode::Multiplayer(screen), hit) => match screen.click(hit, x, y, (w, h), &self.saves) {
crate::multiplayer::Outcome::Back => {
self.mode = Mode::Main;
Action::None
}
crate::multiplayer::Outcome::Connect(address) => Action::Connect { address },
crate::multiplayer::Outcome::None => Action::None,
},
(Mode::Main, Some(3)) => Action::Options,
(Mode::Select { worlds, selected }, Some(10)) => match selected.and_then(|i| worlds.get(i)) {
Some(world) => Action::Play { folder: world.folder.clone() },
@@ -254,6 +270,9 @@ impl Title {
}
}
pub fn type_text(&mut self, text: &str) {
if let Mode::Multiplayer(screen) = &mut self.mode {
screen.type_text(text);
}
if let Mode::Create { name, seed, focus, .. } = &mut self.mode {
let field = if *focus == 0 { name } else { seed };
for c in text.chars().filter(|c| !c.is_control()) {
@@ -264,17 +283,28 @@ impl Title {
}
}
pub fn backspace(&mut self) {
if let Mode::Multiplayer(screen) = &mut self.mode {
screen.backspace();
}
if let Mode::Create { name, seed, focus, .. } = &mut self.mode {
let field = if *focus == 0 { name } else { seed };
field.pop();
}
}
pub fn tab(&mut self) {
if let Mode::Multiplayer(screen) = &mut self.mode {
screen.tab();
}
if let Mode::Create { focus, .. } = &mut self.mode {
*focus = (*focus + 1) % 2;
}
}
pub fn escape(&mut self) {
if let Mode::Multiplayer(screen) = &mut self.mode
&& !screen.escape(&self.saves)
{
return;
}
self.mode = match &self.mode {
Mode::Create { .. } => Mode::Select { worlds: list_worlds(&self.saves), selected: None },
_ => Mode::Main,