1 #include "InitialState.hpp"
2 #include "InteractiveState.hpp"
3 #include "MasterState.hpp"
5 #include "../app/Environment.hpp"
6 #include "../app/init.hpp"
7 #include "../model/Model.hpp"
8 #include "../io/WorldSave.hpp"
9 #include "../world/ChunkIndex.hpp"
10 #include "../world/ChunkStore.hpp"
13 #include <glm/gtx/io.hpp>
21 InitialState::InitialState(MasterState &master)
24 message.Position(glm::vec3(0.0f), Gravity::CENTER);
25 message.Set(master.GetEnv().assets.large_ui_font, "logging in");
28 void InitialState::OnEnter() {
32 void InitialState::Handle(const SDL_Event &evt) {
33 if (evt.type == SDL_QUIT) {
38 void InitialState::Update(int dt) {
42 void InitialState::Render(Viewport &viewport) {
43 message.Render(viewport);
47 // TODO: this clutter is a giant mess
48 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
52 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetConfig().net.host))
53 , world(res.block_types, master.GetWorldConf())
54 , player(*world.AddPlayer(master.GetConfig().player.name, player_id))
55 , hud(master.GetEnv(), master.GetConfig(), player)
56 , manip(master.GetEnv().audio, sounds, player.GetEntity())
57 , input(world, player, master.GetClient())
58 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
59 , chunk_receiver(world.Chunks(), save)
60 , chunk_renderer(player.GetChunks())
63 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
65 , chat(master.GetEnv(), *this, *this)
67 , packets_skipped(0) {
69 save.Write(master.GetWorldConf());
71 res.Load(master.GetEnv().loader, "default");
72 if (res.models.size() < 1) {
73 throw std::runtime_error("need at least one model to run");
75 res.models[0].Instantiate(player.GetEntity().GetModel());
76 sounds.Load(master.GetEnv().loader, res.snd_index);
77 interface.SetInventorySlots(res.block_types.size() - 1);
78 chunk_renderer.LoadTextures(master.GetEnv().loader, res.tex_index);
79 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
82 if (save.Exists(player)) {
87 void InteractiveState::OnResume() {
91 void InteractiveState::OnPause() {
95 void InteractiveState::OnFocus() {
96 if (master.GetConfig().input.mouse) {
97 master.GetEnv().window.GrabMouse();
102 void InteractiveState::OnBlur() {
103 master.GetEnv().window.ReleaseMouse();
107 void InteractiveState::Handle(const SDL_Event &event) {
108 switch (event.type) {
110 // TODO: move to interface
111 if (event.key.keysym.sym == SDLK_RETURN) {
113 master.GetEnv().state.Push(&chat);
114 hud.KeepMessages(true);
115 } else if (event.key.keysym.sym == SDLK_SLASH) {
117 master.GetEnv().state.Push(&chat);
118 hud.KeepMessages(true);
120 interface.HandlePress(event.key);
124 interface.HandleRelease(event.key);
126 case SDL_MOUSEBUTTONDOWN:
127 interface.HandlePress(event.button);
129 case SDL_MOUSEBUTTONUP:
130 interface.HandleRelease(event.button);
132 case SDL_MOUSEMOTION:
133 interface.Handle(event.motion);
136 interface.Handle(event.wheel);
146 void InteractiveState::Update(int dt) {
147 loop_timer.Update(dt);
148 stat_timer.Update(dt);
150 chunk_receiver.Update(dt);
153 while (loop_timer.HitOnce()) {
154 world.Update(loop_timer.Interval());
155 world_dt += loop_timer.Interval();
156 loop_timer.PopIteration();
158 chunk_renderer.Update(dt);
160 if (input.BlockFocus()) {
161 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
162 } else if (input.EntityFocus()) {
163 hud.FocusEntity(*input.EntityFocus().entity);
168 if (input.UpdateImportant() || packets_skipped >= master.NetStat().SuggestedPacketSkip()) {
169 input.PushPlayerUpdate(time_skipped + world_dt);
173 time_skipped += world_dt;
177 hud.Display(res.block_types[player.GetInventorySlot() + 1]);
178 if (stat_timer.Hit()) {
179 hud.UpdateNetStats(master.NetStat());
183 glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
184 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
185 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
186 master.GetEnv().audio.Position(player.GetEntity().Position());
187 master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
188 master.GetEnv().audio.Orientation(dir, up);
191 void InteractiveState::Render(Viewport &viewport) {
192 viewport.WorldPosition(player.GetEntity().ViewTransform(player.GetEntity().ChunkCoords()));
193 if (master.GetConfig().video.world) {
194 chunk_renderer.Render(viewport);
195 world.Render(viewport);
196 sky.Render(viewport);
198 hud.Render(viewport);
201 void InteractiveState::Handle(const Packet::SpawnEntity &pack) {
203 pack.ReadEntityID(entity_id);
204 Entity &entity = world.ForceAddEntity(entity_id);
205 UpdateEntity(entity_id, pack.Seq());
206 pack.ReadEntity(entity);
208 pack.ReadModelID(model_id);
209 if (model_id > 0 && model_id <= res.models.size()) {
210 res.models.Get(model_id).Instantiate(entity.GetModel());
214 void InteractiveState::Handle(const Packet::DespawnEntity &pack) {
216 pack.ReadEntityID(entity_id);
217 ClearEntity(entity_id);
218 for (Entity &entity : world.Entities()) {
219 if (entity.ID() == entity_id) {
226 void InteractiveState::Handle(const Packet::EntityUpdate &pack) {
227 auto world_iter = world.Entities().begin();
228 auto world_end = world.Entities().end();
232 pack.ReadEntityCount(count);
233 pack.ReadChunkBase(base);
236 for (uint32_t i = 0; i < count; ++i) {
237 uint32_t entity_id = 0;
238 pack.ReadEntityID(entity_id, i);
240 while (world_iter != world_end && world_iter->ID() < entity_id) {
243 if (world_iter == world_end) {
244 // nothing can be done from here
247 if (world_iter->ID() == entity_id) {
248 if (UpdateEntity(entity_id, pack.Seq())) {
249 pack.ReadEntityState(state, base, i);
250 world_iter->SetState(state);
256 bool InteractiveState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
257 auto entry = update_status.find(entity_id);
258 if (entry == update_status.end()) {
259 update_status.emplace(entity_id, UpdateStatus{ seq, loop_timer.Elapsed() });
263 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
264 int time_diff = loop_timer.Elapsed() - entry->second.last_update;
265 entry->second.last_update = loop_timer.Elapsed();
267 if (pack_diff > 0 || time_diff > 1500) {
268 entry->second.last_packet = seq;
275 void InteractiveState::ClearEntity(uint32_t entity_id) {
276 update_status.erase(entity_id);
279 void InteractiveState::Handle(const Packet::PlayerCorrection &pack) {
281 EntityState corrected_state;
282 pack.ReadPacketSeq(pack_seq);
283 pack.ReadPlayerState(corrected_state);
284 input.MergePlayerCorrection(pack_seq, corrected_state);
287 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
289 pack.ReadChunkCoords(pos);
290 Chunk *chunk = player.GetChunks().Get(pos);
292 // this change doesn't concern us
296 pack.ReadBlockCount(count);
297 for (uint32_t i = 0; i < count; ++i) {
300 pack.ReadIndex(index, i);
301 pack.ReadBlock(block, i);
302 if (index < Chunk::size && block.type < res.block_types.size()) {
303 manip.SetBlock(*chunk, index, block);
308 void InteractiveState::Handle(const Packet::Message &pack) {
310 pack.ReadMessage(msg);
311 hud.PostMessage(msg);
314 void InteractiveState::SetAudio(bool b) {
315 master.GetConfig().audio.enabled = b;
317 hud.PostMessage("Audio enabled");
319 hud.PostMessage("Audio disabled");
323 void InteractiveState::SetVideo(bool b) {
324 master.GetConfig().video.world = b;
326 hud.PostMessage("World rendering enabled");
328 hud.PostMessage("World rendering disabled");
332 void InteractiveState::SetHUD(bool b) {
333 master.GetConfig().video.hud = b;
335 hud.PostMessage("HUD rendering enabled");
337 hud.PostMessage("HUD rendering disabled");
341 void InteractiveState::SetDebug(bool b) {
342 master.GetConfig().video.debug = b;
344 hud.PostMessage("Debug rendering enabled");
346 hud.PostMessage("Debug rendering disabled");
350 void InteractiveState::Exit() {
355 void InteractiveState::OnLineSubmit(const string &line) {
357 master.GetClient().SendMessage(1, 0, line);
362 MasterState::MasterState(
365 const World::Config &wc)
373 client.GetConnection().SetHandler(this);
376 void MasterState::Quit() {
377 if (!client.GetConnection().Closed()) {
380 env.state.PopUntil(this);
384 void MasterState::OnEnter() {
385 login_packet = client.SendLogin(config.player.name);
386 env.state.Push(&init_state);
390 void MasterState::Handle(const SDL_Event &event) {
395 void MasterState::Update(int dt) {
401 void MasterState::Render(Viewport &) {
406 void MasterState::OnPacketLost(uint16_t id) {
407 if (id == login_packet) {
408 login_packet = client.SendLogin(config.player.name);
412 void MasterState::OnTimeout() {
413 if (client.GetConnection().Closed()) {
415 env.ShowMessage("connection timed out");
419 void MasterState::On(const Packet::Join &pack) {
420 pack.ReadWorldName(world_conf.name);
424 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
427 cout << "joined game \"" << world_conf.name << '"' << endl;
428 // server received our login
433 pack.ReadPlayerID(player_id);
434 state.reset(new InteractiveState(*this, player_id));
436 EntityState player_state;
437 pack.ReadPlayerState(player_state);
438 state->GetPlayer().GetEntity().SetState(player_state);
440 env.state.PopAfter(this);
441 env.state.Push(state.get());
444 void MasterState::On(const Packet::Part &pack) {
448 env.ShowMessage("kicked by server");
451 env.ShowMessage("login refused by server");
455 void MasterState::On(const Packet::SpawnEntity &pack) {
457 cout << "got entity spawn before world was created" << endl;
463 void MasterState::On(const Packet::DespawnEntity &pack) {
465 cout << "got entity despawn before world was created" << endl;
471 void MasterState::On(const Packet::EntityUpdate &pack) {
473 cout << "got entity update before world was created" << endl;
479 void MasterState::On(const Packet::PlayerCorrection &pack) {
481 cout << "got player correction without a player :S" << endl;
487 void MasterState::On(const Packet::ChunkBegin &pack) {
489 cout << "got chunk data, but the world has not been created yet" << endl;
490 cout << "great, this will totally screw up everything :(" << endl;
493 state->GetChunkReceiver().Handle(pack);
496 void MasterState::On(const Packet::ChunkData &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::BlockUpdate &pack) {
507 cout << "received block update, but the world has not been created yet" << endl;
513 void MasterState::On(const Packet::Message &pack) {
518 pack.ReadMessage(msg);
519 cout << "got message before interface was created: " << msg << endl;