use super::entity::Surroundings;
use super::ext::PlayerExt;
use super::player::{PlayerState, tick_in};
use super::rules::Rules;
use crate::input::{Packet, Packets, TickInput};
use crate::world::BlockView;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Stage {
WaitingForServer,
WaitingForChunk,
Loaded,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LoadGate {
stage: Stage,
timed_out: bool,
dead: bool,
}
impl Default for LoadGate {
fn default() -> Self {
LoadGate::waiting()
}
}
impl LoadGate {
#[must_use]
pub const fn waiting() -> Self {
LoadGate {
stage: Stage::WaitingForServer,
timed_out: false,
dead: false,
}
}
#[must_use]
pub const fn loaded() -> Self {
LoadGate {
stage: Stage::Loaded,
timed_out: false,
dead: false,
}
}
pub fn level_chunks_load_start(&mut self) {
if self.stage == Stage::WaitingForServer {
self.stage = Stage::WaitingForChunk;
}
}
pub fn time_out(&mut self) {
self.timed_out = true;
}
pub fn player_alive(&mut self, alive: bool) {
self.dead = !alive;
}
#[must_use]
pub fn is_loaded(&self) -> bool {
self.stage == Stage::Loaded
}
pub fn tick(&mut self, p: &PlayerState, section_compiled: bool) -> bool {
if self.stage != Stage::WaitingForChunk {
return false;
}
let y = p.pos[1].floor();
let outside =
y < f64::from(p.level.min_y) || y >= f64::from(p.level.min_y + p.level.height);
if self.timed_out || outside || p.spectator || self.dead || section_compiled {
self.stage = Stage::Loaded;
return true;
}
false
}
pub fn step<R: Rules, W: BlockView<State = R::State>>(
&mut self,
p: &mut PlayerState,
input: &TickInput,
world: &W,
section_compiled: bool,
out: &mut Packets,
) {
let mut x = PlayerExt::default();
self.step_ext::<R, W>(p, &mut x, input, world, section_compiled, out);
}
pub fn step_ext<R: Rules, W: BlockView<State = R::State>>(
&mut self,
p: &mut PlayerState,
x: &mut PlayerExt,
input: &TickInput,
world: &W,
section_compiled: bool,
out: &mut Packets,
) {
self.step_in::<R, W>(
p,
x,
&Surroundings::default(),
input,
world,
section_compiled,
out,
);
}
#[allow(clippy::too_many_arguments)]
pub fn step_in<R: Rules, W: BlockView<State = R::State>>(
&mut self,
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
input: &TickInput,
world: &W,
section_compiled: bool,
out: &mut Packets,
) {
let was_loaded = self.is_loaded();
if self.tick(p, section_compiled) {
out.push(Packet::PlayerLoaded);
}
if !self.is_loaded() {
p.age += 1;
return;
}
if was_loaded {
tick_in::<R, W>(p, x, around, input, world, out);
} else {
let still = TickInput {
yaw: p.yaw,
pitch: p.pitch,
..*input
};
tick_in::<R, W>(p, x, around, &still, world, out);
}
}
}