Skip to content

Commit

Permalink
Delay Sim creation until server params received
Browse files Browse the repository at this point in the history
This allows Sim to store SimConfig without wrapping it in an Option
  • Loading branch information
patowen authored and Ralith committed Oct 24, 2023
1 parent fd16b9d commit 2b95c8c
Show file tree
Hide file tree
Showing 4 changed files with 146 additions and 147 deletions.
18 changes: 9 additions & 9 deletions client/src/graphics/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use lahar::Staged;
use metrics::histogram;

use super::{fog, voxels, Base, Fog, Frustum, GltfScene, Meshes, Voxels};
use crate::{sim, Asset, Config, Loader, Sim};
use common::math;
use crate::{Asset, Config, Loader, Sim};
use common::proto::{Character, Position};
use common::{math, SimConfig};

/// Manages rendering, independent of what is being rendered to
pub struct Draw {
Expand Down Expand Up @@ -215,12 +215,12 @@ impl Draw {
}

/// Called with server-defined world parameters once they're known
pub fn configure(&mut self, params: &sim::Parameters) {
pub fn configure(&mut self, cfg: &SimConfig) {
let voxels = Voxels::new(
&self.gfx,
self.cfg.clone(),
&mut self.loader,
u32::from(params.cfg.chunk_size),
u32::from(cfg.chunk_size),
PIPELINE_DEPTH,
);
for state in &mut self.states {
Expand Down Expand Up @@ -256,15 +256,15 @@ impl Draw {
/// attachment.
pub unsafe fn draw(
&mut self,
sim: &mut Sim,
mut sim: Option<&mut Sim>,
framebuffer: vk::Framebuffer,
depth_view: vk::ImageView,
extent: vk::Extent2D,
present: vk::Semaphore,
frustum: &Frustum,
) {
let draw_started = Instant::now();
let view = sim.view();
let view = sim.as_ref().map_or_else(Position::origin, |sim| sim.view());
let projection = frustum.projection(1.0e-4);
let view_projection = projection.matrix() * math::mtranspose(&view.local);
self.loader.drive();
Expand Down Expand Up @@ -356,7 +356,7 @@ impl Draw {
.build(),
);

if let Some(ref mut voxels) = self.voxels {
if let (Some(voxels), Some(sim)) = (self.voxels.as_mut(), sim.as_mut()) {
voxels.prepare(
device,
state.voxels.as_mut().unwrap(),
Expand Down Expand Up @@ -434,7 +434,7 @@ impl Draw {
);
}

if let Some(params) = sim.params() {
if let Some(sim) = sim.as_deref() {
for (node, transform) in nearby_nodes(
&sim.graph,
&view,
Expand All @@ -453,7 +453,7 @@ impl Draw {
if let Ok(ch) = sim.world.get::<&Character>(entity) {
let transform = transform
* pos.local
* na::Matrix4::new_scaling(params.cfg.meters_to_absolute)
* na::Matrix4::new_scaling(sim.cfg().meters_to_absolute)
* ch.state.orientation.to_homogeneous();
for mesh in &character_model.0 {
self.meshes
Expand Down
104 changes: 65 additions & 39 deletions client/src/graphics/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{f32, os::raw::c_char};
use ash::{extensions::khr, vk};
use lahar::DedicatedImage;
use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle};
use tracing::info;
use tracing::{error, info};
use winit::{
dpi::PhysicalSize,
event::{
Expand All @@ -16,7 +16,8 @@ use winit::{
};

use super::{Base, Core, Draw, Frustum};
use crate::{Config, Sim};
use crate::Net;
use crate::{net, Config, Sim};

/// OS window
pub struct EarlyWindow {
Expand Down Expand Up @@ -53,7 +54,8 @@ pub struct Window {
swapchain: Option<SwapchainMgr>,
swapchain_needs_update: bool,
draw: Option<Draw>,
sim: Sim,
sim: Option<Sim>,
net: Net,
}

impl Window {
Expand All @@ -63,7 +65,7 @@ impl Window {
core: Arc<Core>,
config: Arc<Config>,
metrics: Arc<crate::metrics::Recorder>,
sim: Sim,
net: Net,
) -> Self {
let surface = unsafe {
ash_window::create_surface(
Expand All @@ -88,7 +90,8 @@ impl Window {
swapchain: None,
swapchain_needs_update: false,
draw: None,
sim,
sim: None,
net,
}
}

Expand Down Expand Up @@ -126,50 +129,49 @@ impl Window {
.unwrap()
.run(move |event, _, control_flow| match event {
Event::MainEventsCleared => {
let this_frame = Instant::now();
let dt = this_frame - last_frame;
let move_direction: na::Vector3<f32> = na::Vector3::x()
* (right as u8 as f32 - left as u8 as f32)
+ na::Vector3::y() * (up as u8 as f32 - down as u8 as f32)
+ na::Vector3::z() * (back as u8 as f32 - forward as u8 as f32);
self.sim
.set_movement_input(if move_direction.norm_squared() > 1.0 {
while let Ok(msg) = self.net.incoming.try_recv() {
self.handle_net(msg);
}

if let Some(sim) = self.sim.as_mut() {
let this_frame = Instant::now();
let dt = this_frame - last_frame;
let move_direction: na::Vector3<f32> = na::Vector3::x()
* (right as u8 as f32 - left as u8 as f32)
+ na::Vector3::y() * (up as u8 as f32 - down as u8 as f32)
+ na::Vector3::z() * (back as u8 as f32 - forward as u8 as f32);
sim.set_movement_input(if move_direction.norm_squared() > 1.0 {
move_direction.normalize()
} else {
move_direction
});

self.sim.rotate(&na::UnitQuaternion::from_axis_angle(
&-na::Vector3::z_axis(),
(clockwise as u8 as f32 - anticlockwise as u8 as f32)
* 2.0
* dt.as_secs_f32(),
));

let had_params = self.sim.params().is_some();

self.sim.step(dt);
last_frame = this_frame;
sim.rotate(&na::UnitQuaternion::from_axis_angle(
&-na::Vector3::z_axis(),
(clockwise as u8 as f32 - anticlockwise as u8 as f32)
* 2.0
* dt.as_secs_f32(),
));

if !had_params {
if let Some(params) = self.sim.params() {
self.draw.as_mut().unwrap().configure(params);
}
sim.step(dt, &mut self.net);
last_frame = this_frame;
}

self.draw();
}
Event::DeviceEvent { event, .. } => match event {
DeviceEvent::MouseMotion { delta } if mouse_captured => {
const SENSITIVITY: f32 = 2e-3;
let rot = na::UnitQuaternion::from_axis_angle(
&na::Vector3::y_axis(),
-delta.0 as f32 * SENSITIVITY,
) * na::UnitQuaternion::from_axis_angle(
&na::Vector3::x_axis(),
-delta.1 as f32 * SENSITIVITY,
);
self.sim.rotate(&rot);
if let Some(sim) = self.sim.as_mut() {
const SENSITIVITY: f32 = 2e-3;
let rot = na::UnitQuaternion::from_axis_angle(
&na::Vector3::y_axis(),
-delta.0 as f32 * SENSITIVITY,
) * na::UnitQuaternion::from_axis_angle(
&na::Vector3::x_axis(),
-delta.1 as f32 * SENSITIVITY,
);
sim.rotate(&rot);
}
}
_ => {}
},
Expand Down Expand Up @@ -231,7 +233,9 @@ impl Window {
down = state == ElementState::Pressed;
}
VirtualKeyCode::V if state == ElementState::Pressed => {
self.sim.toggle_no_clip();
if let Some(sim) = self.sim.as_mut() {
sim.toggle_no_clip();
}
}
VirtualKeyCode::Escape => {
let _ = self.window.set_cursor_grab(CursorGrabMode::None);
Expand All @@ -256,6 +260,28 @@ impl Window {
});
}

fn handle_net(&mut self, msg: net::Message) {
match msg {
net::Message::ConnectionLost(e) => {
error!("connection lost: {}", e);
}
net::Message::Hello(msg) => {
let sim = Sim::new(msg.sim_config, msg.character);
if let Some(draw) = self.draw.as_mut() {
draw.configure(sim.cfg());
}
self.sim = Some(sim);
}
msg => {
if let Some(sim) = self.sim.as_mut() {
sim.handle_net(msg);
} else {
error!("Received game data before ServerHello");
}
}
}
}

/// Draw a new frame
fn draw(&mut self) {
let swapchain = self.swapchain.as_mut().unwrap();
Expand Down Expand Up @@ -292,7 +318,7 @@ impl Window {
let frustum = Frustum::from_vfov(f32::consts::FRAC_PI_4 * 1.2, aspect_ratio);
// Render the frame
draw.draw(
&mut self.sim,
self.sim.as_mut(),
frame.buffer,
frame.depth_view,
swapchain.state.extent,
Expand Down
5 changes: 2 additions & 3 deletions client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
sync::Arc,
};

use client::{graphics, metrics, net, Config, Sim};
use client::{graphics, metrics, net, Config};
use save::Save;

use ash::extensions::khr;
Expand Down Expand Up @@ -65,10 +65,9 @@ fn main() {

// Kick off networking
let net = net::spawn(config.clone());
let sim = Sim::new(net);

// Finish creating the window, including the Vulkan resources used to render to it
let window = graphics::Window::new(window, core.clone(), config, metrics, sim);
let window = graphics::Window::new(window, core.clone(), config, metrics, net);

// Initialize widely-shared graphics resources
let gfx = Arc::new(
Expand Down
Loading

0 comments on commit 2b95c8c

Please sign in to comment.