1 #include "InitialState.hpp"
2 #include "InteractiveState.hpp"
3 #include "MasterState.hpp"
5 #include "../app/Environment.hpp"
6 #include "../app/init.hpp"
7 #include "../app/TextureIndex.hpp"
8 #include "../model/CompositeModel.hpp"
11 #include <glm/gtx/io.hpp>
19 InitialState::InitialState(MasterState &master)
22 message.Position(glm::vec3(0.0f), Gravity::CENTER);
23 message.Set(master.GetEnv().assets.large_ui_font, "logging in");
26 void InitialState::OnEnter() {
30 void InitialState::Handle(const SDL_Event &evt) {
31 if (evt.type == SDL_QUIT) {
36 void InitialState::Update(int dt) {
40 void InitialState::Render(Viewport &viewport) {
41 message.Render(viewport);
45 // TODO: this clutter is a giant mess
46 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
49 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetClientConf().host))
50 , world(block_types, master.GetWorldConf())
52 master.GetInterfaceConf(),
55 world.AddPlayer(master.GetInterfaceConf().player_name, player_id)
57 , chunk_receiver(world.Chunks())
58 , chunk_renderer(*interface.GetPlayer().chunks)
62 TextureIndex tex_index;
63 master.GetEnv().loader.LoadBlockTypes("default", block_types, tex_index);
64 chunk_renderer.LoadTextures(master.GetEnv().loader, tex_index);
65 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
67 // TODO: better solution for initializing HUD
68 interface.SelectNext();
72 void InteractiveState::OnEnter() {
73 master.GetEnv().window.GrabMouse();
76 void InteractiveState::Handle(const SDL_Event &event) {
79 interface.HandlePress(event.key);
82 interface.HandleRelease(event.key);
84 case SDL_MOUSEBUTTONDOWN:
85 interface.HandlePress(event.button);
87 case SDL_MOUSEBUTTONUP:
88 interface.HandleRelease(event.button);
91 interface.Handle(event.motion);
94 interface.Handle(event.wheel);
104 void InteractiveState::Update(int dt) {
105 loop_timer.Update(dt);
107 chunk_receiver.Update(dt);
109 interface.Update(dt);
111 while (loop_timer.HitOnce()) {
112 world.Update(loop_timer.Interval());
113 world_dt += loop_timer.Interval();
114 loop_timer.PopIteration();
116 chunk_renderer.Update(dt);
118 Entity &player = *interface.GetPlayer().entity;
121 PushPlayerUpdate(player, world_dt);
124 glm::mat4 trans = player.Transform(player.ChunkCoords());
125 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
126 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
127 master.GetEnv().audio.Position(player.Position());
128 master.GetEnv().audio.Velocity(player.Velocity());
129 master.GetEnv().audio.Orientation(dir, up);
132 void InteractiveState::PushPlayerUpdate(const Entity &player, int dt) {
133 std::uint16_t packet = master.GetClient().SendPlayerUpdate(player);
134 if (player_hist.size() < 16) {
135 player_hist.emplace_back(player.GetState(), dt, packet);
137 auto entry = player_hist.begin();
138 entry->state = player.GetState();
140 entry->packet = packet;
141 player_hist.splice(player_hist.end(), player_hist, entry);
145 void InteractiveState::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
146 if (player_hist.empty()) return;
148 auto entry = player_hist.begin();
149 auto end = player_hist.end();
151 // we may have received an older packet
152 int pack_diff = int16_t(seq) - int16_t(entry->packet);
154 // indeed we have, just ignore it
158 // drop anything older than the fix
159 while (entry != end) {
160 pack_diff = int16_t(seq) - int16_t(entry->packet);
162 entry = player_hist.erase(entry);
168 EntityState replay_state(corrected_state);
169 EntityState &player_state = interface.GetPlayer().entity->GetState();
172 entry->state.chunk_pos = replay_state.chunk_pos;
173 entry->state.block_pos = replay_state.block_pos;
177 while (entry != end) {
178 replay_state.velocity = entry->state.velocity;
179 replay_state.Update(entry->delta_t);
180 entry->state.chunk_pos = replay_state.chunk_pos;
181 entry->state.block_pos = replay_state.block_pos;
185 glm::vec3 displacement(replay_state.Diff(player_state));
186 const float disp_squared = dot(displacement, displacement);
188 if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
192 // if offset > 10cm, warp the player
193 // otherwise, move at most 1cm per frame towards
194 // the fixed position (160ms, so shouldn't be too noticeable)
195 constexpr float warp_thresh = 0.01f; // (1/10)^2
196 constexpr float max_disp = 0.0001f; // (1/100)^2
198 if (disp_squared > warp_thresh) {
199 player_state.chunk_pos = replay_state.chunk_pos;
200 player_state.block_pos = replay_state.block_pos;
201 } else if (disp_squared < max_disp) {
202 player_state.block_pos += displacement;
204 displacement *= 0.01f / sqrt(disp_squared);
205 player_state.block_pos += displacement;
209 void InteractiveState::Render(Viewport &viewport) {
210 Entity &player = *interface.GetPlayer().entity;
211 viewport.WorldPosition(player.Transform(player.ChunkCoords()));
212 chunk_renderer.Render(viewport);
213 world.Render(viewport);
214 interface.Render(viewport);
218 MasterState::MasterState(
220 const World::Config &wc,
221 const Interface::Config &ic,
222 const Client::Config &cc)
233 client.GetConnection().SetHandler(this);
234 update_timer.Start();
237 void MasterState::Quit() {
238 if (!client.GetConnection().Closed()) {
241 env.state.PopUntil(this);
245 void MasterState::OnEnter() {
246 login_packet = client.SendLogin(intf_conf.player_name);
247 env.state.Push(&init_state);
251 void MasterState::Handle(const SDL_Event &event) {
256 void MasterState::Update(int dt) {
257 update_timer.Update(dt);
263 void MasterState::Render(Viewport &) {
268 void MasterState::OnPacketLost(uint16_t id) {
269 if (id == login_packet) {
270 login_packet = client.SendLogin(intf_conf.player_name);
274 void MasterState::OnTimeout() {
275 if (client.GetConnection().Closed()) {
276 // TODO: push disconnected message
277 cout << "connection timed out" << endl;
282 void MasterState::On(const Packet::Join &pack) {
283 pack.ReadWorldName(world_conf.name);
287 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
290 cout << "joined game \"" << world_conf.name << '"' << endl;
291 // server received our login
296 pack.ReadPlayerID(player_id);
297 state.reset(new InteractiveState(*this, player_id));
299 pack.ReadPlayerState(state->GetInterface().GetPlayer().entity->GetState());
301 env.state.PopAfter(this);
302 env.state.Push(state.get());
305 void MasterState::On(const Packet::Part &pack) {
308 cout << "kicked by server" << endl;
311 cout << "login refused by server" << endl;
316 void MasterState::On(const Packet::SpawnEntity &pack) {
318 cout << "got entity spawn before world was created" << endl;
323 pack.ReadEntityID(entity_id);
324 Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
325 UpdateEntity(entity_id, pack.Seq());
326 pack.ReadEntity(entity);
328 pack.ReadSkeletonID(skel_id);
329 CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
331 skel->Instantiate(entity.GetModel());
333 cout << "spawned entity " << entity.Name() << " at " << entity.AbsolutePosition() << endl;
336 void MasterState::On(const Packet::DespawnEntity &pack) {
338 cout << "got entity despawn before world was created" << endl;
343 pack.ReadEntityID(entity_id);
344 ClearEntity(entity_id);
345 for (Entity &entity : state->GetWorld().Entities()) {
346 if (entity.ID() == entity_id) {
348 cout << "despawned entity " << entity.Name() << " at " << entity.AbsolutePosition() << endl;
354 void MasterState::On(const Packet::EntityUpdate &pack) {
356 cout << "got entity update before world was created" << endl;
361 auto world_iter = state->GetWorld().Entities().begin();
362 auto world_end = state->GetWorld().Entities().end();
365 pack.ReadEntityCount(count);
367 for (uint32_t i = 0; i < count; ++i) {
368 uint32_t entity_id = 0;
369 pack.ReadEntityID(entity_id, i);
371 while (world_iter != world_end && world_iter->ID() < entity_id) {
374 if (world_iter == world_end) {
375 // nothing can be done from here
378 if (world_iter->ID() == entity_id) {
379 if (UpdateEntity(entity_id, pack.Seq())) {
380 pack.ReadEntityState(world_iter->GetState(), i);
386 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
387 auto entry = update_status.find(entity_id);
388 if (entry == update_status.end()) {
389 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
393 int pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
394 int time_diff = update_timer.Elapsed() - entry->second.last_update;
395 entry->second.last_update = update_timer.Elapsed();
397 if (pack_diff > 0 || time_diff > 1500) {
398 entry->second.last_packet = seq;
405 void MasterState::ClearEntity(uint32_t entity_id) {
406 update_status.erase(entity_id);
409 void MasterState::On(const Packet::PlayerCorrection &pack) {
411 cout << "got player correction without a player :S" << endl;
416 EntityState corrected_state;
417 pack.ReadPacketSeq(pack_seq);
418 pack.ReadPlayerState(corrected_state);
419 state->MergePlayerCorrection(pack_seq, corrected_state);
422 void MasterState::On(const Packet::ChunkBegin &pack) {
424 cout << "got chunk data, but the world has not been created yet" << endl;
425 cout << "great, this will totally screw up everything :(" << endl;
428 state->GetChunkReceiver().Handle(pack);
431 void MasterState::On(const Packet::ChunkData &pack) {
433 cout << "got chunk data, but the world has not been created yet" << endl;
434 cout << "great, this will totally screw up everything :(" << endl;
437 state->GetChunkReceiver().Handle(pack);