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())
62 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
64 , chat(master.GetEnv(), *this, *this) {
66 save.Write(master.GetWorldConf());
68 res.Load(master.GetEnv().loader, "default");
69 if (res.models.size() < 1) {
70 throw std::runtime_error("need at least one model to run");
72 res.models[0].Instantiate(player.GetEntity().GetModel());
73 sounds.Load(master.GetEnv().loader, res.snd_index);
74 interface.SetInventorySlots(res.block_types.size() - 1);
75 chunk_renderer.LoadTextures(master.GetEnv().loader, res.tex_index);
76 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
78 if (save.Exists(player)) {
83 void InteractiveState::OnResume() {
87 void InteractiveState::OnPause() {
91 void InteractiveState::OnFocus() {
92 if (master.GetConfig().input.mouse) {
93 master.GetEnv().window.GrabMouse();
98 void InteractiveState::OnBlur() {
99 master.GetEnv().window.ReleaseMouse();
103 void InteractiveState::Handle(const SDL_Event &event) {
104 switch (event.type) {
106 // TODO: move to interface
107 if (event.key.keysym.sym == SDLK_RETURN) {
108 master.GetEnv().state.Push(&chat);
109 hud.KeepMessages(true);
111 interface.HandlePress(event.key);
115 interface.HandleRelease(event.key);
117 case SDL_MOUSEBUTTONDOWN:
118 interface.HandlePress(event.button);
120 case SDL_MOUSEBUTTONUP:
121 interface.HandleRelease(event.button);
123 case SDL_MOUSEMOTION:
124 interface.Handle(event.motion);
127 interface.Handle(event.wheel);
137 void InteractiveState::Update(int dt) {
138 loop_timer.Update(dt);
140 chunk_receiver.Update(dt);
143 while (loop_timer.HitOnce()) {
144 world.Update(loop_timer.Interval());
145 world_dt += loop_timer.Interval();
146 loop_timer.PopIteration();
148 chunk_renderer.Update(dt);
150 if (input.BlockFocus()) {
151 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
152 } else if (input.EntityFocus()) {
153 hud.FocusEntity(*input.EntityFocus().entity);
158 input.PushPlayerUpdate(world_dt);
160 hud.Display(res.block_types[player.GetInventorySlot() + 1]);
163 glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
164 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
165 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
166 master.GetEnv().audio.Position(player.GetEntity().Position());
167 master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
168 master.GetEnv().audio.Orientation(dir, up);
171 void InteractiveState::Render(Viewport &viewport) {
172 viewport.WorldPosition(
173 player.GetEntity().Transform(player.GetEntity().ChunkCoords())
174 * player.GetEntity().GetModel().EyesTransform());
175 if (master.GetConfig().video.world) {
176 chunk_renderer.Render(viewport);
177 world.Render(viewport);
178 sky.Render(viewport);
180 hud.Render(viewport);
183 void InteractiveState::Handle(const Packet::SpawnEntity &pack) {
185 pack.ReadEntityID(entity_id);
186 Entity &entity = world.ForceAddEntity(entity_id);
187 UpdateEntity(entity_id, pack.Seq());
188 pack.ReadEntity(entity);
190 pack.ReadModelID(model_id);
191 if (model_id > 0 && model_id <= res.models.size()) {
192 res.models.Get(model_id).Instantiate(entity.GetModel());
194 cout << "spawned entity #" << entity_id << " (" << entity.Name()
195 << ") at " << entity.AbsolutePosition() << endl;
198 void InteractiveState::Handle(const Packet::DespawnEntity &pack) {
200 pack.ReadEntityID(entity_id);
201 ClearEntity(entity_id);
202 for (Entity &entity : world.Entities()) {
203 if (entity.ID() == entity_id) {
205 cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
211 void InteractiveState::Handle(const Packet::EntityUpdate &pack) {
212 auto world_iter = world.Entities().begin();
213 auto world_end = world.Entities().end();
217 pack.ReadEntityCount(count);
218 pack.ReadChunkBase(base);
221 for (uint32_t i = 0; i < count; ++i) {
222 uint32_t entity_id = 0;
223 pack.ReadEntityID(entity_id, i);
225 while (world_iter != world_end && world_iter->ID() < entity_id) {
228 if (world_iter == world_end) {
229 // nothing can be done from here
232 if (world_iter->ID() == entity_id) {
233 if (UpdateEntity(entity_id, pack.Seq())) {
234 pack.ReadEntityState(state, base, i);
235 world_iter->SetState(state);
241 bool InteractiveState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
242 auto entry = update_status.find(entity_id);
243 if (entry == update_status.end()) {
244 update_status.emplace(entity_id, UpdateStatus{ seq, loop_timer.Elapsed() });
248 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
249 int time_diff = loop_timer.Elapsed() - entry->second.last_update;
250 entry->second.last_update = loop_timer.Elapsed();
252 if (pack_diff > 0 || time_diff > 1500) {
253 entry->second.last_packet = seq;
260 void InteractiveState::ClearEntity(uint32_t entity_id) {
261 update_status.erase(entity_id);
264 void InteractiveState::Handle(const Packet::PlayerCorrection &pack) {
266 EntityState corrected_state;
267 pack.ReadPacketSeq(pack_seq);
268 pack.ReadPlayerState(corrected_state);
269 input.MergePlayerCorrection(pack_seq, corrected_state);
272 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
274 pack.ReadChunkCoords(pos);
275 Chunk *chunk = player.GetChunks().Get(pos);
277 // this change doesn't concern us
281 pack.ReadBlockCount(count);
282 for (uint32_t i = 0; i < count; ++i) {
285 pack.ReadIndex(index, i);
286 pack.ReadBlock(block, i);
287 if (index < Chunk::size && block.type < res.block_types.size()) {
288 manip.SetBlock(*chunk, index, block);
293 void InteractiveState::Handle(const Packet::Message &pack) {
295 pack.ReadMessage(msg);
296 hud.PostMessage(msg);
299 void InteractiveState::SetAudio(bool b) {
300 master.GetConfig().audio.enabled = b;
302 hud.PostMessage("Audio enabled");
304 hud.PostMessage("Audio disabled");
308 void InteractiveState::SetVideo(bool b) {
309 master.GetConfig().video.world = b;
311 hud.PostMessage("World rendering enabled");
313 hud.PostMessage("World rendering disabled");
317 void InteractiveState::SetHUD(bool b) {
318 master.GetConfig().video.hud = b;
320 hud.PostMessage("HUD rendering enabled");
322 hud.PostMessage("HUD rendering disabled");
326 void InteractiveState::SetDebug(bool b) {
327 master.GetConfig().video.debug = b;
329 hud.PostMessage("Debug rendering enabled");
331 hud.PostMessage("Debug rendering disabled");
335 void InteractiveState::Exit() {
340 void InteractiveState::OnLineSubmit(const string &line) {
342 master.GetClient().SendMessage(1, 0, line);
347 MasterState::MasterState(
350 const World::Config &wc)
358 client.GetConnection().SetHandler(this);
361 void MasterState::Quit() {
362 if (!client.GetConnection().Closed()) {
365 env.state.PopUntil(this);
369 void MasterState::OnEnter() {
370 login_packet = client.SendLogin(config.player.name);
371 env.state.Push(&init_state);
375 void MasterState::Handle(const SDL_Event &event) {
380 void MasterState::Update(int dt) {
386 void MasterState::Render(Viewport &) {
391 void MasterState::OnPacketLost(uint16_t id) {
392 if (id == login_packet) {
393 login_packet = client.SendLogin(config.player.name);
397 void MasterState::OnTimeout() {
398 if (client.GetConnection().Closed()) {
400 env.ShowMessage("connection timed out");
404 void MasterState::On(const Packet::Join &pack) {
405 pack.ReadWorldName(world_conf.name);
409 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
412 cout << "joined game \"" << world_conf.name << '"' << endl;
413 // server received our login
418 pack.ReadPlayerID(player_id);
419 state.reset(new InteractiveState(*this, player_id));
421 EntityState player_state;
422 pack.ReadPlayerState(player_state);
423 state->GetPlayer().GetEntity().SetState(player_state);
425 env.state.PopAfter(this);
426 env.state.Push(state.get());
429 void MasterState::On(const Packet::Part &pack) {
433 env.ShowMessage("kicked by server");
436 env.ShowMessage("login refused by server");
440 void MasterState::On(const Packet::SpawnEntity &pack) {
442 cout << "got entity spawn before world was created" << endl;
448 void MasterState::On(const Packet::DespawnEntity &pack) {
450 cout << "got entity despawn before world was created" << endl;
456 void MasterState::On(const Packet::EntityUpdate &pack) {
458 cout << "got entity update before world was created" << endl;
464 void MasterState::On(const Packet::PlayerCorrection &pack) {
466 cout << "got player correction without a player :S" << endl;
472 void MasterState::On(const Packet::ChunkBegin &pack) {
474 cout << "got chunk data, but the world has not been created yet" << endl;
475 cout << "great, this will totally screw up everything :(" << endl;
478 state->GetChunkReceiver().Handle(pack);
481 void MasterState::On(const Packet::ChunkData &pack) {
483 cout << "got chunk data, but the world has not been created yet" << endl;
484 cout << "great, this will totally screw up everything :(" << endl;
487 state->GetChunkReceiver().Handle(pack);
490 void MasterState::On(const Packet::BlockUpdate &pack) {
492 cout << "received block update, but the world has not been created yet" << endl;
498 void MasterState::On(const Packet::Message &pack) {
503 pack.ReadMessage(msg);
504 cout << "got message before interface was created: " << msg << endl;