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 save.Write(master.GetWorldConf());
69 res.Load(master.GetEnv().loader, "default");
70 if (res.models.size() < 1) {
71 throw std::runtime_error("need at least one model to run");
73 res.models[0].Instantiate(player.GetEntity().GetModel());
74 sounds.Load(master.GetEnv().loader, res.snd_index);
75 interface.SetInventorySlots(res.block_types.size() - 1);
76 chunk_renderer.LoadTextures(master.GetEnv().loader, res.tex_index);
77 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
80 if (save.Exists(player)) {
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().entity);
166 input.PushPlayerUpdate(world_dt);
168 hud.Display(res.block_types[player.GetInventorySlot() + 1]);
169 if (stat_timer.Hit()) {
170 hud.UpdateNetStats(master);
174 glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
175 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
176 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
177 master.GetEnv().audio.Position(player.GetEntity().Position());
178 master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
179 master.GetEnv().audio.Orientation(dir, up);
182 void InteractiveState::Render(Viewport &viewport) {
183 viewport.WorldPosition(
184 player.GetEntity().Transform(player.GetEntity().ChunkCoords())
185 * player.GetEntity().GetModel().EyesTransform());
186 if (master.GetConfig().video.world) {
187 chunk_renderer.Render(viewport);
188 world.Render(viewport);
189 sky.Render(viewport);
191 hud.Render(viewport);
194 void InteractiveState::Handle(const Packet::SpawnEntity &pack) {
196 pack.ReadEntityID(entity_id);
197 Entity &entity = world.ForceAddEntity(entity_id);
198 UpdateEntity(entity_id, pack.Seq());
199 pack.ReadEntity(entity);
201 pack.ReadModelID(model_id);
202 if (model_id > 0 && model_id <= res.models.size()) {
203 res.models.Get(model_id).Instantiate(entity.GetModel());
207 void InteractiveState::Handle(const Packet::DespawnEntity &pack) {
209 pack.ReadEntityID(entity_id);
210 ClearEntity(entity_id);
211 for (Entity &entity : world.Entities()) {
212 if (entity.ID() == entity_id) {
219 void InteractiveState::Handle(const Packet::EntityUpdate &pack) {
220 auto world_iter = world.Entities().begin();
221 auto world_end = world.Entities().end();
225 pack.ReadEntityCount(count);
226 pack.ReadChunkBase(base);
229 for (uint32_t i = 0; i < count; ++i) {
230 uint32_t entity_id = 0;
231 pack.ReadEntityID(entity_id, i);
233 while (world_iter != world_end && world_iter->ID() < entity_id) {
236 if (world_iter == world_end) {
237 // nothing can be done from here
240 if (world_iter->ID() == entity_id) {
241 if (UpdateEntity(entity_id, pack.Seq())) {
242 pack.ReadEntityState(state, base, i);
243 world_iter->SetState(state);
249 bool InteractiveState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
250 auto entry = update_status.find(entity_id);
251 if (entry == update_status.end()) {
252 update_status.emplace(entity_id, UpdateStatus{ seq, loop_timer.Elapsed() });
256 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
257 int time_diff = loop_timer.Elapsed() - entry->second.last_update;
258 entry->second.last_update = loop_timer.Elapsed();
260 if (pack_diff > 0 || time_diff > 1500) {
261 entry->second.last_packet = seq;
268 void InteractiveState::ClearEntity(uint32_t entity_id) {
269 update_status.erase(entity_id);
272 void InteractiveState::Handle(const Packet::PlayerCorrection &pack) {
274 EntityState corrected_state;
275 pack.ReadPacketSeq(pack_seq);
276 pack.ReadPlayerState(corrected_state);
277 input.MergePlayerCorrection(pack_seq, corrected_state);
280 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
282 pack.ReadChunkCoords(pos);
283 Chunk *chunk = player.GetChunks().Get(pos);
285 // this change doesn't concern us
289 pack.ReadBlockCount(count);
290 for (uint32_t i = 0; i < count; ++i) {
293 pack.ReadIndex(index, i);
294 pack.ReadBlock(block, i);
295 if (index < Chunk::size && block.type < res.block_types.size()) {
296 manip.SetBlock(*chunk, index, block);
301 void InteractiveState::Handle(const Packet::Message &pack) {
303 pack.ReadMessage(msg);
304 hud.PostMessage(msg);
307 void InteractiveState::SetAudio(bool b) {
308 master.GetConfig().audio.enabled = b;
310 hud.PostMessage("Audio enabled");
312 hud.PostMessage("Audio disabled");
316 void InteractiveState::SetVideo(bool b) {
317 master.GetConfig().video.world = b;
319 hud.PostMessage("World rendering enabled");
321 hud.PostMessage("World rendering disabled");
325 void InteractiveState::SetHUD(bool b) {
326 master.GetConfig().video.hud = b;
328 hud.PostMessage("HUD rendering enabled");
330 hud.PostMessage("HUD rendering disabled");
334 void InteractiveState::SetDebug(bool b) {
335 master.GetConfig().video.debug = b;
337 hud.PostMessage("Debug rendering enabled");
339 hud.PostMessage("Debug rendering disabled");
343 void InteractiveState::Exit() {
348 void InteractiveState::OnLineSubmit(const string &line) {
350 master.GetClient().SendMessage(1, 0, line);
355 MasterState::MasterState(
358 const World::Config &wc)
366 client.GetConnection().SetHandler(this);
369 void MasterState::Quit() {
370 if (!client.GetConnection().Closed()) {
373 env.state.PopUntil(this);
377 void MasterState::OnEnter() {
378 login_packet = client.SendLogin(config.player.name);
379 env.state.Push(&init_state);
383 void MasterState::Handle(const SDL_Event &event) {
388 void MasterState::Update(int dt) {
394 void MasterState::Render(Viewport &) {
399 void MasterState::OnPacketLost(uint16_t id) {
400 if (id == login_packet) {
401 login_packet = client.SendLogin(config.player.name);
405 void MasterState::OnTimeout() {
406 if (client.GetConnection().Closed()) {
408 env.ShowMessage("connection timed out");
412 void MasterState::On(const Packet::Join &pack) {
413 pack.ReadWorldName(world_conf.name);
417 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
420 cout << "joined game \"" << world_conf.name << '"' << endl;
421 // server received our login
426 pack.ReadPlayerID(player_id);
427 state.reset(new InteractiveState(*this, player_id));
429 EntityState player_state;
430 pack.ReadPlayerState(player_state);
431 state->GetPlayer().GetEntity().SetState(player_state);
433 env.state.PopAfter(this);
434 env.state.Push(state.get());
437 void MasterState::On(const Packet::Part &pack) {
441 env.ShowMessage("kicked by server");
444 env.ShowMessage("login refused by server");
448 void MasterState::On(const Packet::SpawnEntity &pack) {
450 cout << "got entity spawn before world was created" << endl;
456 void MasterState::On(const Packet::DespawnEntity &pack) {
458 cout << "got entity despawn before world was created" << endl;
464 void MasterState::On(const Packet::EntityUpdate &pack) {
466 cout << "got entity update before world was created" << endl;
472 void MasterState::On(const Packet::PlayerCorrection &pack) {
474 cout << "got player correction without a player :S" << endl;
480 void MasterState::On(const Packet::ChunkBegin &pack) {
482 cout << "got chunk data, but the world has not been created yet" << endl;
483 cout << "great, this will totally screw up everything :(" << endl;
486 state->GetChunkReceiver().Handle(pack);
489 void MasterState::On(const Packet::ChunkData &pack) {
491 cout << "got chunk data, but the world has not been created yet" << endl;
492 cout << "great, this will totally screw up everything :(" << endl;
495 state->GetChunkReceiver().Handle(pack);
498 void MasterState::On(const Packet::BlockUpdate &pack) {
500 cout << "received block update, but the world has not been created yet" << endl;
506 void MasterState::On(const Packet::Message &pack) {
511 pack.ReadMessage(msg);
512 cout << "got message before interface was created: " << msg << endl;