1 #include "InitialState.hpp"
2 #include "InteractiveState.hpp"
3 #include "MasterState.hpp"
5 #include "../app/Environment.hpp"
6 #include "../app/init.hpp"
7 #include "../geometry/distance.hpp"
8 #include "../model/Model.hpp"
9 #include "../io/WorldSave.hpp"
10 #include "../world/ChunkIndex.hpp"
11 #include "../world/ChunkStore.hpp"
14 #include <glm/gtx/io.hpp>
22 InitialState::InitialState(MasterState &master)
25 message.Position(glm::vec3(0.0f), Gravity::CENTER);
26 message.Set(master.GetEnv().assets.large_ui_font, "logging in");
29 void InitialState::OnEnter() {
33 void InitialState::Handle(const SDL_Event &evt) {
34 if (evt.type == SDL_QUIT) {
39 void InitialState::Update(int dt) {
43 void InitialState::Render(Viewport &viewport) {
44 message.Render(viewport);
48 // TODO: this clutter is a giant mess
49 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
53 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetConfig().net.host))
54 , world(res.block_types, master.GetWorldConf())
55 , player(*world.AddPlayer(master.GetConfig().player.name, player_id))
56 , hud(master.GetEnv(), master.GetConfig(), player)
57 , manip(master.GetEnv().audio, sounds, player.GetEntity())
58 , input(world, player, master.GetClient())
59 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
60 , chunk_receiver(master.GetClient(), world.Chunks(), save)
61 , chunk_renderer(player.GetChunks())
64 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
66 , chat(master.GetEnv(), *this, *this)
68 , packets_skipped(0) {
70 save.Write(master.GetWorldConf());
72 res.Load(master.GetEnv().loader, "default");
73 if (res.models.size() < 1) {
74 throw std::runtime_error("need at least one model to run");
76 res.models[0].Instantiate(player.GetEntity().GetModel());
77 sounds.Load(master.GetEnv().loader, res.snd_index);
78 interface.SetInventorySlots(res.block_types.size() - 1);
79 chunk_renderer.LoadTextures(master.GetEnv().loader, res.tex_index);
80 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
85 void InteractiveState::OnResume() {
89 void InteractiveState::OnPause() {
93 void InteractiveState::OnFocus() {
94 if (master.GetConfig().input.mouse) {
95 master.GetEnv().window.GrabMouse();
100 void InteractiveState::OnBlur() {
101 master.GetEnv().window.ReleaseMouse();
105 void InteractiveState::Handle(const SDL_Event &event) {
106 switch (event.type) {
108 // TODO: move to interface
109 if (event.key.keysym.sym == SDLK_RETURN) {
111 master.GetEnv().state.Push(&chat);
112 hud.KeepMessages(true);
113 } else if (event.key.keysym.sym == SDLK_SLASH) {
115 master.GetEnv().state.Push(&chat);
116 hud.KeepMessages(true);
118 interface.HandlePress(event.key);
122 interface.HandleRelease(event.key);
124 case SDL_MOUSEBUTTONDOWN:
125 interface.HandlePress(event.button);
127 case SDL_MOUSEBUTTONUP:
128 interface.HandleRelease(event.button);
130 case SDL_MOUSEMOTION:
131 interface.Handle(event.motion);
134 interface.Handle(event.wheel);
144 void InteractiveState::Update(int dt) {
145 loop_timer.Update(dt);
146 stat_timer.Update(dt);
148 chunk_receiver.Update(dt);
151 while (loop_timer.HitOnce()) {
152 world.Update(loop_timer.Interval());
153 world_dt += loop_timer.Interval();
154 loop_timer.PopIteration();
156 chunk_renderer.Update(dt);
158 if (input.BlockFocus()) {
159 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
160 } else if (input.EntityFocus()) {
161 hud.FocusEntity(input.EntityFocus().GetEntity());
166 if (input.UpdateImportant() || packets_skipped >= master.NetStat().SuggestedPacketSkip()) {
167 input.PushPlayerUpdate(time_skipped + world_dt);
171 time_skipped += world_dt;
175 hud.Display(res.block_types[player.GetInventorySlot() + 1]);
176 if (stat_timer.Hit()) {
177 hud.UpdateNetStats(master.NetStat());
181 glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
182 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
183 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
184 master.GetEnv().audio.Position(player.GetEntity().Position());
185 master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
186 master.GetEnv().audio.Orientation(dir, up);
189 void InteractiveState::Render(Viewport &viewport) {
190 viewport.WorldPosition(player.GetEntity().ViewTransform(player.GetEntity().ChunkCoords()));
191 if (master.GetConfig().video.world) {
192 chunk_renderer.Render(viewport);
193 world.Render(viewport);
194 if (master.GetConfig().video.debug) {
195 world.RenderDebug(viewport);
197 sky.Render(viewport);
199 hud.Render(viewport);
202 void InteractiveState::Handle(const Packet::SpawnEntity &pack) {
204 pack.ReadEntityID(entity_id);
205 Entity &entity = world.ForceAddEntity(entity_id);
206 UpdateEntity(entity_id, pack.Seq());
207 pack.ReadEntity(entity);
209 pack.ReadModelID(model_id);
210 if (model_id > 0 && model_id <= res.models.size()) {
211 res.models.Get(model_id).Instantiate(entity.GetModel());
215 void InteractiveState::Handle(const Packet::DespawnEntity &pack) {
217 pack.ReadEntityID(entity_id);
218 ClearEntity(entity_id);
219 for (Entity &entity : world.Entities()) {
220 if (entity.ID() == entity_id) {
227 void InteractiveState::Handle(const Packet::EntityUpdate &pack) {
228 auto world_iter = world.Entities().begin();
229 auto world_end = world.Entities().end();
233 pack.ReadEntityCount(count);
234 pack.ReadChunkBase(base);
237 for (uint32_t i = 0; i < count; ++i) {
238 uint32_t entity_id = 0;
239 pack.ReadEntityID(entity_id, i);
241 while (world_iter != world_end && world_iter->ID() < entity_id) {
244 if (world_iter == world_end) {
245 // nothing can be done from here
248 if (world_iter->ID() == entity_id) {
249 if (UpdateEntity(entity_id, pack.Seq())) {
250 pack.ReadEntityState(state, base, i);
251 world_iter->SetState(state);
257 bool InteractiveState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
258 auto entry = update_status.find(entity_id);
259 if (entry == update_status.end()) {
260 update_status.emplace(entity_id, UpdateStatus{ seq, loop_timer.Elapsed() });
264 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
265 int time_diff = loop_timer.Elapsed() - entry->second.last_update;
266 entry->second.last_update = loop_timer.Elapsed();
268 if (pack_diff > 0 || time_diff > 1500) {
269 entry->second.last_packet = seq;
276 void InteractiveState::ClearEntity(uint32_t entity_id) {
277 update_status.erase(entity_id);
280 void InteractiveState::Handle(const Packet::PlayerCorrection &pack) {
282 EntityState corrected_state;
283 pack.ReadPacketSeq(pack_seq);
284 pack.ReadPlayerState(corrected_state);
285 input.MergePlayerCorrection(pack_seq, corrected_state);
288 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
290 pack.ReadChunkCoords(pos);
291 Chunk *chunk = player.GetChunks().Get(pos);
293 // this change doesn't concern us
297 pack.ReadBlockCount(count);
298 for (uint32_t i = 0; i < count; ++i) {
301 pack.ReadIndex(index, i);
302 pack.ReadBlock(block, i);
303 if (index < Chunk::size && block.type < res.block_types.size()) {
304 manip.SetBlock(*chunk, index, block);
309 void InteractiveState::Handle(const Packet::Message &pack) {
311 pack.ReadMessage(msg);
312 hud.PostMessage(msg);
315 void InteractiveState::SetAudio(bool b) {
316 master.GetConfig().audio.enabled = b;
318 hud.PostMessage("Audio enabled");
320 hud.PostMessage("Audio disabled");
324 void InteractiveState::SetVideo(bool b) {
325 master.GetConfig().video.world = b;
327 hud.PostMessage("World rendering enabled");
329 hud.PostMessage("World rendering disabled");
333 void InteractiveState::SetHUD(bool b) {
334 master.GetConfig().video.hud = b;
336 hud.PostMessage("HUD rendering enabled");
338 hud.PostMessage("HUD rendering disabled");
342 void InteractiveState::SetDebug(bool b) {
343 master.GetConfig().video.debug = b;
345 hud.PostMessage("Debug rendering enabled");
347 hud.PostMessage("Debug rendering disabled");
351 void InteractiveState::NextCamera() {
352 if (iszero(master.GetEnv().viewport.CameraOffset())) {
353 master.GetEnv().viewport.OffsetCamera(glm::vec3(0.0f, 0.0f, -5.0f));
355 master.GetEnv().viewport.OffsetCamera(glm::vec3(0.0f, 0.0f, 0.0f));
359 void InteractiveState::Exit() {
364 void InteractiveState::OnLineSubmit(const string &line) {
366 master.GetClient().SendMessage(1, 0, line);
371 MasterState::MasterState(
374 const World::Config &wc)
382 client.GetConnection().SetHandler(this);
385 void MasterState::Quit() {
386 if (!client.GetConnection().Closed()) {
389 env.state.PopUntil(this);
393 void MasterState::OnEnter() {
394 login_packet = client.SendLogin(config.player.name);
395 env.state.Push(&init_state);
399 void MasterState::Handle(const SDL_Event &) {
404 void MasterState::Update(int dt) {
410 void MasterState::Render(Viewport &) {
415 void MasterState::OnPacketLost(uint16_t id) {
416 if (id == login_packet) {
417 login_packet = client.SendLogin(config.player.name);
421 void MasterState::OnTimeout() {
422 if (client.GetConnection().Closed()) {
424 env.ShowMessage("connection timed out");
428 void MasterState::On(const Packet::Join &pack) {
429 pack.ReadWorldName(world_conf.name);
433 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
436 cout << "joined game \"" << world_conf.name << '"' << endl;
437 // server received our login
442 pack.ReadPlayerID(player_id);
443 state.reset(new InteractiveState(*this, player_id));
445 EntityState player_state;
446 pack.ReadPlayerState(player_state);
447 state->GetPlayer().GetEntity().SetState(player_state);
449 env.state.PopAfter(this);
450 env.state.Push(state.get());
453 void MasterState::On(const Packet::Part &) {
457 env.ShowMessage("kicked by server");
460 env.ShowMessage("login refused by server");
464 void MasterState::On(const Packet::SpawnEntity &pack) {
466 cout << "got entity spawn before world was created" << endl;
472 void MasterState::On(const Packet::DespawnEntity &pack) {
474 cout << "got entity despawn before world was created" << endl;
480 void MasterState::On(const Packet::EntityUpdate &pack) {
482 cout << "got entity update before world was created" << endl;
488 void MasterState::On(const Packet::PlayerCorrection &pack) {
490 cout << "got player correction without a player :S" << endl;
496 void MasterState::On(const Packet::ChunkBegin &pack) {
498 cout << "got chunk data, but the world has not been created yet" << endl;
499 cout << "great, this will totally screw up everything :(" << endl;
502 state->GetChunkReceiver().Handle(pack);
505 void MasterState::On(const Packet::ChunkData &pack) {
507 cout << "got chunk data, but the world has not been created yet" << endl;
508 cout << "great, this will totally screw up everything :(" << endl;
511 state->GetChunkReceiver().Handle(pack);
514 void MasterState::On(const Packet::BlockUpdate &pack) {
516 cout << "received block update, but the world has not been created yet" << endl;
522 void MasterState::On(const Packet::Message &pack) {
527 pack.ReadMessage(msg);
528 cout << "got message before interface was created: " << msg << endl;