Server: one level per dimension, so players can be in different dimensions

A server (the dedicated server and single player's server thread) now
holds a level per dimension, like vanilla's `MinecraftServer.levels`. Each
server tick runs every level with players in it, one at a time, by swapping
its fields into place (game/levels.rs), so the world tick code runs
unchanged. Before this, a portal did nothing while two or more players were
online.

- Levels: the parked levels keep the world, streaming, save, block ticks,
  entities, block entity state, raids, sculk and creaking scans. The
  Overworld stays loaded; another level is saved and closed after 300 ticks
  with nobody in it. Saving saves every level.
- Hub: `tick` is split into `poll` (the network, once per tick),
  `tick_level` (the packets, chunks, block changes, containers and entities
  of the players in the level in place) and `end_tick` (latency). Each guest
  has a dimension; time, weather, sounds and events reach only the players
  in their level, and the clock and weather last sent are kept per level.
- Travel: every player has their own portal state; a portal moves only that
  player into the destination's level (`ServerPlayer.teleport` packets as
  before). Respawning brings a player back to the Overworld's level.
- Player data saves and loads each player's dimension, and a returning
  player is placed in their own level.
- tools/lan_e2e.py --server-thread --check portals: the guest goes to the
  Nether while the host stays, then the host goes to the End while the guest
  is in the Nether, and both come back.

The in-frame game keeps its one level that follows its player.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 14:45:28 +02:00
parent 45cbb4f7d6
commit a67a323959
19 changed files with 828 additions and 185 deletions
+29 -14
View File
@@ -70,6 +70,7 @@ mod lan_screen;
mod lan_trading;
mod leads;
mod level_particles;
mod levels;
mod lightning;
mod llamas;
mod loom;
@@ -973,8 +974,14 @@ struct Game<'a> {
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>,
/// A server's players on their way to another level, each waiting for
/// the destination to load around them.
server_trips: Vec<server_travel::Trip>,
/// A server's levels other than the one in place (game/levels.rs).
levels: levels::Levels,
/// Which pass of a server tick runs (`tick_server`): the first one reads
/// the network, the last one ends the players' tick.
level_pass: levels::Pass,
/// 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).
@@ -1164,7 +1171,7 @@ struct Game<'a> {
/// The local player as a model (third person, the inventory).
player_model: Option<Mob>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Dim {
Overworld,
Nether,
@@ -8429,18 +8436,10 @@ impl Game<'_> {
if self.remote.is_some() {
return Ok(());
}
self.streaming.save(&mut self.world, wait);
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
self.save
.save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?;
if wait {
self.save.flush();
}
self.save_entities(wait)?;
self.save_level(wait)?;
self.save_parked_levels(wait)?;
self.save_maps();
self.save_random_sequences();
self.save_raids();
self.save_fight();
self.save_wandering_trader();
self.save_portal_arrivals();
@@ -8457,6 +8456,20 @@ impl Game<'_> {
self.message = Some(("Saved the game".into(), Instant::now()));
Ok(())
}
/// Save the level in place: its changed chunks, its entities and its raids.
fn save_level(&mut self, wait: bool) -> Result<()> {
self.streaming.save(&mut self.world, wait);
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
self.save
.save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?;
if wait {
self.save.flush();
}
self.save_entities(wait)?;
self.save_raids();
Ok(())
}
fn render(&mut self) -> Result<bool> {
self.poll_shader_pack();
let Some(size) = self
@@ -10132,7 +10145,9 @@ impl<'a> Game<'a> {
dim: Dim::Overworld,
world_root: PathBuf::new(),
travelling: None,
server_trip: None,
server_trips: Vec::new(),
levels: Default::default(),
level_pass: Default::default(),
portals: Default::default(),
end_travel: false,
respawn_config: None,
@@ -362,3 +362,11 @@ pub(super) struct CreakingState {
/// Which block states are creaking hearts, by state id.
hearts: Vec<bool>,
}
impl CreakingState {
/// Exchange the chunks scanned for creaking hearts with another level's
/// (game/levels.rs).
pub(super) fn swap_level(&mut self, other: &mut Self) {
std::mem::swap(&mut self.scanned, &mut other.scanned);
}
}
+12 -12
View File
@@ -543,18 +543,12 @@ impl Game<'_> {
);
self.save_game()?;
}
self.update_dedicated_streaming();
self.update_world();
if paused {
// MinecraftServer.tickServer: only the connections run.
self.tick_lan();
} else {
if !state.autosave {
// `save-off`: the periodic save inside the tick is skipped.
self.ticks = self.ticks.max(1);
}
self.tick()?;
if !paused && !state.autosave {
// `save-off`: the periodic save inside the tick is skipped.
self.ticks = self.ticks.max(1);
}
// MinecraftServer.tickServer: while paused only the connections run.
self.tick_server(paused)?;
if idle_timeout > 0 {
self.kick_idle(idle_timeout);
}
@@ -595,7 +589,13 @@ impl Game<'_> {
let center = self
.lan
.as_ref()
.and_then(|h| h.hub.guests.iter().find(|g| g.placed).map(|g| g.chunk()))
.and_then(|h| {
h.hub
.guests
.iter()
.find(|g| h.hub.here(g))
.map(|g| g.chunk())
})
.or_else(|| {
self.spawn
.map(|s| ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4))
@@ -23,7 +23,7 @@ impl Game<'_> {
.guests
.iter()
.filter(|g| {
g.placed
host.hub.here(g)
&& g.loaded
&& !g.dead
&& !g.creative()
+2 -4
View File
@@ -314,14 +314,12 @@ impl Game<'_> {
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.run_tasks();
self.update_dedicated_streaming();
self.update_world();
if flags.paused.load(Ordering::Relaxed) {
// Only the connections run.
self.tick_lan();
self.tick_server(true)?;
} else {
let started = Instant::now();
self.tick()?;
self.tick_server(false)?;
self.debug_charts.log_tick(started, started.elapsed());
flags.smoothed_tick_ms.store(
self.debug_charts.smoothed_tick_ms.to_bits(),
+54 -6
View File
@@ -52,7 +52,7 @@ pub(super) struct LanHost {
/// Blocks broken this tick (their sound is a level event for the guests).
pub broken: Vec<[f64; 3]>,
/// Hurt and death state of the mobs guests see.
mob_state: HashMap<u32, (i32, bool)>,
mob_state: HashMap<super::Dim, HashMap<u32, (i32, bool)>>,
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
pub mob_players: HashMap<u32, u32>,
/// An integrated server's owner (game/integrated.rs).
@@ -783,7 +783,19 @@ impl Game<'_> {
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
};
host.hub.tick(&mut ctx)
// A server with several levels runs a pass for each
// (`tick_server`): the network is read once, before the first.
let pass = self.level_pass;
let mut events = if pass.first {
host.hub.poll(&mut ctx)
} else {
Vec::new()
};
events.extend(host.hub.tick_level(&mut ctx));
if pass.last {
host.hub.end_tick();
}
events
};
if let Some(state) = &state
&& host.host_mode != state.game_mode
@@ -823,7 +835,15 @@ impl Game<'_> {
if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos)
&& !guest.spectator()
{
self.container_openers_changed(pos, false);
// In the level they were in.
let back = self.dim;
let theirs = super::Dim::from_id(&guest.dimension);
if self.enter_level(Some(&mut host), theirs).is_ok() {
self.container_openers_changed(pos, false);
}
if let Err(e) = self.enter_level(Some(&mut host), back) {
log::error!("could not reopen {}: {e}", back.id());
}
}
self.lan_crafting_left(&mut host, &mut guest);
self.save_guest(&host, &guest);
@@ -875,6 +895,7 @@ impl Game<'_> {
let default_mode = host.hub.config.default_game_mode;
let force = host.hub.config.force_game_mode;
let root = self.world_root.clone();
let in_place = host.hub.config.dimension.clone();
let owner = host.owner.as_mut();
let Some(g) = host.hub.guest_mut(conn) else {
return;
@@ -897,8 +918,28 @@ impl Game<'_> {
g.previous_position = spawn;
g.health = 20.0;
g.food = 20;
g.dimension = super::Dim::Overworld.id().to_owned();
}
// A server places each player in their own level
// (`PlayerList.placeNewPlayer`); the in-frame game has one.
let back = self.dim;
let level = super::Dim::from_id(&g.dimension);
let elsewhere = self.options.dedicated.is_some() && level != back;
if !elsewhere {
g.dimension = in_place;
}
self.load_guest_records(host, conn);
let theirs;
let entities = if elsewhere {
if let Err(e) = self.enter_level(Some(host), level) {
log::error!("could not open {}: {e}", level.id());
return;
}
theirs = self.lan_entities(&mut host.hub);
&theirs[..]
} else {
entities
};
let mut ctx = TickCtx {
world: &mut self.world,
host: state,
@@ -912,6 +953,9 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
};
host.hub.place_new_player(conn, &mut ctx);
if elsewhere && let Err(e) = self.enter_level(Some(host), back) {
log::error!("could not reopen {}: {e}", back.id());
}
}
/// Level events the game queued, for the guests (`process_level_events`).
@@ -966,7 +1010,11 @@ impl Game<'_> {
let mut seen = HashMap::new();
for m in &self.mobs {
let dead = !m.alive();
let old = host.mob_state.get(&m.id).copied();
let old = host
.mob_state
.get(&self.dim)
.and_then(|s| s.get(&m.id))
.copied();
let at = [m.position.x, m.position.y, m.position.z];
if m.hurt_time > old.map_or(0, |o| o.0) && !dead {
host.hub.entity_event(m.id as i32, 2, at);
@@ -976,7 +1024,7 @@ impl Game<'_> {
}
seen.insert(m.id, (m.hurt_time, dead));
}
host.mob_state = seen;
host.mob_state.insert(self.dim, seen);
}
/// Keep the chunks around every guest loaded.
@@ -985,7 +1033,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| g.placed)
.filter(|g| host.hub.here(g))
// The tracked square's corners and their lit neighbours lie
// within (view distance + 2) * √2 of the player's chunk.
.map(|g| (g.chunk(), (g.view_distance + 2) * 3 / 2 + 1))
+21 -2
View File
@@ -54,6 +54,8 @@ pub(super) struct GuestPlay {
/// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw.
pub(super) stats: super::stats::Stats,
last_inventory: u64,
/// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs).
pub(super) portal: horizon_client::nether_portal::PortalState,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -917,7 +919,18 @@ impl Game<'_> {
if !host.hub.guests[i].dead {
return;
}
self.respawn_level(host);
// PlayerList.respawn: a server's player comes back in the Overworld,
// where the world spawn is (respawn anchors and beds aside).
let back = self.dim;
let away = self.options.dedicated.is_some()
&& host.hub.guests[i].dimension != super::Dim::Overworld.id();
if away {
self.server_trips.retain(|t| !t.is(conn));
if let Err(e) = self.enter_level(Some(host), super::Dim::Overworld) {
log::error!("could not open the Overworld: {e}");
return;
}
}
let g = &mut host.hub.guests[i];
g.dead = false;
g.health = 20.0;
@@ -953,6 +966,9 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
};
host.hub.respawn(i, spawn, &ctx);
if away && let Err(e) = self.enter_level(Some(host), back) {
log::error!("could not reopen {}: {e}", back.id());
}
}
/// Per tick, for every guest: dig, use items, pick up drops, die.
@@ -963,7 +979,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded)
.filter(|g| host.hub.here(g) && g.loaded)
.map(|g| g.conn)
.collect();
for conn in conns {
@@ -1355,6 +1371,9 @@ impl Game<'_> {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
if !host.hub.here(g) {
continue;
}
let (id, at) = (g.entity_id, g.position);
let play = host.play.get_mut(&conn).expect("play");
let swinging = play.swing.swinging() && play.swing.ticks == 0;
+6 -3
View File
@@ -138,7 +138,7 @@ impl Game<'_> {
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g)))
.collect()
}
@@ -209,9 +209,12 @@ pub(super) struct Present {
impl Game<'_> {
/// Every guest in the world (`ServerLevel.getPlayers` past the host).
pub(super) fn lan_present(&self) -> Vec<Present> {
let guests = self.lan.iter().flat_map(|h| &h.hub.guests);
let guests = self
.lan
.iter()
.flat_map(|h| h.hub.guests.iter().filter(|g| h.hub.here(g)));
guests
.filter(|g| g.placed && g.loaded)
.filter(|g| g.loaded)
.map(|g| {
let [x, y, z] = g.position;
Present {
+2 -2
View File
@@ -32,7 +32,7 @@ impl Game<'_> {
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?)))
.min_by(|a, b| a.1.total_cmp(&b.1))
}
@@ -64,7 +64,7 @@ impl Game<'_> {
host.hub
.guests
.iter()
.find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead)
.find(|g| g.entity_id == id && g.conn != conn && host.hub.here(g) && !g.dead)
.map(|g| Victim::Guest(g.conn))
}
@@ -372,7 +372,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.find(|g| g.conn == conn)
.find(|g| g.conn == conn && host.hub.here(g))
.map(|g| uuid_words(g.uuid))
else {
continue;
+350
View File
@@ -0,0 +1,350 @@
//! A server's levels, one per dimension (`MinecraftServer.levels`).
//!
//! The game's tick code reads one level: the one in place, held in `Game`'s
//! own fields (the world, its streaming and save, block ticks, entities).
//! A server (the dedicated server and single player's server thread) keeps
//! the other dimensions' levels here and ticks each one that has players by
//! swapping it into place (`enter_level`), the way `as_guest` swaps a player
//! in, so the tick code runs unchanged, one level at a time. The in-frame
//! game holds one level, which follows its player (`enter_dimension`).
//!
//! Shared by every level, as vanilla's derived levels share the
//! Overworld's level data: the game time, the day time and the weather, the
//! game rules, the scoreboard, the maps and the entities waiting to arrive
//! through a portal.
use super::{
Dim, ExperienceOrb, FallingBlock, Game, ItemEntity, Mob, boats, commands,
creaking::CreakingState, dragon, fireworks, lan::LanHost, lightning, machines, minecarts,
ominous_item_spawner, persist, raids::Raiding, sculk::SculkState, tnt, trident,
};
use horizon_client::{
Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections,
save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World,
};
use horizon_world::level::{LevelEvent, Ticks};
use std::{collections::HashMap, sync::Arc};
/// Server ticks a level other than the Overworld stays loaded with no player
/// in it, before it is saved and closed (vanilla unloads a level's chunks
/// once no ticket holds them; the Overworld stays loaded).
const IDLE_TICKS: u32 = 300;
/// A level that is not in place: every per-level field of `Game`.
pub(super) struct Parked {
world: World,
streaming: Streaming,
save: Arc<SaveDir>,
block_ticks: Ticks,
tick_chunks: TickChunkMembership,
random_tick_sections: RandomTickSections,
level_events: Vec<LevelEvent>,
falling: Vec<FallingBlock>,
paintings: Vec<horizon_client::entities::Painting>,
item_frames: Vec<horizon_client::entities::ItemFrame>,
armor_stands: Vec<horizon_client::entities::ArmorStand>,
others: Vec<commands::OtherEntity>,
boats: Vec<boats::Boat>,
carts: Vec<minecarts::Minecart>,
jukebox_sounds: HashMap<(i32, i32, i32), u64>,
bolts: Vec<lightning::Bolt>,
crystals: Vec<dragon::Crystal>,
dragon: Option<dragon::Dragon>,
dragon_fireballs: Vec<dragon::DragonFireball>,
breath_clouds: Vec<dragon::Breath>,
tridents: Vec<trident::ThrownTrident>,
rockets: Vec<fireworks::Rocket>,
ominous_spawners: Vec<ominous_item_spawner::OminousItemSpawner>,
tnts: Vec<tnt::PrimedTnt>,
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
mobs: Vec<Mob>,
projectiles: Vec<horizon_client::projectiles::Projectile>,
dropped: Vec<ItemEntity>,
orbs: Vec<ExperienceOrb>,
persist: persist::EntityMemory,
lectern_pulses: Vec<((i32, i32, i32), i32)>,
lid_openers: HashMap<(i32, i32, i32), i32>,
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
lan_block_events: Vec<([i32; 3], i32, i32, u16)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
/// Only the per-level parts of these are used (`swap_level`).
anims: BlockEntityAnims,
raiding: Raiding,
sculk: SculkState,
creaking: CreakingState,
/// Server ticks since a player was last in the level.
idle: u32,
}
/// Which passes of the server tick the level in place runs: the first
/// reads the network (`Hub::poll`), the last ends the tick for every player
/// (`Hub::end_tick`). A tick with one level is both.
#[derive(Clone, Copy)]
pub(super) struct Pass {
pub first: bool,
pub last: bool,
}
impl Default for Pass {
fn default() -> Self {
Self {
first: true,
last: true,
}
}
}
/// The levels not in place, by dimension.
#[derive(Default)]
pub(super) struct Levels {
parked: HashMap<Dim, Parked>,
}
impl Game<'_> {
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
fn open_level(&self, dim: Dim) -> Result<Parked> {
let (streaming, save) =
self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?;
let mut world = World::new(self.res.facts.air, self.level.seed);
world.fast_lava = dim == Dim::Nether;
Ok(Parked {
world,
streaming,
save,
block_ticks: Ticks::new(self.level.seed as i32),
tick_chunks: Default::default(),
random_tick_sections: Default::default(),
level_events: Vec::new(),
falling: Vec::new(),
paintings: Vec::new(),
item_frames: Vec::new(),
armor_stands: Vec::new(),
others: Vec::new(),
boats: Vec::new(),
carts: Vec::new(),
jukebox_sounds: HashMap::new(),
bolts: Vec::new(),
crystals: Vec::new(),
dragon: None,
dragon_fireballs: Vec::new(),
breath_clouds: Vec::new(),
tridents: Vec::new(),
rockets: Vec::new(),
ominous_spawners: Vec::new(),
tnts: Vec::new(),
hoppers: HashMap::new(),
mobs: Vec::new(),
projectiles: Vec::new(),
dropped: Vec::new(),
orbs: Vec::new(),
persist: Default::default(),
lectern_pulses: Vec::new(),
lid_openers: HashMap::new(),
lan_events: Vec::new(),
lan_block_events: Vec::new(),
lan_entity_events: Vec::new(),
anims: Default::default(),
raiding: Default::default(),
sculk: Default::default(),
creaking: Default::default(),
idle: 0,
})
}
/// Exchange the level in place with `p`.
fn swap_level(&mut self, p: &mut Parked) {
use std::mem::swap;
swap(&mut self.world, &mut p.world);
swap(&mut self.streaming, &mut p.streaming);
swap(&mut self.save, &mut p.save);
swap(&mut self.block_ticks, &mut p.block_ticks);
swap(&mut self.tick_chunks, &mut p.tick_chunks);
swap(&mut self.random_tick_sections, &mut p.random_tick_sections);
swap(&mut self.level_events, &mut p.level_events);
swap(&mut self.falling, &mut p.falling);
swap(&mut self.paintings, &mut p.paintings);
swap(&mut self.item_frames, &mut p.item_frames);
swap(&mut self.armor_stands, &mut p.armor_stands);
swap(&mut self.others, &mut p.others);
swap(&mut self.boats, &mut p.boats);
swap(&mut self.carts, &mut p.carts);
swap(&mut self.jukebox_sounds, &mut p.jukebox_sounds);
swap(&mut self.bolts, &mut p.bolts);
swap(&mut self.crystals, &mut p.crystals);
swap(&mut self.dragon, &mut p.dragon);
swap(&mut self.dragon_fireballs, &mut p.dragon_fireballs);
swap(&mut self.breath_clouds, &mut p.breath_clouds);
swap(&mut self.tridents, &mut p.tridents);
swap(&mut self.rockets, &mut p.rockets);
swap(&mut self.ominous_spawners, &mut p.ominous_spawners);
swap(&mut self.tnts, &mut p.tnts);
swap(&mut self.hoppers, &mut p.hoppers);
swap(&mut self.mobs, &mut p.mobs);
swap(&mut self.creatures.projectiles, &mut p.projectiles);
swap(&mut self.dropped, &mut p.dropped);
swap(&mut self.orbs, &mut p.orbs);
swap(&mut self.persist, &mut p.persist);
swap(&mut self.lectern_pulses, &mut p.lectern_pulses);
swap(&mut self.lid_openers, &mut p.lid_openers);
swap(&mut self.lan_events, &mut p.lan_events);
swap(&mut self.lan_block_events, &mut p.lan_block_events);
swap(&mut self.lan_entity_events, &mut p.lan_entity_events);
let (a, b) = (&mut self.be_anims, &mut p.anims);
swap(&mut a.chests, &mut b.chests);
swap(&mut a.books, &mut b.books);
swap(&mut a.shulkers, &mut b.shulkers);
swap(&mut a.bells, &mut b.bells);
swap(&mut a.conduits, &mut b.conduits);
swap(&mut a.skulls, &mut b.skulls);
swap(&mut a.pots, &mut b.pots);
swap(&mut a.gateways, &mut b.gateways);
swap(&mut a.gateway_servers, &mut b.gateway_servers);
self.raiding.swap_level(&mut p.raiding);
self.sculk.swap_level(&mut p.sculk);
self.creaking.swap_level(&mut p.creaking);
// What only the client draws starts over.
self.particles.clear();
self.pickups.clear();
}
/// Put `target`'s level in place, opening it first if it is not loaded.
/// The level that was in place is kept with the others; the shared
/// clock and weather go with the swap. `host` is the hub when the caller
/// holds it (`self.lan` is taken during the network tick).
pub(super) fn enter_level(&mut self, host: Option<&mut LanHost>, target: Dim) -> Result<()> {
// The in-frame game keeps its one level (`enter_dimension`).
if self.options.dedicated.is_none() {
return Ok(());
}
if target != self.dim {
let (mut p, opened) = match self.levels.parked.remove(&target) {
Some(p) => (p, false),
None => (self.open_level(target)?, true),
};
p.world.game_time = self.world.game_time;
p.world.day_time = self.world.day_time;
p.world.weather = self.world.weather;
// The sculk tables' watched blocks are built once per game.
p.world.watched = std::mem::take(&mut self.world.watched);
self.swap_level(&mut p);
p.idle = 0;
let left = std::mem::replace(&mut self.dim, target);
self.levels.parked.insert(left, p);
if opened {
// The new streaming's radius and meshing options.
self.apply_settings();
}
}
let host = match host {
Some(h) => Some(h),
None => self.lan.as_mut(),
};
if let Some(h) = host {
h.hub.set_dimension(target.id());
}
Ok(())
}
/// One server tick (`MinecraftServer.tickServer`): each level with
/// players in turn (`tickChildren`), its chunks streamed and loaded and
/// its world ticked. The first pass reads the network and runs the
/// tick's shared parts (the clock, the weather, functions, the autosave);
/// the next ones only their level. While `paused`, only the connections
/// run.
pub(super) fn tick_server(&mut self, paused: bool) -> Result<()> {
let dims = self.levels_to_tick();
let n = dims.len();
let mut result = Ok(());
for (k, dim) in dims.into_iter().enumerate() {
if let Err(e) = self.enter_level(None, dim) {
result = Err(e);
break;
}
self.level_pass = Pass {
first: k == 0,
last: k + 1 == n,
};
self.update_dedicated_streaming();
self.update_world();
result = if paused {
self.tick_lan();
Ok(())
} else if k == 0 {
self.tick()
} else {
let running = self.clock.world_runs();
if running {
self.tick_weather_effects();
}
self.tick_world(running)
};
if result.is_err() {
break;
}
}
self.level_pass = Pass::default();
result?;
self.close_idle_levels()
}
/// The levels this server tick runs, in `MinecraftServer.levels` order
/// (the Overworld, the Nether, the End): every level with a player in
/// it, or the Overworld while nobody is online.
pub(super) fn levels_to_tick(&self) -> Vec<Dim> {
let guests = self
.lan
.as_ref()
.map_or(&[][..], |h| h.hub.guests.as_slice());
let mut dims: Vec<Dim> = [Dim::Overworld, Dim::Nether, Dim::End]
.into_iter()
.filter(|d| guests.iter().any(|g| g.dimension == d.id()))
.collect();
if dims.is_empty() {
dims.push(Dim::Overworld);
}
dims
}
/// Count the parked levels' empty ticks, and save and close the ones
/// (other than the Overworld) nobody has been in for a while.
pub(super) fn close_idle_levels(&mut self) -> Result<()> {
let occupied = self.levels_to_tick();
let mut closing = Vec::new();
for (dim, p) in &mut self.levels.parked {
if occupied.contains(dim) {
p.idle = 0;
continue;
}
p.idle += 1;
if *dim != Dim::Overworld && p.idle >= IDLE_TICKS {
closing.push(*dim);
}
}
if closing.is_empty() {
return Ok(());
}
let back = self.dim;
for dim in closing {
self.enter_level(None, dim)?;
self.save_level(true)?;
self.enter_level(None, back)?;
self.levels.parked.remove(&dim);
}
Ok(())
}
/// Save every parked level (`MinecraftServer.saveAllChunks`); the level
/// in place is the caller's to save.
pub(super) fn save_parked_levels(&mut self, wait: bool) -> Result<()> {
if self.levels.parked.is_empty() {
return Ok(());
}
let back = self.dim;
let dims: Vec<Dim> = self.levels.parked.keys().copied().collect();
for dim in dims {
self.enter_level(None, dim)?;
self.save_level(wait)?;
}
self.enter_level(None, back)
}
}
+11
View File
@@ -39,6 +39,17 @@ pub(super) struct Raiding {
homes: HashMap<i32, (i64, std::sync::Arc<Vec<[i32; 3]>>)>,
}
impl Raiding {
/// Exchange the level-held parts (`ServerLevel.getRaids`) with another
/// level's (game/levels.rs).
pub(super) fn swap_level(&mut self, other: &mut Self) {
std::mem::swap(&mut self.raids, &mut other.raids);
std::mem::swap(&mut self.loaded, &mut other.loaded);
std::mem::swap(&mut self.bar_hurts, &mut other.bar_hurts);
std::mem::swap(&mut self.homes, &mut other.homes);
}
}
/// `SectionPos` of a block position.
pub(super) fn section(p: [i32; 3]) -> (i32, i32, i32) {
(p[0] >> 4, p[1] >> 4, p[2] >> 4)
+9
View File
@@ -80,6 +80,15 @@ pub(super) struct SculkState {
ticks: u32,
pub tracker_loaded: bool,
}
impl SculkState {
/// Exchange the level-held parts (its sculk block entities and the
/// chunks scanned for them) with another level's (game/levels.rs).
pub(super) fn swap_level(&mut self, other: &mut Self) {
std::mem::swap(&mut self.index, &mut other.index);
std::mem::swap(&mut self.known, &mut other.known);
}
}
/// An insertion-ordered set of block positions (`Level.blockEntityTickers`
/// keeps the order block entities were added in).
#[derive(Default)]
+141 -118
View File
@@ -1,59 +1,81 @@
//! A server's player between dimensions.
//! A server's players 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.
//! A server holds a level per dimension (game/levels.rs). A player who steps
//! into a Nether or End portal moves to the destination's level, which opens
//! if nobody was there: the swap is the in-frame path's portal plans and
//! arrival search, and 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 around them.
use super::nether_portal::PLAYER_DELAY;
use super::nether_portal::{PLAYER_DELAY, Plan};
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`.
/// A trip under way: the player is in the destination's level, whose
/// chunks are loading around `target`.
pub(super) struct Trip {
conn: u32,
dim: Dim,
target: Vec3,
/// Through an End portal (or out of the End by respawning).
/// Through an End portal.
end: bool,
/// The Nether portal plan, whose exit is found or built on arrival.
plan: Option<Plan>,
}
/// The lone player's box: Player's standing dimensions.
/// A player's box: Player's standing dimensions.
const WIDTH: f64 = 0.6;
const HEIGHT: f64 = 1.8;
impl Trip {
pub(super) fn is(&self, conn: u32) -> bool {
self.conn == conn
}
}
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)
self.server_trips.iter().any(|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.
/// Per server tick in each level, after the guests' own: the arrivals of
/// the trips into this level, then `Entity.handlePortal` for each player
/// in it (Nether portals count up their transition time, End portals
/// take them at once).
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;
self.arrive_server_trips(host);
let conns: Vec<u32> = host
.hub
.guests
.iter()
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.map(|g| g.conn)
.collect();
for conn in conns {
if self.on_server_trip(conn) {
continue;
}
// `Entity.portalProcess` and `portalCooldown` are the player's own.
let mut portal = host.play.entry(conn).or_default().portal;
std::mem::swap(&mut self.portals.player, &mut portal);
self.handle_server_portal(host, conn);
std::mem::swap(&mut self.portals.player, &mut portal);
host.play.entry(conn).or_default().portal = portal;
}
let [g] = host.hub.guests.as_slice() else {
}
/// `Entity.handlePortal` for one player, whose portal state is in place.
fn handle_server_portal(&mut self, host: &mut LanHost, conn: u32) {
let Some(g) = host.hub.guest(conn) else {
return;
};
if !g.placed || !g.loaded || g.dead || g.spectator() {
return;
}
let (conn, at, invulnerable, sleeping) = (
g.conn,
let (at, invulnerable, sleeping) = (
Vec3::new(g.position[0], g.position[1], g.position[2]),
g.creative(),
g.sleeping,
@@ -70,7 +92,7 @@ impl Game<'_> {
} else {
Dim::End
};
self.start_server_trip(host, conn, target, true);
self.start_server_trip(host, conn, target, None);
}
// Entity.setAsInsidePortal while cooling down restarts the cooldown.
self.portals.player.cooldown = 10;
@@ -93,11 +115,10 @@ impl Game<'_> {
if !self.may_enter(plan.dim) {
return;
}
self.portals.travel = Some(plan);
self.start_server_trip(host, conn, plan.dim, false);
self.start_server_trip(host, conn, plan.dim, Some(plan));
}
/// A Nether portal block the lone player's box is in.
/// A Nether portal block a 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];
@@ -114,9 +135,16 @@ impl Game<'_> {
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) {
/// The player moves to `target`'s level (opened if nobody was there)
/// and is told it is there, at the approximate exit, while it loads. The
/// level whose tick is running is put back in place afterwards.
fn start_server_trip(
&mut self,
host: &mut LanHost,
conn: u32,
target: Dim,
plan: Option<Plan>,
) {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
@@ -124,105 +152,100 @@ impl Game<'_> {
let from = Vec3::new(g.position[0], g.position[1], g.position[2]);
let yaw = g.yaw;
let source = self.dim;
let end = plan.is_none();
// Coordinates scale by 8 between the Overworld and the Nether; an
// End portal has fixed destinations.
let scale = match (source, target) {
(Dim::Overworld, Dim::Nether) | (Dim::End, Dim::Nether) => 1.0 / 8.0,
(Dim::Nether, Dim::Overworld) => 8.0,
_ => 1.0,
};
self.end_portal_travel = end;
let switched = self.switch_level(target, from);
let scaled = self.end_destination(target).unwrap_or(Vec3::new(
from.x * scale,
from.y,
from.z * scale,
));
self.end_portal_travel = false;
let destination = match switched {
Ok(d) => d,
Err(e) => {
log::error!("could not open {}: {e}", target.id());
return;
}
if let Err(e) = self.enter_level(Some(host), target) {
log::error!("could not open {}: {e}", target.id());
return;
}
let destination = match plan {
Some(plan) => self.arrival_centre(&plan),
None => scaled,
};
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 {
self.server_trips.push(Trip {
conn,
dim: target,
target: destination,
end,
plan,
});
if let Err(e) = self.enter_level(Some(host), source) {
log::error!("could not reopen {}: {e}", source.id());
}
}
/// 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)
}
/// The trips into the level in place whose destination has loaded
/// around their target: the exit (the Nether portal found or built, the
/// End platform, the Overworld's spawn column) and the teleport there.
fn arrive_server_trips(&mut self, host: &mut LanHost) {
let mut k = 0;
while k < self.server_trips.len() {
let trip = &self.server_trips[k];
let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else {
// They left on the way.
self.server_trips.remove(k);
continue;
};
let (cx, cz) = (
(trip.target.x.floor() as i32) >> 4,
(trip.target.z.floor() as i32) >> 4,
);
if trip.dim != self.dim
|| !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz)))
{
k += 1;
continue;
}
} 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)
let trip = self.server_trips.remove(k);
self.resolve_arrivals();
let yaw = host.hub.guests[i].yaw;
let (position, yaw) = if trip.end {
match self.end_arrival(trip.target) {
Ok((at, turned)) => (at, turned.unwrap_or(yaw)),
Err(e) => {
log::error!("End arrival: {e}");
(trip.target, yaw)
}
}
_ => (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;
} else {
let exit = trip
.plan
.as_ref()
.and_then(|plan| self.nether_exit_portal(plan));
match (trip.plan, exit) {
(Some(plan), Some(exit)) => {
let (at, rotation) = self.arrival(&plan, exit);
(at, yaw + rotation)
}
_ => (trip.target, yaw),
}
};
// Player.getDimensionChangingDelay.
host.play.entry(trip.conn).or_default().portal.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]));
}
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.
+2 -2
View File
@@ -25,7 +25,7 @@ impl Hub {
for g in self
.guests
.iter()
.filter(|g| g.placed && Some(g.conn) != except)
.filter(|g| self.here(g) && Some(g.conn) != except)
{
let d: f64 = (0..3).map(|k| (g.position[k] - at[k]).powi(2)).sum();
if d <= range * range {
@@ -464,7 +464,7 @@ impl Hub {
let Some(menu) = self.guests[i]
.menu
.as_ref()
.filter(|_| self.guests[i].placed)
.filter(|_| self.here(&self.guests[i]))
else {
continue;
};
+4
View File
@@ -131,6 +131,9 @@ pub struct Guest {
pub dead: bool,
/// The join packets were sent (PlayerList.placeNewPlayer ran).
pub placed: bool,
/// The level the player is in (`ServerPlayer.level().dimension()`): the
/// hub's level passes only reach the players in theirs.
pub dimension: String,
/// The open block container, if any.
pub menu: Option<super::menu::Menu>,
pub next_window: i32,
@@ -226,6 +229,7 @@ impl Guest {
moves_from_ground: false,
dead: false,
placed: false,
dimension: "minecraft:overworld".into(),
menu: None,
next_window: 0,
drag: None,
+97 -16
View File
@@ -112,6 +112,9 @@ pub struct Hub {
last_rate: f32,
ticking: (f32, bool),
weather: (bool, f32, f32),
/// The clock and weather last sent in the levels not in place, by
/// dimension (`set_dimension` swaps them with the fields above).
level_sync: std::collections::HashMap<String, LevelSync>,
/// Operators and their permission levels (dedicated servers).
pub ops: std::collections::HashMap<u128, u8>,
chat_type: i32,
@@ -180,6 +183,24 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool {
dx * dx + dz * dz < i64::from(r) * i64::from(r)
}
/// What a level's players were last told of its clock and weather.
#[derive(Clone, Copy)]
struct LevelSync {
last_clock: i64,
last_rate: f32,
weather: (bool, f32, f32),
}
impl Default for LevelSync {
fn default() -> Self {
Self {
last_clock: i64::MIN,
last_rate: 0.0,
weather: (false, 0.0, 0.0),
}
}
}
impl Hub {
pub fn new(lan: Lan, sync: Arc<SyncData>, encoder: ChunkEncoder, config: HubConfig) -> Self {
let chat_type = sync
@@ -204,6 +225,7 @@ impl Hub {
ticking: (20.0, false),
ops: Default::default(),
weather: (false, 0.0, 0.0),
level_sync: Default::default(),
chat_type,
dimension_type,
clock_ids,
@@ -257,6 +279,18 @@ impl Hub {
g.sender.send(body.clone());
}
}
/// Whether a guest is placed in the level in place (`config.dimension`).
pub fn here(&self, g: &Guest) -> bool {
g.placed && g.dimension == self.config.dimension
}
/// `PlayerList.broadcastAll(packet, dimension)`: the players in the
/// level in place.
pub fn broadcast_level(&self, packet: &C) {
let body = packet.encode();
for g in self.guests.iter().filter(|g| self.here(g)) {
g.sender.send(body.clone());
}
}
pub fn broadcast_except(&self, conn: u32, packet: &C) {
let body = packet.encode();
for g in self.guests.iter().filter(|g| g.placed && g.conn != conn) {
@@ -448,6 +482,7 @@ impl Hub {
guest.joined_tick = self.ticks;
guest.position = ctx.spawn;
guest.previous_position = ctx.spawn;
guest.dimension = self.config.dimension.clone();
self.guests.push(guest);
conn
}
@@ -857,7 +892,19 @@ impl Hub {
// ---- per tick ------------------------------------------------------
/// A whole tick with one level: the network, the level, then the
/// players' latencies.
pub fn tick(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
let mut events = self.poll(ctx);
events.extend(self.tick_level(ctx));
self.end_tick();
events
}
/// The network since the last tick, once per server tick before any
/// level ticks: joins (into the level in place), leaves, and each guest's
/// packets queued for its own level's pass.
pub fn poll(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
self.ticks += 1;
let mut events = Vec::new();
for event in self.lan.poll() {
@@ -893,13 +940,25 @@ impl Hub {
}
}
}
events
}
/// The level in place's part of the tick (`ServerLevel.tick`'s chunk
/// map and the connections of the players in it): their packets, then
/// the chunks, block changes, containers and entities they see.
pub fn tick_level(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
let mut events = Vec::new();
for i in 0..self.guests.len() {
if self.guests[i].placed {
if self.here(&self.guests[i]) {
self.process_inbox(i, ctx, &mut events);
}
}
if !self.guests.iter().any(|g| g.placed) {
if self.guests.is_empty() {
if !self.guests.iter().any(|g| self.here(g)) {
if !self
.guests
.iter()
.any(|g| g.dimension == self.config.dimension)
{
let _ = ctx.world.block_log.take();
}
return events;
@@ -909,7 +968,7 @@ impl Hub {
}
self.sync_world(ctx);
for i in 0..self.guests.len() {
if self.guests[i].placed {
if self.here(&self.guests[i]) {
self.update_chunks(i, ctx);
}
}
@@ -917,7 +976,7 @@ impl Hub {
// ServerGamePacketListenerImpl.tick: the actions handled since the last tick are
// acknowledged after the block changes they made were sent, so a client's predicted
// blocks settle on the server's states.
for g in &self.guests {
for g in self.guests.iter().filter(|g| self.here(g)) {
let sequence = g.ack_up_to.replace(-1);
if sequence >= 0 {
g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence }));
@@ -926,11 +985,16 @@ impl Hub {
self.sync_containers(ctx.world);
self.track_entities(ctx);
for i in 0..self.guests.len() {
if self.guests[i].placed {
if self.here(&self.guests[i]) {
self.sync_player_state(i);
self.sync_effects(i);
}
}
events
}
/// After every level: `PlayerList.tick`.
pub fn end_tick(&mut self) {
let latencies: Vec<_> = self
.guests
.iter()
@@ -952,7 +1016,6 @@ impl Hub {
entries,
}));
}
events
}
fn remove_guest(&mut self, i: usize, reason: &str) -> Guest {
@@ -983,7 +1046,7 @@ impl Hub {
// MinecraftServer.tickServer: the game time every 20 ticks
// (forceGameTimeSynchronization, no clocks).
if self.ticks.is_multiple_of(20) {
self.broadcast(&C::SetTime(play::SetTime {
self.broadcast_level(&C::SetTime(play::SetTime {
game_time: world.game_time,
clocks: Vec::new(),
}));
@@ -999,7 +1062,7 @@ impl Hub {
.sync
.id("minecraft:world_clock", "minecraft:overworld")
.unwrap_or(0);
self.broadcast(&C::SetTime(play::SetTime {
self.broadcast_level(&C::SetTime(play::SetTime {
game_time: world.game_time,
clocks: vec![play::ClockState {
clock: overworld,
@@ -1018,7 +1081,7 @@ impl Hub {
let w = &world.weather;
let (raining, rain, thunder) = self.weather;
if w.raining != raining {
self.broadcast(&C::GameEvent(play::GameEvent {
self.broadcast_level(&C::GameEvent(play::GameEvent {
event: if w.raining {
game_event::START_RAINING
} else {
@@ -1028,13 +1091,13 @@ impl Hub {
}));
}
if (w.rain_level.1 - rain).abs() > f32::EPSILON {
self.broadcast(&C::GameEvent(play::GameEvent {
self.broadcast_level(&C::GameEvent(play::GameEvent {
event: game_event::RAIN_LEVEL,
param: w.rain_level.1,
}));
}
if (w.thunder_level.1 - thunder).abs() > f32::EPSILON {
self.broadcast(&C::GameEvent(play::GameEvent {
self.broadcast_level(&C::GameEvent(play::GameEvent {
event: game_event::THUNDER_LEVEL,
param: w.thunder_level.1,
}));
@@ -1164,7 +1227,7 @@ impl Hub {
for ((sx, sy, sz), positions) in sections {
let viewers: Vec<usize> = (0..self.guests.len())
.filter(|&i| {
self.guests[i].placed && self.guests[i].sent_chunks.contains(&(sx, sz))
self.here(&self.guests[i]) && self.guests[i].sent_chunks.contains(&(sx, sz))
})
.collect();
if viewers.is_empty() {
@@ -1329,7 +1392,7 @@ impl Hub {
));
}
let placed: Vec<usize> = (0..self.guests.len())
.filter(|&i| self.guests[i].placed)
.filter(|&i| self.here(&self.guests[i]))
.collect();
let guest_states: Vec<_> = placed
.into_iter()
@@ -1363,7 +1426,7 @@ impl Hub {
let by_id: std::collections::HashMap<i32, usize> =
all.iter().enumerate().map(|(i, e)| (e.id, i)).collect();
for gi in 0..self.guests.len() {
if !self.guests[gi].placed {
if !self.here(&self.guests[gi]) {
continue;
}
let view = self.guests[gi].view_distance;
@@ -1772,12 +1835,15 @@ impl Hub {
let mode = self.guests[i].game_mode;
let mut info = self.spawn_info(mode);
// Player.getLastDeathLocation, set where the player died.
// The level they died in: theirs until now.
info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos {
dimension: self.config.dimension.clone(),
dimension: self.guests[i].dimension.clone(),
pos,
});
self.close_container_for(i);
let g = &mut self.guests[i];
// PlayerList.respawn: into the level in place (the respawn level).
g.dimension = self.config.dimension.clone();
// ServerLevel.removePlayerImmediately: every entity paired with the dead player is
// removed (ServerEntity.removePairing, one packet each). Its chunks are dropped
// without ForgetLevelChunk (PlayerChunkSender.dropChunk skips dead players): the
@@ -1846,6 +1912,20 @@ impl Hub {
/// 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) {
if self.config.dimension == dimension {
return;
}
// What this level's players were told stays with it.
let leaving = LevelSync {
last_clock: self.last_clock,
last_rate: self.last_rate,
weather: self.weather,
};
let entering = self.level_sync.remove(dimension).unwrap_or_default();
self.level_sync
.insert(std::mem::take(&mut self.config.dimension), leaving);
(self.last_clock, self.last_rate, self.weather) =
(entering.last_clock, entering.last_rate, entering.weather);
self.config.dimension = dimension.to_owned();
self.dimension_type = self
.sync
@@ -1865,6 +1945,7 @@ impl Hub {
let info = self.spawn_info(mode);
self.close_container_for(i);
let g = &mut self.guests[i];
g.dimension = self.config.dimension.clone();
g.tracker.clear();
g.sent_chunks.clear();
g.chunk_queue.clear();
+5 -1
View File
@@ -71,6 +71,10 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.saved = level.player_extra.clone();
guest.recipe_book = level.recipe_book.clone();
guest.dimension = match level.dimension.as_str() {
d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(),
_ => "minecraft:overworld".to_owned(),
};
if level.ender_items.len() == 27 {
guest.ender_items = level.ender_items.clone();
}
@@ -100,7 +104,6 @@ pub fn apply(guest: &mut Guest, level: &Level) {
pub fn save(guest: &Guest, world: &Path) {
let mut level = Level {
player_uuid: Some(uuid_ints(guest.uuid)),
dimension: "minecraft:overworld".into(),
..Level::default()
};
store(guest, &mut level);
@@ -114,6 +117,7 @@ pub fn save(guest: &Guest, world: &Path) {
/// Put a guest's state in `level`'s player fields.
pub fn store(guest: &Guest, level: &mut Level) {
level.position = Some(guest.position);
level.dimension = guest.dimension.clone();
level.rotation = [guest.yaw, guest.pitch];
level.health = guest.health;
level.food = guest.food;