veloren/voxygen/src/session.rs

581 lines
25 KiB
Rust
Raw Normal View History

use crate::{
2020-01-10 00:33:38 +00:00
ecs::MyEntity,
hud::{DebugInfo, Event as HudEvent, Hud},
key_state::KeyState,
render::Renderer,
2019-08-26 11:11:37 +00:00
scene::Scene,
2019-07-26 02:28:53 +00:00
window::{Event, GameInput},
Direction, Error, GlobalState, PlayState, PlayStateResult,
};
use client::{self, Client, Event::Chat};
2019-08-06 21:51:13 +00:00
use common::{
clock::Clock,
comp,
2020-01-08 19:31:42 +00:00
comp::{ActionState, Pos, Vel},
msg::ClientState,
terrain::{Block, BlockKind},
vol::ReadVol,
2019-10-17 05:14:20 +00:00
ChatType,
2019-08-06 21:51:13 +00:00
};
2019-07-26 02:28:53 +00:00
use log::error;
2019-11-30 06:41:20 +00:00
use specs::{Join, WorldExt};
use std::{cell::RefCell, rc::Rc, time::Duration};
use vek::*;
pub struct SessionState {
scene: Scene,
client: Rc<RefCell<Client>>,
hud: Hud,
2019-06-09 14:20:20 +00:00
key_state: KeyState,
inputs: comp::ControllerInputs,
2019-07-04 19:59:57 +00:00
selected_block: Block,
}
/// Represents an active game session (i.e., the one being played).
impl SessionState {
/// Create a new `SessionState`.
2019-07-26 02:28:53 +00:00
pub fn new(global_state: &mut GlobalState, client: Rc<RefCell<Client>>) -> Self {
// Create a scene for this session. The scene handles visible elements of the game world.
2019-08-05 16:37:52 +00:00
let mut scene = Scene::new(global_state.window.renderer_mut());
scene
.camera_mut()
.set_fov_deg(global_state.settings.graphics.fov);
let hud = Hud::new(global_state, &client.borrow());
2020-01-10 00:33:38 +00:00
{
let my_entity = client.borrow().entity();
client
.borrow_mut()
.state_mut()
.ecs_mut()
.insert(MyEntity(my_entity));
}
Self {
scene,
2019-01-15 15:13:11 +00:00
client,
key_state: KeyState::new(),
inputs: comp::ControllerInputs::default(),
hud,
selected_block: Block::new(BlockKind::Normal, Rgb::broadcast(255)),
}
}
}
impl SessionState {
/// Tick the session (and the client attached to it).
2019-06-09 14:20:20 +00:00
fn tick(&mut self, dt: Duration) -> Result<(), Error> {
2019-11-29 15:20:35 +00:00
self.inputs.tick(dt);
2020-01-10 00:33:38 +00:00
for event in self.client.borrow_mut().tick(
self.inputs.clone(),
dt,
crate::ecs::sys::add_local_systems,
)? {
match event {
Chat {
2019-07-17 22:10:42 +00:00
chat_type: _,
message: _,
} => {
self.hud.new_message(event);
}
client::Event::Disconnect => {} // TODO
client::Event::DisconnectionNotification(time) => {
let message = match time {
0 => String::from("Goodbye!"),
_ => format!("Connection lost. Kicking in {} seconds", time),
};
self.hud.new_message(Chat {
chat_type: ChatType::Meta,
message,
});
}
}
}
2019-01-14 15:47:57 +00:00
Ok(())
}
/// Clean up the session (and the client attached to it) after a tick.
2019-01-23 20:01:58 +00:00
pub fn cleanup(&mut self) {
self.client.borrow_mut().cleanup();
2019-01-23 20:01:58 +00:00
}
/// Render the session to the screen.
///
/// This method should be called once per frame.
pub fn render(&mut self, renderer: &mut Renderer) {
// Clear the screen
2019-07-04 12:02:26 +00:00
renderer.clear();
// Render the screen using the global renderer
self.scene.render(renderer, &mut self.client.borrow_mut());
// Draw the UI to the screen
self.hud.render(renderer, self.scene.globals());
// Finish the frame
renderer.flush();
}
}
impl PlayState for SessionState {
fn play(&mut self, _: Direction, global_state: &mut GlobalState) -> PlayStateResult {
// Trap the cursor.
global_state.window.grab_cursor(true);
// Set up an fps clock.
let mut clock = Clock::start();
self.client.borrow_mut().clear_terrain();
// Send startup commands to the server
if global_state.settings.send_logon_commands {
for cmd in &global_state.settings.logon_commands {
self.client.borrow_mut().send_chat(cmd.to_string());
}
}
// Game loop
let mut current_client_state = self.client.borrow().get_client_state();
while let ClientState::Pending | ClientState::Character = current_client_state {
2019-08-24 17:58:28 +00:00
// Compute camera data
let (view_mat, _, cam_pos) = self
.scene
.camera()
.compute_dependents(&self.client.borrow());
let cam_dir: Vec3<f32> = Vec3::from(view_mat.inverted() * -Vec4::unit_z());
2019-09-26 10:43:03 +00:00
// Check to see whether we're aiming at anything
let (build_pos, select_pos) = {
let client = self.client.borrow();
let terrain = client.state().terrain();
let ray = terrain
.ray(cam_pos, cam_pos + cam_dir * 100.0)
2019-09-26 13:03:41 +00:00
.until(|block| block.is_tangible())
2019-09-26 10:43:03 +00:00
.cast();
let dist = ray.0;
if let Ok(Some(_)) = ray.1 {
// Hit something!
(
Some((cam_pos + cam_dir * (dist - 0.01)).map(|e| e.floor() as i32)),
2019-09-26 10:43:03 +00:00
Some((cam_pos + cam_dir * dist).map(|e| e.floor() as i32)),
)
} else {
(None, None)
}
};
self.scene.set_select_pos(select_pos);
// Handle window events.
for event in global_state.window.fetch_events() {
// Pass all events to the ui first.
if self.hud.handle_event(event.clone(), global_state) {
continue;
}
match event {
Event::Close => {
return PlayStateResult::Shutdown;
}
Event::InputUpdate(GameInput::Primary, state) => {
2019-07-03 17:55:56 +00:00
// Check the existence of CanBuild component. If it's here, use LMB to
// place blocks, if not, use it to attack
2019-07-04 18:14:14 +00:00
let mut client = self.client.borrow_mut();
if state
&& client
.state()
.read_storage::<comp::CanBuild>()
.get(client.entity())
.is_some()
2019-07-04 18:14:14 +00:00
{
2019-09-26 10:43:03 +00:00
if let Some(build_pos) = build_pos {
client.place_block(build_pos, self.selected_block);
2019-07-03 17:55:56 +00:00
}
} else {
2019-11-29 15:20:35 +00:00
self.inputs.primary.set_state(state);
2019-07-03 17:55:56 +00:00
}
}
2019-07-04 18:14:14 +00:00
Event::InputUpdate(GameInput::Secondary, state) => {
2019-11-29 15:20:35 +00:00
self.inputs.secondary.set_state(false); // To be changed later on
let mut client = self.client.borrow_mut();
if state
&& client
.state()
.read_storage::<comp::CanBuild>()
.get(client.entity())
.is_some()
{
2019-09-26 10:43:03 +00:00
if let Some(select_pos) = select_pos {
client.remove_block(select_pos);
2019-06-30 20:25:37 +00:00
}
} else if client
.state()
.read_storage::<comp::CharacterState>()
.get(client.entity())
2020-01-08 19:31:42 +00:00
.map(|cs| match cs.action_state {
ActionState::Attack(_)
| ActionState::Block(_)
| ActionState::Wield(_) => true,
_ => false,
})
.unwrap_or(false)
{
2019-11-29 15:20:35 +00:00
self.inputs.secondary.set_state(state);
} else {
2019-09-26 10:43:03 +00:00
if let Some(select_pos) = select_pos {
client.collect_block(select_pos);
}
2019-06-30 20:25:37 +00:00
}
}
2019-06-11 04:08:55 +00:00
Event::InputUpdate(GameInput::Roll, state) => {
2019-07-04 19:59:57 +00:00
let client = self.client.borrow();
if client
.state()
.read_storage::<comp::CanBuild>()
.get(client.entity())
.is_some()
{
if state {
2019-09-26 10:43:03 +00:00
if let Some(block) = select_pos
.and_then(|sp| client.state().terrain().get(sp).ok().copied())
2019-07-07 04:37:22 +00:00
{
2019-09-26 10:43:03 +00:00
self.selected_block = block;
2019-07-04 19:59:57 +00:00
}
}
} else {
2019-11-29 15:20:35 +00:00
self.inputs.roll.set_state(state);
2019-07-04 19:59:57 +00:00
}
2019-06-11 04:08:55 +00:00
}
Event::InputUpdate(GameInput::Respawn, state) => {
2019-11-29 15:20:35 +00:00
self.inputs.respawn.set_state(state);
}
2019-06-09 14:20:20 +00:00
Event::InputUpdate(GameInput::Jump, state) => {
2019-11-29 15:20:35 +00:00
self.inputs.jump.set_state(state);
}
Event::InputUpdate(GameInput::Sit, state) => {
2019-11-29 15:20:35 +00:00
self.inputs.sit.set_state(state);
}
Event::InputUpdate(GameInput::MoveForward, state) => self.key_state.up = state,
Event::InputUpdate(GameInput::MoveBack, state) => self.key_state.down = state,
Event::InputUpdate(GameInput::MoveLeft, state) => self.key_state.left = state,
Event::InputUpdate(GameInput::MoveRight, state) => self.key_state.right = state,
Event::InputUpdate(GameInput::Glide, state) => {
2019-11-29 15:20:35 +00:00
self.inputs.glide.set_state(state);
}
Event::InputUpdate(GameInput::Climb, state) => {
self.inputs.climb.set_state(state)
}
Event::InputUpdate(GameInput::ClimbDown, state) => {
2019-11-29 15:20:35 +00:00
self.inputs.climb_down.set_state(state)
}
Event::InputUpdate(GameInput::WallLeap, state) => {
self.inputs.wall_leap.set_state(state)
}
Event::InputUpdate(GameInput::Mount, true) => {
let mut client = self.client.borrow_mut();
if client.is_mounted() {
client.unmount();
} else {
let player_pos = client
.state()
.read_storage::<comp::Pos>()
.get(client.entity())
.copied();
if let Some(player_pos) = player_pos {
// Find closest mountable entity
let closest_mountable = (
&client.state().ecs().entities(),
&client.state().ecs().read_storage::<comp::Pos>(),
&client.state().ecs().read_storage::<comp::MountState>(),
)
.join()
.filter(|(_, _, ms)| {
if let comp::MountState::Unmounted = ms {
true
} else {
false
}
})
.min_by_key(|(_, pos, _)| {
(player_pos.0.distance_squared(pos.0) * 1000.0) as i32
})
.map(|(uid, _, _)| uid);
if let Some(mountee_entity) = closest_mountable {
client.mount(mountee_entity);
}
}
}
}
Event::InputUpdate(GameInput::Interact, state) => {
let mut client = self.client.borrow_mut();
let player_pos = client
.state()
.read_storage::<comp::Pos>()
.get(client.entity())
.copied();
if let (Some(player_pos), true) = (player_pos, state) {
let entity = (
&client.state().ecs().entities(),
&client.state().ecs().read_storage::<comp::Pos>(),
&client.state().ecs().read_storage::<comp::Item>(),
)
.join()
.filter(|(_, pos, _)| {
pos.0.distance_squared(player_pos.0) < 3.0 * 3.0
})
.min_by_key(|(_, pos, _)| {
(pos.0.distance_squared(player_pos.0) * 1000.0) as i32
})
.map(|(entity, _, _)| entity);
if let Some(entity) = entity {
client.pick_up(entity);
}
}
}
2019-11-29 15:20:35 +00:00
Event::InputUpdate(GameInput::ToggleWield, state) => {
self.inputs.toggle_wield.set_state(state)
}
Event::InputUpdate(GameInput::Charge, state) => {
self.inputs.charge.set_state(state);
}
// Pass all other events to the scene
event => {
self.scene.handle_input_event(event);
} // TODO: Do something if the event wasn't handled?
}
}
2019-06-09 14:20:20 +00:00
// Calculate the movement input vector of the player from the current key presses
// and the camera direction.
let ori = self.scene.camera().get_orientation();
let unit_vecs = (
Vec2::new(ori[0].cos(), -ori[0].sin()),
Vec2::new(ori[0].sin(), ori[0].cos()),
);
let dir_vec = self.key_state.dir_vec();
self.inputs.move_dir = unit_vecs.0 * dir_vec[0] + unit_vecs.1 * dir_vec[1];
2019-06-09 14:20:20 +00:00
self.inputs.look_dir = cam_dir;
2019-08-24 17:58:28 +00:00
// Perform an in-game tick.
if let Err(err) = self.tick(clock.get_avg_delta()) {
global_state.info_message = Some(
"Connection lost!\nDid the server restart?\nIs the client up to date?"
.to_owned(),
);
error!("[session] Failed to tick the scene: {:?}", err);
return PlayStateResult::Pop;
}
// Maintain global state.
2019-08-31 08:30:23 +00:00
global_state.maintain(clock.get_last_delta().as_secs_f32());
// Extract HUD events ensuring the client borrow gets dropped.
let hud_events = self.hud.maintain(
&self.client.borrow(),
global_state,
DebugInfo {
tps: clock.get_tps(),
ping_ms: self.client.borrow().get_ping_ms(),
coordinates: self
.client
.borrow()
.state()
.ecs()
.read_storage::<Pos>()
.get(self.client.borrow().entity())
.cloned(),
2019-08-06 21:51:13 +00:00
velocity: self
.client
.borrow()
.state()
.ecs()
.read_storage::<Vel>()
.get(self.client.borrow().entity())
.cloned(),
num_chunks: self.scene.terrain().chunk_count() as u32,
num_visible_chunks: self.scene.terrain().visible_chunk_count() as u32,
num_figures: self.scene.figure_mgr().figure_count() as u32,
num_figures_visible: self.scene.figure_mgr().figure_count_visible() as u32,
},
&self.scene.camera(),
clock.get_last_delta(),
);
// Maintain the UI.
for event in hud_events {
match event {
HudEvent::SendMessage(msg) => {
// TODO: Handle result
self.client.borrow_mut().send_chat(msg);
}
HudEvent::CharacterSelection => {
self.client.borrow_mut().request_remove_character()
}
HudEvent::Logout => self.client.borrow_mut().request_logout(),
HudEvent::Quit => {
return PlayStateResult::Shutdown;
}
HudEvent::AdjustMousePan(sensitivity) => {
global_state.window.pan_sensitivity = sensitivity;
global_state.settings.gameplay.pan_sensitivity = sensitivity;
2019-07-26 02:28:53 +00:00
global_state.settings.save_to_file_warn();
}
HudEvent::AdjustMouseZoom(sensitivity) => {
global_state.window.zoom_sensitivity = sensitivity;
global_state.settings.gameplay.zoom_sensitivity = sensitivity;
2019-07-26 02:28:53 +00:00
global_state.settings.save_to_file_warn();
}
HudEvent::ToggleZoomInvert(zoom_inverted) => {
global_state.window.zoom_inversion = zoom_inverted;
global_state.settings.gameplay.zoom_inversion = zoom_inverted;
global_state.settings.save_to_file_warn();
}
2020-01-10 00:33:38 +00:00
HudEvent::Sct(sct) => {
global_state.settings.gameplay.sct = sct;
global_state.settings.save_to_file_warn();
}
HudEvent::SctPlayerBatch(sct_player_batch) => {
global_state.settings.gameplay.sct_player_batch = sct_player_batch;
global_state.settings.save_to_file_warn();
}
HudEvent::SctDamageBatch(sct_damage_batch) => {
global_state.settings.gameplay.sct_damage_batch = sct_damage_batch;
global_state.settings.save_to_file_warn();
}
HudEvent::ToggleDebug(toggle_debug) => {
global_state.settings.gameplay.toggle_debug = toggle_debug;
global_state.settings.save_to_file_warn();
}
2019-12-06 22:49:17 +00:00
HudEvent::ToggleMouseYInvert(mouse_y_inverted) => {
global_state.window.mouse_y_inversion = mouse_y_inverted;
global_state.settings.gameplay.mouse_y_inversion = mouse_y_inverted;
global_state.settings.save_to_file_warn();
}
HudEvent::AdjustViewDistance(view_distance) => {
self.client.borrow_mut().set_view_distance(view_distance);
global_state.settings.graphics.view_distance = view_distance;
2019-07-26 02:28:53 +00:00
global_state.settings.save_to_file_warn();
}
2019-07-07 00:15:22 +00:00
HudEvent::CrosshairTransp(crosshair_transp) => {
global_state.settings.gameplay.crosshair_transp = crosshair_transp;
2019-07-26 02:28:53 +00:00
global_state.settings.save_to_file_warn();
2019-07-07 00:15:22 +00:00
}
HudEvent::ChatTransp(chat_transp) => {
global_state.settings.gameplay.chat_transp = chat_transp;
global_state.settings.save_to_file_warn();
}
2019-07-23 01:02:57 +00:00
HudEvent::CrosshairType(crosshair_type) => {
global_state.settings.gameplay.crosshair_type = crosshair_type;
2019-07-26 02:28:53 +00:00
global_state.settings.save_to_file_warn();
}
HudEvent::Intro(intro_show) => {
global_state.settings.gameplay.intro_show = intro_show;
global_state.settings.save_to_file_warn();
}
HudEvent::ToggleXpBar(xp_bar) => {
global_state.settings.gameplay.xp_bar = xp_bar;
global_state.settings.save_to_file_warn();
}
HudEvent::ToggleBarNumbers(bar_numbers) => {
global_state.settings.gameplay.bar_numbers = bar_numbers;
global_state.settings.save_to_file_warn();
}
HudEvent::ToggleShortcutNumbers(shortcut_numbers) => {
global_state.settings.gameplay.shortcut_numbers = shortcut_numbers;
global_state.settings.save_to_file_warn();
}
2019-07-26 02:28:53 +00:00
HudEvent::UiScale(scale_change) => {
global_state.settings.gameplay.ui_scale =
self.hud.scale_change(scale_change);
global_state.settings.save_to_file_warn();
2019-07-23 01:02:57 +00:00
}
HudEvent::AdjustMusicVolume(music_volume) => {
global_state.audio.set_music_volume(music_volume);
2019-07-23 01:02:57 +00:00
global_state.settings.audio.music_volume = music_volume;
global_state.settings.save_to_file_warn();
}
HudEvent::AdjustSfxVolume(sfx_volume) => {
global_state.audio.set_sfx_volume(sfx_volume);
global_state.settings.audio.sfx_volume = sfx_volume;
2019-07-26 02:28:53 +00:00
global_state.settings.save_to_file_warn();
}
HudEvent::ChangeAudioDevice(name) => {
global_state.audio.set_device(name.clone());
global_state.settings.audio.audio_device = Some(name);
2019-07-26 02:28:53 +00:00
global_state.settings.save_to_file_warn();
}
2019-06-06 19:11:39 +00:00
HudEvent::ChangeMaxFPS(fps) => {
global_state.settings.graphics.max_fps = fps;
2019-07-26 02:28:53 +00:00
global_state.settings.save_to_file_warn();
2019-06-06 19:11:39 +00:00
}
HudEvent::UseInventorySlot(x) => self.client.borrow_mut().use_inventory_slot(x),
2019-07-25 22:52:28 +00:00
HudEvent::SwapInventorySlots(a, b) => {
self.client.borrow_mut().swap_inventory_slots(a, b)
}
2019-07-26 17:08:40 +00:00
HudEvent::DropInventorySlot(x) => {
self.client.borrow_mut().drop_inventory_slot(x)
}
2019-08-05 16:37:52 +00:00
HudEvent::ChangeFOV(new_fov) => {
global_state.settings.graphics.fov = new_fov;
global_state.settings.save_to_file_warn();
self.scene.camera_mut().set_fov_deg(new_fov);
}
HudEvent::ChangeAaMode(new_aa_mode) => {
// Do this first so if it crashes the setting isn't saved :)
global_state
.window
.renderer_mut()
.set_aa_mode(new_aa_mode)
.unwrap();
global_state.settings.graphics.aa_mode = new_aa_mode;
global_state.settings.save_to_file_warn();
2019-08-05 16:37:52 +00:00
}
}
}
// Maintain the scene.
2019-09-06 10:38:02 +00:00
self.scene.maintain(
global_state.window.renderer_mut(),
&mut global_state.audio,
&self.client.borrow(),
);
2019-01-23 20:01:58 +00:00
// Render the session.
self.render(global_state.window.renderer_mut());
// Display the frame on the window.
global_state
.window
.swap_buffers()
.expect("Failed to swap window buffers!");
// Wait for the next tick.
2019-06-06 19:11:39 +00:00
clock.tick(Duration::from_millis(
1000 / global_state.settings.graphics.max_fps as u64,
));
2019-01-23 20:01:58 +00:00
// Clean things up after the tick.
2019-01-23 20:01:58 +00:00
self.cleanup();
current_client_state = self.client.borrow().get_client_state();
}
PlayStateResult::Pop
}
fn name(&self) -> &'static str {
"Session"
}
}