]> git.localhorst.tv Git - blank.git/blob - client/client.cpp
new gcc version
[blank.git] / client / client.cpp
1 #include "InitialState.hpp"
2 #include "InteractiveState.hpp"
3 #include "MasterState.hpp"
4
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"
12
13 #include <iostream>
14 #include <glm/gtx/io.hpp>
15
16 using namespace std;
17
18
19 namespace blank {
20 namespace client {
21
22 InitialState::InitialState(MasterState &master)
23 : master(master)
24 , message() {
25         message.Position(glm::vec3(0.0f), Gravity::CENTER);
26         message.Set(master.GetEnv().assets.large_ui_font, "logging in");
27 }
28
29 void InitialState::OnEnter() {
30
31 }
32
33 void InitialState::Handle(const SDL_Event &evt) {
34         if (evt.type == SDL_QUIT) {
35                 master.Quit();
36         }
37 }
38
39 void InitialState::Update(int dt) {
40         master.Update(dt);
41 }
42
43 void InitialState::Render(Viewport &viewport) {
44         message.Render(viewport);
45 }
46
47
48 // TODO: this clutter is a giant mess
49 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
50 : master(master)
51 , res()
52 , sounds()
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())
62 , loop_timer(16)
63 , stat_timer(1000)
64 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
65 , update_status()
66 , chat(master.GetEnv(), *this, *this)
67 , time_skipped(0)
68 , packets_skipped(0) {
69         if (!save.Exists()) {
70                 save.Write(master.GetWorldConf());
71         }
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");
75         }
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);
81         loop_timer.Start();
82         stat_timer.Start();
83 }
84
85 void InteractiveState::OnResume() {
86         OnFocus();
87 }
88
89 void InteractiveState::OnPause() {
90         OnBlur();
91 }
92
93 void InteractiveState::OnFocus() {
94         if (master.GetConfig().input.mouse) {
95                 master.GetEnv().window.GrabMouse();
96         }
97         interface.Unlock();
98 }
99
100 void InteractiveState::OnBlur() {
101         master.GetEnv().window.ReleaseMouse();
102         interface.Lock();
103 }
104
105 void InteractiveState::Handle(const SDL_Event &event) {
106         switch (event.type) {
107                 case SDL_KEYDOWN:
108                         // TODO: move to interface
109                         if (event.key.keysym.sym == SDLK_RETURN) {
110                                 chat.Clear();
111                                 master.GetEnv().state.Push(&chat);
112                                 hud.KeepMessages(true);
113                         } else if (event.key.keysym.sym == SDLK_SLASH) {
114                                 chat.Preset("/");
115                                 master.GetEnv().state.Push(&chat);
116                                 hud.KeepMessages(true);
117                         } else {
118                                 interface.HandlePress(event.key);
119                         }
120                         break;
121                 case SDL_KEYUP:
122                         interface.HandleRelease(event.key);
123                         break;
124                 case SDL_MOUSEBUTTONDOWN:
125                         interface.HandlePress(event.button);
126                         break;
127                 case SDL_MOUSEBUTTONUP:
128                         interface.HandleRelease(event.button);
129                         break;
130                 case SDL_MOUSEMOTION:
131                         interface.Handle(event.motion);
132                         break;
133                 case SDL_MOUSEWHEEL:
134                         interface.Handle(event.wheel);
135                         break;
136                 case SDL_QUIT:
137                         Exit();
138                         break;
139                 default:
140                         break;
141         }
142 }
143
144 void InteractiveState::Update(int dt) {
145         loop_timer.Update(dt);
146         stat_timer.Update(dt);
147         master.Update(dt);
148         chunk_receiver.Update(dt);
149
150         int world_dt = 0;
151         while (loop_timer.HitOnce()) {
152                 world.Update(loop_timer.Interval());
153                 world_dt += loop_timer.Interval();
154                 loop_timer.PopIteration();
155         }
156         chunk_renderer.Update(dt);
157
158         if (input.BlockFocus()) {
159                 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
160         } else if (input.EntityFocus()) {
161                 hud.FocusEntity(input.EntityFocus().GetEntity());
162         } else {
163                 hud.FocusNone();
164         }
165         if (world_dt > 0) {
166                 if (input.UpdateImportant() || packets_skipped >= master.NetStat().SuggestedPacketSkip()) {
167                         input.PushPlayerUpdate(time_skipped + world_dt);
168                         time_skipped = 0;
169                         packets_skipped = 0;
170                 } else {
171                         time_skipped += world_dt;
172                         ++packets_skipped;
173                 }
174         }
175         hud.Display(res.block_types[player.GetInventorySlot() + 1]);
176         if (stat_timer.Hit()) {
177                 hud.UpdateNetStats(master.NetStat());
178         }
179         hud.Update(dt);
180
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);
187 }
188
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);
196                 }
197                 sky.Render(viewport);
198         }
199         hud.Render(viewport);
200 }
201
202 void InteractiveState::Handle(const Packet::SpawnEntity &pack) {
203         uint32_t entity_id;
204         pack.ReadEntityID(entity_id);
205         Entity &entity = world.ForceAddEntity(entity_id);
206         UpdateEntity(entity_id, pack.Seq());
207         pack.ReadEntity(entity);
208         uint32_t model_id;
209         pack.ReadModelID(model_id);
210         if (model_id > 0 && model_id <= res.models.size()) {
211                 res.models.Get(model_id).Instantiate(entity.GetModel());
212         }
213 }
214
215 void InteractiveState::Handle(const Packet::DespawnEntity &pack) {
216         uint32_t entity_id;
217         pack.ReadEntityID(entity_id);
218         ClearEntity(entity_id);
219         for (Entity &entity : world.Entities()) {
220                 if (entity.ID() == entity_id) {
221                         entity.Kill();
222                         return;
223                 }
224         }
225 }
226
227 void InteractiveState::Handle(const Packet::EntityUpdate &pack) {
228         auto world_iter = world.Entities().begin();
229         auto world_end = world.Entities().end();
230
231         uint32_t count = 0;
232         glm::ivec3 base;
233         pack.ReadEntityCount(count);
234         pack.ReadChunkBase(base);
235         EntityState state;
236
237         for (uint32_t i = 0; i < count; ++i) {
238                 uint32_t entity_id = 0;
239                 pack.ReadEntityID(entity_id, i);
240
241                 while (world_iter != world_end && world_iter->ID() < entity_id) {
242                         ++world_iter;
243                 }
244                 if (world_iter == world_end) {
245                         // nothing can be done from here
246                         return;
247                 }
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);
252                         }
253                 }
254         }
255 }
256
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() });
261                 return true;
262         }
263
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();
267
268         if (pack_diff > 0 || time_diff > 1500) {
269                 entry->second.last_packet = seq;
270                 return true;
271         } else {
272                 return false;
273         }
274 }
275
276 void InteractiveState::ClearEntity(uint32_t entity_id) {
277         update_status.erase(entity_id);
278 }
279
280 void InteractiveState::Handle(const Packet::PlayerCorrection &pack) {
281         uint16_t pack_seq;
282         EntityState corrected_state;
283         pack.ReadPacketSeq(pack_seq);
284         pack.ReadPlayerState(corrected_state);
285         input.MergePlayerCorrection(pack_seq, corrected_state);
286 }
287
288 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
289         glm::ivec3 pos;
290         pack.ReadChunkCoords(pos);
291         Chunk *chunk = player.GetChunks().Get(pos);
292         if (!chunk) {
293                 // this change doesn't concern us
294                 return;
295         }
296         uint32_t count = 0;
297         pack.ReadBlockCount(count);
298         for (uint32_t i = 0; i < count; ++i) {
299                 uint16_t index;
300                 Block block;
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);
305                 }
306         }
307 }
308
309 void InteractiveState::Handle(const Packet::Message &pack) {
310         string msg;
311         pack.ReadMessage(msg);
312         hud.PostMessage(msg);
313 }
314
315 void InteractiveState::SetAudio(bool b) {
316         master.GetConfig().audio.enabled = b;
317         if (b) {
318                 hud.PostMessage("Audio enabled");
319         } else {
320                 hud.PostMessage("Audio disabled");
321         }
322 }
323
324 void InteractiveState::SetVideo(bool b) {
325         master.GetConfig().video.world = b;
326         if (b) {
327                 hud.PostMessage("World rendering enabled");
328         } else {
329                 hud.PostMessage("World rendering disabled");
330         }
331 }
332
333 void InteractiveState::SetHUD(bool b) {
334         master.GetConfig().video.hud = b;
335         if (b) {
336                 hud.PostMessage("HUD rendering enabled");
337         } else {
338                 hud.PostMessage("HUD rendering disabled");
339         }
340 }
341
342 void InteractiveState::SetDebug(bool b) {
343         master.GetConfig().video.debug = b;
344         if (b) {
345                 hud.PostMessage("Debug rendering enabled");
346         } else {
347                 hud.PostMessage("Debug rendering disabled");
348         }
349 }
350
351 void InteractiveState::NextCamera() {
352         if (iszero(master.GetEnv().viewport.CameraOffset())) {
353                 master.GetEnv().viewport.OffsetCamera(glm::vec3(0.0f, 0.0f, -5.0f));
354         } else {
355                 master.GetEnv().viewport.OffsetCamera(glm::vec3(0.0f, 0.0f, 0.0f));
356         }
357 }
358
359 void InteractiveState::Exit() {
360         save.Write(player);
361         master.Quit();
362 }
363
364 void InteractiveState::OnLineSubmit(const string &line) {
365         if (!line.empty()) {
366                 master.GetClient().SendMessage(1, 0, line);
367         }
368 }
369
370
371 MasterState::MasterState(
372         Environment &env,
373         Config &config,
374         const World::Config &wc)
375 : env(env)
376 , config(config)
377 , world_conf(wc)
378 , state()
379 , client(config.net)
380 , init_state(*this)
381 , login_packet(-1) {
382         client.GetConnection().SetHandler(this);
383 }
384
385 void MasterState::Quit() {
386         if (!client.GetConnection().Closed()) {
387                 client.SendPart();
388         }
389         env.state.PopUntil(this);
390 }
391
392
393 void MasterState::OnEnter() {
394         login_packet = client.SendLogin(config.player.name);
395         env.state.Push(&init_state);
396 }
397
398
399 void MasterState::Handle(const SDL_Event &) {
400
401 }
402
403
404 void MasterState::Update(int dt) {
405         client.Handle();
406         client.Update(dt);
407 }
408
409
410 void MasterState::Render(Viewport &) {
411
412 }
413
414
415 void MasterState::OnPacketLost(uint16_t id) {
416         if (id == login_packet) {
417                 login_packet = client.SendLogin(config.player.name);
418         }
419 }
420
421 void MasterState::OnTimeout() {
422         if (client.GetConnection().Closed()) {
423                 Quit();
424                 env.ShowMessage("connection timed out");
425         }
426 }
427
428 void MasterState::On(const Packet::Join &pack) {
429         pack.ReadWorldName(world_conf.name);
430
431         if (state) {
432                 // changing worlds
433                 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
434         } else {
435                 // joining game
436                 cout << "joined game \"" << world_conf.name << '"' << endl;
437                 // server received our login
438                 login_packet = -1;
439         }
440
441         uint32_t player_id;
442         pack.ReadPlayerID(player_id);
443         state.reset(new InteractiveState(*this, player_id));
444
445         EntityState player_state;
446         pack.ReadPlayerState(player_state);
447         state->GetPlayer().GetEntity().SetState(player_state);
448
449         env.state.PopAfter(this);
450         env.state.Push(state.get());
451 }
452
453 void MasterState::On(const Packet::Part &) {
454         Quit();
455         if (state) {
456                 // kicked
457                 env.ShowMessage("kicked by server");
458         } else {
459                 // join refused
460                 env.ShowMessage("login refused by server");
461         }
462 }
463
464 void MasterState::On(const Packet::SpawnEntity &pack) {
465         if (!state) {
466                 cout << "got entity spawn before world was created" << endl;
467                 return;
468         }
469         state->Handle(pack);
470 }
471
472 void MasterState::On(const Packet::DespawnEntity &pack) {
473         if (!state) {
474                 cout << "got entity despawn before world was created" << endl;
475                 return;
476         }
477         state->Handle(pack);
478 }
479
480 void MasterState::On(const Packet::EntityUpdate &pack) {
481         if (!state) {
482                 cout << "got entity update before world was created" << endl;
483                 return;
484         }
485         state->Handle(pack);
486 }
487
488 void MasterState::On(const Packet::PlayerCorrection &pack) {
489         if (!state) {
490                 cout << "got player correction without a player :S" << endl;
491                 return;
492         }
493         state->Handle(pack);
494 }
495
496 void MasterState::On(const Packet::ChunkBegin &pack) {
497         if (!state) {
498                 cout << "got chunk data, but the world has not been created yet" << endl;
499                 cout << "great, this will totally screw up everything :(" << endl;
500                 return;
501         }
502         state->GetChunkReceiver().Handle(pack);
503 }
504
505 void MasterState::On(const Packet::ChunkData &pack) {
506         if (!state) {
507                 cout << "got chunk data, but the world has not been created yet" << endl;
508                 cout << "great, this will totally screw up everything :(" << endl;
509                 return;
510         }
511         state->GetChunkReceiver().Handle(pack);
512 }
513
514 void MasterState::On(const Packet::BlockUpdate &pack) {
515         if (!state) {
516                 cout << "received block update, but the world has not been created yet" << endl;
517                 return;
518         }
519         state->Handle(pack);
520 }
521
522 void MasterState::On(const Packet::Message &pack) {
523         if (state) {
524                 state->Handle(pack);
525         } else {
526                 string msg;
527                 pack.ReadMessage(msg);
528                 cout << "got message before interface was created: " << msg << endl;
529         }
530 }
531
532 }
533 }