1 #include "ChunkRequester.hpp"
2 #include "InitialState.hpp"
3 #include "InteractiveState.hpp"
4 #include "MasterState.hpp"
6 #include "../app/Environment.hpp"
7 #include "../app/init.hpp"
8 #include "../app/TextureIndex.hpp"
9 #include "../model/CompositeModel.hpp"
10 #include "../io/WorldSave.hpp"
11 #include "../world/ChunkStore.hpp"
14 #include <glm/gtx/io.hpp>
22 ChunkRequester::ChunkRequester(
31 void ChunkRequester::Update(int dt) {
32 // check if there's chunks waiting to be loaded
35 // store a few chunks as well
36 constexpr int max_save = 10;
38 for (Chunk &chunk : store) {
39 if (chunk.ShouldUpdateSave()) {
42 if (saved >= max_save) {
49 int ChunkRequester::ToLoad() const noexcept {
50 return store.EstimateMissing();
53 void ChunkRequester::LoadOne() {
54 if (!store.HasMissing()) return;
56 Chunk::Pos pos = store.NextMissing();
57 Chunk *chunk = store.Allocate(pos);
59 // chunk store corrupted?
63 if (save.Exists(pos)) {
65 // TODO: request chunk from server with cache tag
67 // TODO: request chunk from server
71 void ChunkRequester::LoadN(std::size_t n) {
72 std::size_t end = std::min(n, std::size_t(ToLoad()));
73 for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
79 InitialState::InitialState(MasterState &master)
82 message.Position(glm::vec3(0.0f), Gravity::CENTER);
83 message.Set(master.GetEnv().assets.large_ui_font, "logging in");
86 void InitialState::OnEnter() {
90 void InitialState::Handle(const SDL_Event &evt) {
91 if (evt.type == SDL_QUIT) {
96 void InitialState::Update(int dt) {
100 void InitialState::Render(Viewport &viewport) {
101 message.Render(viewport);
105 // TODO: this clutter is a giant mess
106 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
109 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetConfig().net.host))
110 , world(block_types, master.GetWorldConf())
111 , player(*world.AddPlayer(master.GetConfig().player.name))
112 , hud(master.GetEnv(), master.GetConfig(), player)
113 , manip(master.GetEnv(), player.GetEntity())
114 , input(world, player, manip)
115 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
116 // TODO: looks like chunk requester and receiver can and should be merged
117 , chunk_requester(world.Chunks(), save)
118 , chunk_receiver(world.Chunks())
119 , chunk_renderer(player.GetChunks())
122 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
124 if (!save.Exists()) {
125 save.Write(master.GetWorldConf());
127 TextureIndex tex_index;
128 master.GetEnv().loader.LoadBlockTypes("default", block_types, tex_index);
129 interface.SetInventorySlots(block_types.Size() - 1);
130 chunk_renderer.LoadTextures(master.GetEnv().loader, tex_index);
131 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
136 void InteractiveState::OnEnter() {
137 master.GetEnv().window.GrabMouse();
140 void InteractiveState::Handle(const SDL_Event &event) {
141 switch (event.type) {
143 interface.HandlePress(event.key);
146 interface.HandleRelease(event.key);
148 case SDL_MOUSEBUTTONDOWN:
149 interface.HandlePress(event.button);
151 case SDL_MOUSEBUTTONUP:
152 interface.HandleRelease(event.button);
154 case SDL_MOUSEMOTION:
155 interface.Handle(event.motion);
158 interface.Handle(event.wheel);
168 void InteractiveState::Update(int dt) {
170 if (input.BlockFocus()) {
171 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
172 } else if (input.EntityFocus()) {
173 hud.FocusEntity(*input.EntityFocus().entity);
177 hud.Display(block_types[player.GetInventorySlot() + 1]);
178 loop_timer.Update(dt);
180 chunk_receiver.Update(dt);
181 chunk_requester.Update(dt);
185 while (loop_timer.HitOnce()) {
186 world.Update(loop_timer.Interval());
187 world_dt += loop_timer.Interval();
188 loop_timer.PopIteration();
190 chunk_renderer.Update(dt);
193 PushPlayerUpdate(player.GetEntity(), world_dt);
196 glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
197 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
198 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
199 master.GetEnv().audio.Position(player.GetEntity().Position());
200 master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
201 master.GetEnv().audio.Orientation(dir, up);
204 void InteractiveState::PushPlayerUpdate(const Entity &player, int dt) {
205 std::uint16_t packet = master.GetClient().SendPlayerUpdate(player);
206 if (player_hist.size() < 16) {
207 player_hist.emplace_back(player.GetState(), dt, packet);
209 auto entry = player_hist.begin();
210 entry->state = player.GetState();
212 entry->packet = packet;
213 player_hist.splice(player_hist.end(), player_hist, entry);
217 void InteractiveState::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
218 if (player_hist.empty()) return;
220 auto entry = player_hist.begin();
221 auto end = player_hist.end();
223 // we may have received an older packet
224 int pack_diff = int16_t(seq) - int16_t(entry->packet);
226 // indeed we have, just ignore it
230 // drop anything older than the fix
231 while (entry != end) {
232 pack_diff = int16_t(seq) - int16_t(entry->packet);
234 entry = player_hist.erase(entry);
240 EntityState replay_state(corrected_state);
241 EntityState &player_state = player.GetEntity().GetState();
244 entry->state.chunk_pos = replay_state.chunk_pos;
245 entry->state.block_pos = replay_state.block_pos;
249 while (entry != end) {
250 replay_state.velocity = entry->state.velocity;
251 replay_state.Update(entry->delta_t);
252 entry->state.chunk_pos = replay_state.chunk_pos;
253 entry->state.block_pos = replay_state.block_pos;
257 glm::vec3 displacement(replay_state.Diff(player_state));
258 const float disp_squared = dot(displacement, displacement);
260 if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
264 // if offset > 10cm, warp the player
265 // otherwise, move at most 1cm per frame towards
266 // the fixed position (160ms, so shouldn't be too noticeable)
267 constexpr float warp_thresh = 0.01f; // (1/10)^2
268 constexpr float max_disp = 0.0001f; // (1/100)^2
270 if (disp_squared > warp_thresh) {
271 player_state.chunk_pos = replay_state.chunk_pos;
272 player_state.block_pos = replay_state.block_pos;
273 } else if (disp_squared < max_disp) {
274 player_state.block_pos += displacement;
276 displacement *= 0.01f / sqrt(disp_squared);
277 player_state.block_pos += displacement;
281 void InteractiveState::Render(Viewport &viewport) {
282 viewport.WorldPosition(player.GetEntity().Transform(player.GetEntity().ChunkCoords()));
283 if (master.GetConfig().video.world) {
284 chunk_renderer.Render(viewport);
285 world.Render(viewport);
286 sky.Render(viewport);
288 hud.Render(viewport);
291 void InteractiveState::SetAudio(bool b) {
292 master.GetConfig().audio.enabled = b;
294 hud.PostMessage("Audio enabled");
296 hud.PostMessage("Audio disabled");
300 void InteractiveState::SetVideo(bool b) {
301 master.GetConfig().video.world = b;
303 hud.PostMessage("World rendering enabled");
305 hud.PostMessage("World rendering disabled");
309 void InteractiveState::SetHUD(bool b) {
310 master.GetConfig().video.hud = b;
312 hud.PostMessage("HUD rendering enabled");
314 hud.PostMessage("HUD rendering disabled");
318 void InteractiveState::SetDebug(bool b) {
319 master.GetConfig().video.debug = b;
321 hud.PostMessage("Debug rendering enabled");
323 hud.PostMessage("Debug rendering disabled");
327 void InteractiveState::Exit() {
332 MasterState::MasterState(
335 const World::Config &wc)
345 client.GetConnection().SetHandler(this);
346 update_timer.Start();
349 void MasterState::Quit() {
350 if (!client.GetConnection().Closed()) {
353 env.state.PopUntil(this);
357 void MasterState::OnEnter() {
358 login_packet = client.SendLogin(config.player.name);
359 env.state.Push(&init_state);
363 void MasterState::Handle(const SDL_Event &event) {
368 void MasterState::Update(int dt) {
369 update_timer.Update(dt);
375 void MasterState::Render(Viewport &) {
380 void MasterState::OnPacketLost(uint16_t id) {
381 if (id == login_packet) {
382 login_packet = client.SendLogin(config.player.name);
386 void MasterState::OnTimeout() {
387 if (client.GetConnection().Closed()) {
388 // TODO: push disconnected message
389 cout << "connection timed out" << endl;
394 void MasterState::On(const Packet::Join &pack) {
395 pack.ReadWorldName(world_conf.name);
399 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
402 cout << "joined game \"" << world_conf.name << '"' << endl;
403 // server received our login
408 pack.ReadPlayerID(player_id);
409 state.reset(new InteractiveState(*this, player_id));
411 pack.ReadPlayerState(state->GetPlayer().GetEntity().GetState());
413 env.state.PopAfter(this);
414 env.state.Push(state.get());
417 void MasterState::On(const Packet::Part &pack) {
420 cout << "kicked by server" << endl;
423 cout << "login refused by server" << endl;
428 void MasterState::On(const Packet::SpawnEntity &pack) {
430 cout << "got entity spawn before world was created" << endl;
435 pack.ReadEntityID(entity_id);
436 Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
437 UpdateEntity(entity_id, pack.Seq());
438 pack.ReadEntity(entity);
440 pack.ReadSkeletonID(skel_id);
441 CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
443 skel->Instantiate(entity.GetModel());
445 cout << "spawned entity #" << entity_id << " (" << entity.Name()
446 << ") at " << entity.AbsolutePosition() << endl;
449 void MasterState::On(const Packet::DespawnEntity &pack) {
451 cout << "got entity despawn before world was created" << endl;
456 pack.ReadEntityID(entity_id);
457 ClearEntity(entity_id);
458 for (Entity &entity : state->GetWorld().Entities()) {
459 if (entity.ID() == entity_id) {
461 cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
467 void MasterState::On(const Packet::EntityUpdate &pack) {
469 cout << "got entity update before world was created" << endl;
474 auto world_iter = state->GetWorld().Entities().begin();
475 auto world_end = state->GetWorld().Entities().end();
478 pack.ReadEntityCount(count);
480 for (uint32_t i = 0; i < count; ++i) {
481 uint32_t entity_id = 0;
482 pack.ReadEntityID(entity_id, i);
484 while (world_iter != world_end && world_iter->ID() < entity_id) {
487 if (world_iter == world_end) {
488 // nothing can be done from here
491 if (world_iter->ID() == entity_id) {
492 if (UpdateEntity(entity_id, pack.Seq())) {
493 pack.ReadEntityState(world_iter->GetState(), i);
499 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
500 auto entry = update_status.find(entity_id);
501 if (entry == update_status.end()) {
502 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
506 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
507 int time_diff = update_timer.Elapsed() - entry->second.last_update;
508 entry->second.last_update = update_timer.Elapsed();
510 if (pack_diff > 0 || time_diff > 1500) {
511 entry->second.last_packet = seq;
518 void MasterState::ClearEntity(uint32_t entity_id) {
519 update_status.erase(entity_id);
522 void MasterState::On(const Packet::PlayerCorrection &pack) {
524 cout << "got player correction without a player :S" << endl;
529 EntityState corrected_state;
530 pack.ReadPacketSeq(pack_seq);
531 pack.ReadPlayerState(corrected_state);
532 state->MergePlayerCorrection(pack_seq, corrected_state);
535 void MasterState::On(const Packet::ChunkBegin &pack) {
537 cout << "got chunk data, but the world has not been created yet" << endl;
538 cout << "great, this will totally screw up everything :(" << endl;
541 state->GetChunkReceiver().Handle(pack);
544 void MasterState::On(const Packet::ChunkData &pack) {
546 cout << "got chunk data, but the world has not been created yet" << endl;
547 cout << "great, this will totally screw up everything :(" << endl;
550 state->GetChunkReceiver().Handle(pack);