Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions client/src/graphics/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,11 @@ impl Window {
sim.toggle_no_clip();
}
}
KeyCode::KeyB if state == ElementState::Pressed => {
if let Some(sim) = self.sim.as_mut() {
sim.debug_spawn_blinker();
}
}
KeyCode::F1 if state == ElementState::Pressed => {
self.gui_state.toggle_gui();
}
Expand Down
2 changes: 1 addition & 1 deletion client/src/local_character_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use common::{math, proto::Position};
pub struct LocalCharacterController {
/// The last extrapolated inter-frame view position, used for rendering and gravity-specific
/// orientation computations
position: Position,
pub position: Position,

/// The up vector relative to position, ignoring orientation
up: na::UnitVector3<f32>,
Expand Down
1 change: 1 addition & 0 deletions client/src/prediction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ mod tests {
movement: na::Vector3::x(),
jump: false,
no_clip: true,
debug_spawn_blinker: false,
block_update: None,
};

Expand Down
13 changes: 13 additions & 0 deletions client/src/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ pub struct Sim {
no_clip: bool,
/// Whether no_clip will be toggled next step
toggle_no_clip: bool,
debug_spawn_blinker: bool,
/// Whether the current step starts with a jump
is_jumping: bool,
/// Whether the jump button has been pressed since the last step
Expand Down Expand Up @@ -100,6 +101,7 @@ impl Sim {
average_movement_input: na::zero(),
no_clip: true,
toggle_no_clip: false,
debug_spawn_blinker: false,
is_jumping: false,
jump_pressed: false,
jump_held: false,
Expand Down Expand Up @@ -144,6 +146,11 @@ impl Sim {
self.toggle_no_clip = true;
}

pub fn debug_spawn_blinker(&mut self) {
// Note: the blinker currently does nothing but update internal state
self.debug_spawn_blinker = true;
}

pub fn set_jump_held(&mut self, jump_held: bool) {
self.jump_held = jump_held;
self.jump_pressed = jump_held || self.jump_pressed;
Expand Down Expand Up @@ -367,6 +374,9 @@ impl Sim {
node = Some(x.node);
builder.add(x);
}
TickerEntity(x) => {
builder.add(x);
}
};
}
let entity = self.world.spawn(builder.build());
Expand All @@ -392,6 +402,7 @@ impl Sim {
movement: sanitize_motion_input(orientation * self.average_movement_input),
jump: self.is_jumping,
no_clip: self.no_clip,
debug_spawn_blinker: self.debug_spawn_blinker,
block_update: self.get_local_character_block_update(),
};
let generation = self
Expand All @@ -404,6 +415,7 @@ impl Sim {
character_input,
orientation: self.local_character_controller.orientation(),
});
self.debug_spawn_blinker = false;
}

fn update_view_position(&mut self) {
Expand All @@ -425,6 +437,7 @@ impl Sim {
/ (self.since_input_sent.as_secs_f32() / self.cfg.step_interval.as_secs_f32()),
jump: self.is_jumping,
no_clip: self.no_clip,
debug_spawn_blinker: self.debug_spawn_blinker,
block_update: None,
};
character_controller::run_character_step(
Expand Down
33 changes: 33 additions & 0 deletions common/src/id_generator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use crate::EntityId;
use fxhash::FxHashMap;
use hecs::Entity;
use rand::rngs::SmallRng;
use rand::{Rng, SeedableRng};

pub struct IDGenerator {
pub rng: SmallRng,
pub entity_ids: FxHashMap<EntityId, Entity>,
}

impl IDGenerator {
pub fn new() -> Self {
Self {
rng: SmallRng::from_entropy(),
entity_ids: FxHashMap::default(),
}
}
pub fn new_id(&mut self) -> EntityId {
loop {
let id = self.rng.gen();
if !self.entity_ids.contains_key(&id) {
return id;
}
}
}
}

impl Default for IDGenerator {
fn default() -> Self {
IDGenerator::new()
}
}
2 changes: 2 additions & 0 deletions common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub mod graph;
pub mod graph_collision;
mod graph_entities;
pub mod graph_ray_casting;
pub mod id_generator;
pub mod lru_slab;
mod margins;
pub mod math;
Expand All @@ -29,6 +30,7 @@ mod plane;
pub mod proto;
mod sim_config;
pub mod terraingen;
pub mod ticker;
pub mod traversal;
pub mod voxel_math;
pub mod world;
Expand Down
6 changes: 4 additions & 2 deletions common/src/proto.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use serde::{Deserialize, Serialize};

use crate::{
dodeca, graph::NodeId, node::ChunkId, voxel_math::Coords, world::Material, EntityId, SimConfig,
Step,
dodeca, graph::NodeId, node::ChunkId, ticker::TickerEntity, voxel_math::Coords,
world::Material, EntityId, SimConfig, Step,
};

#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -70,6 +70,7 @@ pub struct CharacterInput {
pub movement: na::Vector3<f32>,
pub jump: bool,
pub no_clip: bool,
pub debug_spawn_blinker: bool,
pub block_update: Option<BlockUpdate>,
}

Expand All @@ -90,6 +91,7 @@ pub struct SerializedVoxelData {
pub enum Component {
Character(Character),
Position(Position),
TickerEntity(TickerEntity),
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down
35 changes: 35 additions & 0 deletions common/src/ticker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use crate::Step;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct TickerEntity {
pub last_ticked: Step,
pub ticker: Ticker,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Ticker {
on: bool,
}

impl Ticker {
pub fn new() -> Self {
Self { on: false }
}
pub fn tick(&mut self, _step: Step) {
self.on = !self.on;

// Just for testing
if self.on {
println!("Ticked ON!");
} else {
println!("Ticked OFF!");
}
}
}

impl Default for Ticker {
fn default() -> Self {
Ticker::new()
}
}
53 changes: 35 additions & 18 deletions server/src/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ use common::proto::{BlockUpdate, SerializedVoxelData};
use common::{node::ChunkId, GraphEntities};
use fxhash::{FxHashMap, FxHashSet};
use hecs::Entity;
use rand::rngs::SmallRng;
use rand::{Rng, SeedableRng};
use save::ComponentType;
use tracing::{error, error_span, info, trace};

use common::{
character_controller, dodeca,
graph::{Graph, NodeId},
id_generator::IDGenerator,
math,
node::{populate_fresh_nodes, Chunk},
proto::{
Character, CharacterInput, CharacterState, ClientHello, Command, Component, FreshNode,
Position, Spawns, StateDelta,
},
ticker::{Ticker, TickerEntity},
traversal::{ensure_nearby, nearby_nodes},
worldgen::ChunkParams,
EntityId, SimConfig, Step,
Expand All @@ -30,14 +30,14 @@ use crate::postcard_helpers::{self, SaveEntity};

pub struct Sim {
cfg: Arc<SimConfig>,
rng: SmallRng,
step: Step,
entity_ids: FxHashMap<EntityId, Entity>,
id_generator: IDGenerator,
world: hecs::World,
graph: Graph,
/// Voxel data that has been fetched from a savefile but not yet introduced to the graph
preloaded_voxel_data: FxHashMap<ChunkId, VoxelData>,
spawns: Vec<Entity>,
pending_ticker_spawns: Vec<(Position, TickerEntity)>,
despawns: Vec<EntityId>,
graph_entities: GraphEntities,
/// All nodes that have entity-related information yet to be saved
Expand All @@ -51,13 +51,13 @@ pub struct Sim {
impl Sim {
pub fn new(cfg: Arc<SimConfig>, save: &save::Save) -> Self {
let mut result = Self {
rng: SmallRng::from_entropy(),
step: 0,
entity_ids: FxHashMap::default(),
id_generator: IDGenerator::new(),
world: hecs::World::new(),
graph: Graph::new(cfg.chunk_size),
preloaded_voxel_data: FxHashMap::default(),
spawns: Vec::new(),
pending_ticker_spawns: Vec::new(),
despawns: Vec::new(),
graph_entities: GraphEntities::new(),
dirty_nodes: FxHashSet::default(),
Expand Down Expand Up @@ -187,7 +187,7 @@ impl Sim {
}

pub fn spawn_character(&mut self, hello: ClientHello) -> (EntityId, Entity) {
let id = self.new_id();
let id = self.id_generator.new_id();
info!(%id, name = %hello.name, "spawning character");
let position = Position {
node: NodeId::ROOT,
Expand All @@ -205,11 +205,12 @@ impl Sim {
movement: na::Vector3::zeros(),
jump: false,
no_clip: true,
debug_spawn_blinker: false,
block_update: None,
};
let entity = self.world.spawn((id, position, character, initial_input));
self.graph_entities.insert(position.node, entity);
self.entity_ids.insert(id, entity);
self.id_generator.entity_ids.insert(id, entity);
self.spawns.push(entity);
self.dirty_nodes.insert(position.node);
(id, entity)
Expand All @@ -229,7 +230,7 @@ impl Sim {

pub fn destroy(&mut self, entity: Entity) {
let id = *self.world.get::<&EntityId>(entity).unwrap();
self.entity_ids.remove(&id);
self.id_generator.entity_ids.remove(&id);
if let Ok(position) = self.world.get::<&Position>(entity) {
self.graph_entities.remove(position.node, entity);
}
Expand Down Expand Up @@ -272,6 +273,14 @@ impl Sim {
let span = error_span!("step", step = self.step);
let _guard = span.enter();

{
let mut ticker_query = self.world.query::<&mut TickerEntity>();
let ticker_iter = ticker_query.iter();
for (_entity, ticker_entity) in ticker_iter {
ticker_entity.ticker.tick(self.step);
}
}

let mut pending_block_updates: Vec<BlockUpdate> = vec![];

// Extend graph structure
Expand Down Expand Up @@ -332,6 +341,13 @@ impl Sim {
.iter()
{
let prev_node = position.node;
if input.debug_spawn_blinker {
let ticker: TickerEntity = TickerEntity {
last_ticked: 0,
ticker: Ticker::new(),
};
self.pending_ticker_spawns.push((*position, ticker));
}
character_controller::run_character_step(
&self.cfg,
&self.graph,
Expand All @@ -350,6 +366,16 @@ impl Sim {
self.dirty_nodes.insert(position.node);
}

let pending_ticker_spawns = std::mem::take(&mut self.pending_ticker_spawns);
for (position, ticker) in pending_ticker_spawns {
let id = self.id_generator.new_id();
let entity = self.world.spawn((id, position, ticker));
self.graph_entities.insert(position.node, entity);
self.id_generator.entity_ids.insert(id, entity);
self.spawns.push(entity);
self.dirty_nodes.insert(position.node);
}

let mut accepted_block_updates: Vec<BlockUpdate> = vec![];

for block_update in pending_block_updates.into_iter() {
Expand Down Expand Up @@ -411,15 +437,6 @@ impl Sim {
self.step += 1;
(spawns, delta)
}

fn new_id(&mut self) -> EntityId {
loop {
let id = self.rng.gen();
if !self.entity_ids.contains_key(&id) {
return id;
}
}
}
}

fn dump_entity(world: &hecs::World, entity: Entity) -> Vec<Component> {
Expand Down