]> git.localhorst.tv Git - blank.git/blob - src/client/client.cpp
exchange block updates with clients
[blank.git] / src / client / client.cpp
1 #include "ChunkRequester.hpp"
2 #include "InitialState.hpp"
3 #include "InteractiveState.hpp"
4 #include "MasterState.hpp"
5
6 #include "../app/Environment.hpp"
7 #include "../app/init.hpp"
8 #include "../app/TextureIndex.hpp"
9 #include "../model/CompositeModel.hpp"
10 #include "../io/WorldSave.hpp"
11 #include "../world/ChunkIndex.hpp"
12 #include "../world/ChunkStore.hpp"
13
14 #include <iostream>
15 #include <glm/gtx/io.hpp>
16
17 using namespace std;
18
19
20 namespace blank {
21 namespace client {
22
23 ChunkRequester::ChunkRequester(
24         ChunkStore &store,
25         const WorldSave &save
26 ) noexcept
27 : store(store)
28 , save(save) {
29
30 }
31
32 void ChunkRequester::Update(int dt) {
33         // check if there's chunks waiting to be loaded
34         LoadN(10);
35
36         // store a few chunks as well
37         constexpr int max_save = 10;
38         int saved = 0;
39         for (Chunk &chunk : store) {
40                 if (chunk.ShouldUpdateSave()) {
41                         save.Write(chunk);
42                         ++saved;
43                         if (saved >= max_save) {
44                                 break;
45                         }
46                 }
47         }
48 }
49
50 int ChunkRequester::ToLoad() const noexcept {
51         return store.EstimateMissing();
52 }
53
54 void ChunkRequester::LoadOne() {
55         if (!store.HasMissing()) return;
56
57         Chunk::Pos pos = store.NextMissing();
58         Chunk *chunk = store.Allocate(pos);
59         if (!chunk) {
60                 // chunk store corrupted?
61                 return;
62         }
63
64         if (save.Exists(pos)) {
65                 save.Read(*chunk);
66                 // TODO: request chunk from server with cache tag
67         } else {
68                 // TODO: request chunk from server
69         }
70 }
71
72 void ChunkRequester::LoadN(std::size_t n) {
73         std::size_t end = std::min(n, std::size_t(ToLoad()));
74         for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
75                 LoadOne();
76         }
77 }
78
79
80 InitialState::InitialState(MasterState &master)
81 : master(master)
82 , message() {
83         message.Position(glm::vec3(0.0f), Gravity::CENTER);
84         message.Set(master.GetEnv().assets.large_ui_font, "logging in");
85 }
86
87 void InitialState::OnEnter() {
88
89 }
90
91 void InitialState::Handle(const SDL_Event &evt) {
92         if (evt.type == SDL_QUIT) {
93                 master.Quit();
94         }
95 }
96
97 void InitialState::Update(int dt) {
98         master.Update(dt);
99 }
100
101 void InitialState::Render(Viewport &viewport) {
102         message.Render(viewport);
103 }
104
105
106 // TODO: this clutter is a giant mess
107 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
108 : master(master)
109 , block_types()
110 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetConfig().net.host))
111 , world(block_types, master.GetWorldConf())
112 , player(*world.AddPlayer(master.GetConfig().player.name))
113 , hud(master.GetEnv(), master.GetConfig(), player)
114 , manip(master.GetEnv(), player.GetEntity())
115 , input(world, player, master.GetClient())
116 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
117 // TODO: looks like chunk requester and receiver can and should be merged
118 , chunk_requester(world.Chunks(), save)
119 , chunk_receiver(world.Chunks())
120 , chunk_renderer(player.GetChunks())
121 , skeletons()
122 , loop_timer(16)
123 , sky(master.GetEnv().loader.LoadCubeMap("skybox")) {
124         if (!save.Exists()) {
125                 save.Write(master.GetWorldConf());
126         }
127         TextureIndex tex_index;
128         master.GetEnv().loader.LoadBlockTypes("default", block_types, tex_index);
129         interface.SetInventorySlots(block_types.Size() - 1);
130         chunk_renderer.LoadTextures(master.GetEnv().loader, tex_index);
131         chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
132         skeletons.Load();
133         loop_timer.Start();
134 }
135
136 void InteractiveState::OnEnter() {
137         master.GetEnv().window.GrabMouse();
138 }
139
140 void InteractiveState::Handle(const SDL_Event &event) {
141         switch (event.type) {
142                 case SDL_KEYDOWN:
143                         interface.HandlePress(event.key);
144                         break;
145                 case SDL_KEYUP:
146                         interface.HandleRelease(event.key);
147                         break;
148                 case SDL_MOUSEBUTTONDOWN:
149                         interface.HandlePress(event.button);
150                         break;
151                 case SDL_MOUSEBUTTONUP:
152                         interface.HandleRelease(event.button);
153                         break;
154                 case SDL_MOUSEMOTION:
155                         interface.Handle(event.motion);
156                         break;
157                 case SDL_MOUSEWHEEL:
158                         interface.Handle(event.wheel);
159                         break;
160                 case SDL_QUIT:
161                         master.Quit();
162                         break;
163                 default:
164                         break;
165         }
166 }
167
168 void InteractiveState::Update(int dt) {
169         input.Update(dt);
170         if (input.BlockFocus()) {
171                 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
172         } else if (input.EntityFocus()) {
173                 hud.FocusEntity(*input.EntityFocus().entity);
174         } else {
175                 hud.FocusNone();
176         }
177         hud.Display(block_types[player.GetInventorySlot() + 1]);
178         loop_timer.Update(dt);
179         master.Update(dt);
180         chunk_receiver.Update(dt);
181         chunk_requester.Update(dt);
182
183         hud.Update(dt);
184         int world_dt = 0;
185         while (loop_timer.HitOnce()) {
186                 world.Update(loop_timer.Interval());
187                 world_dt += loop_timer.Interval();
188                 loop_timer.PopIteration();
189         }
190         chunk_renderer.Update(dt);
191
192         if (world_dt > 0) {
193                 input.PushPlayerUpdate(world_dt);
194         }
195
196         glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
197         glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
198         glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
199         master.GetEnv().audio.Position(player.GetEntity().Position());
200         master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
201         master.GetEnv().audio.Orientation(dir, up);
202 }
203
204 void InteractiveState::Render(Viewport &viewport) {
205         viewport.WorldPosition(player.GetEntity().Transform(player.GetEntity().ChunkCoords()));
206         if (master.GetConfig().video.world) {
207                 chunk_renderer.Render(viewport);
208                 world.Render(viewport);
209                 sky.Render(viewport);
210         }
211         hud.Render(viewport);
212 }
213
214 void InteractiveState::MergePlayerCorrection(std::uint16_t pack, const EntityState &state) {
215         input.MergePlayerCorrection(pack, state);
216 }
217
218 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
219         glm::ivec3 pos;
220         pack.ReadChunkCoords(pos);
221         Chunk *chunk = player.GetChunks().Get(pos);
222         if (!chunk) {
223                 // this change doesn't concern us
224                 return;
225         }
226         uint32_t count = 0;
227         pack.ReadBlockCount(count);
228         for (uint32_t i = 0; i < count; ++i) {
229                 uint16_t index;
230                 Block block;
231                 pack.ReadIndex(index, i);
232                 pack.ReadBlock(block, i);
233                 if (index < Chunk::size && block.type < block_types.Size()) {
234                         manip.SetBlock(*chunk, index, block);
235                 }
236         }
237 }
238
239 void InteractiveState::SetAudio(bool b) {
240         master.GetConfig().audio.enabled = b;
241         if (b) {
242                 hud.PostMessage("Audio enabled");
243         } else {
244                 hud.PostMessage("Audio disabled");
245         }
246 }
247
248 void InteractiveState::SetVideo(bool b) {
249         master.GetConfig().video.world = b;
250         if (b) {
251                 hud.PostMessage("World rendering enabled");
252         } else {
253                 hud.PostMessage("World rendering disabled");
254         }
255 }
256
257 void InteractiveState::SetHUD(bool b) {
258         master.GetConfig().video.hud = b;
259         if (b) {
260                 hud.PostMessage("HUD rendering enabled");
261         } else {
262                 hud.PostMessage("HUD rendering disabled");
263         }
264 }
265
266 void InteractiveState::SetDebug(bool b) {
267         master.GetConfig().video.debug = b;
268         if (b) {
269                 hud.PostMessage("Debug rendering enabled");
270         } else {
271                 hud.PostMessage("Debug rendering disabled");
272         }
273 }
274
275 void InteractiveState::Exit() {
276         master.Quit();
277 }
278
279
280 MasterState::MasterState(
281         Environment &env,
282         Config &config,
283         const World::Config &wc)
284 : env(env)
285 , config(config)
286 , world_conf(wc)
287 , state()
288 , client(config.net)
289 , init_state(*this)
290 , login_packet(-1)
291 , update_status()
292 , update_timer(16) {
293         client.GetConnection().SetHandler(this);
294         update_timer.Start();
295 }
296
297 void MasterState::Quit() {
298         if (!client.GetConnection().Closed()) {
299                 client.SendPart();
300         }
301         env.state.PopUntil(this);
302 }
303
304
305 void MasterState::OnEnter() {
306         login_packet = client.SendLogin(config.player.name);
307         env.state.Push(&init_state);
308 }
309
310
311 void MasterState::Handle(const SDL_Event &event) {
312
313 }
314
315
316 void MasterState::Update(int dt) {
317         update_timer.Update(dt);
318         client.Handle();
319         client.Update(dt);
320 }
321
322
323 void MasterState::Render(Viewport &) {
324
325 }
326
327
328 void MasterState::OnPacketLost(uint16_t id) {
329         if (id == login_packet) {
330                 login_packet = client.SendLogin(config.player.name);
331         }
332 }
333
334 void MasterState::OnTimeout() {
335         if (client.GetConnection().Closed()) {
336                 // TODO: push disconnected message
337                 cout << "connection timed out" << endl;
338                 Quit();
339         }
340 }
341
342 void MasterState::On(const Packet::Join &pack) {
343         pack.ReadWorldName(world_conf.name);
344
345         if (state) {
346                 // changing worlds
347                 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
348         } else {
349                 // joining game
350                 cout << "joined game \"" << world_conf.name << '"' << endl;
351                 // server received our login
352                 login_packet = -1;
353         }
354
355         uint32_t player_id;
356         pack.ReadPlayerID(player_id);
357         state.reset(new InteractiveState(*this, player_id));
358
359         pack.ReadPlayerState(state->GetPlayer().GetEntity().GetState());
360
361         env.state.PopAfter(this);
362         env.state.Push(state.get());
363 }
364
365 void MasterState::On(const Packet::Part &pack) {
366         if (state) {
367                 // kicked
368                 cout << "kicked by server" << endl;
369         } else {
370                 // join refused
371                 cout << "login refused by server" << endl;
372         }
373         Quit();
374 }
375
376 void MasterState::On(const Packet::SpawnEntity &pack) {
377         if (!state) {
378                 cout << "got entity spawn before world was created" << endl;
379                 Quit();
380                 return;
381         }
382         uint32_t entity_id;
383         pack.ReadEntityID(entity_id);
384         Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
385         UpdateEntity(entity_id, pack.Seq());
386         pack.ReadEntity(entity);
387         uint32_t skel_id;
388         pack.ReadSkeletonID(skel_id);
389         CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
390         if (skel) {
391                 skel->Instantiate(entity.GetModel());
392         }
393         cout << "spawned entity #" << entity_id << "  (" << entity.Name()
394                 << ") at " << entity.AbsolutePosition() << endl;
395 }
396
397 void MasterState::On(const Packet::DespawnEntity &pack) {
398         if (!state) {
399                 cout << "got entity despawn before world was created" << endl;
400                 Quit();
401                 return;
402         }
403         uint32_t entity_id;
404         pack.ReadEntityID(entity_id);
405         ClearEntity(entity_id);
406         for (Entity &entity : state->GetWorld().Entities()) {
407                 if (entity.ID() == entity_id) {
408                         entity.Kill();
409                         cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
410                         return;
411                 }
412         }
413 }
414
415 void MasterState::On(const Packet::EntityUpdate &pack) {
416         if (!state) {
417                 cout << "got entity update before world was created" << endl;
418                 Quit();
419                 return;
420         }
421
422         auto world_iter = state->GetWorld().Entities().begin();
423         auto world_end = state->GetWorld().Entities().end();
424
425         uint32_t count = 0;
426         pack.ReadEntityCount(count);
427
428         for (uint32_t i = 0; i < count; ++i) {
429                 uint32_t entity_id = 0;
430                 pack.ReadEntityID(entity_id, i);
431
432                 while (world_iter != world_end && world_iter->ID() < entity_id) {
433                         ++world_iter;
434                 }
435                 if (world_iter == world_end) {
436                         // nothing can be done from here
437                         return;
438                 }
439                 if (world_iter->ID() == entity_id) {
440                         if (UpdateEntity(entity_id, pack.Seq())) {
441                                 pack.ReadEntityState(world_iter->GetState(), i);
442                         }
443                 }
444         }
445 }
446
447 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
448         auto entry = update_status.find(entity_id);
449         if (entry == update_status.end()) {
450                 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
451                 return true;
452         }
453
454         int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
455         int time_diff = update_timer.Elapsed() - entry->second.last_update;
456         entry->second.last_update = update_timer.Elapsed();
457
458         if (pack_diff > 0 || time_diff > 1500) {
459                 entry->second.last_packet = seq;
460                 return true;
461         } else {
462                 return false;
463         }
464 }
465
466 void MasterState::ClearEntity(uint32_t entity_id) {
467         update_status.erase(entity_id);
468 }
469
470 void MasterState::On(const Packet::PlayerCorrection &pack) {
471         if (!state) {
472                 cout << "got player correction without a player :S" << endl;
473                 Quit();
474                 return;
475         }
476         uint16_t pack_seq;
477         EntityState corrected_state;
478         pack.ReadPacketSeq(pack_seq);
479         pack.ReadPlayerState(corrected_state);
480         state->MergePlayerCorrection(pack_seq, corrected_state);
481 }
482
483 void MasterState::On(const Packet::ChunkBegin &pack) {
484         if (!state) {
485                 cout << "got chunk data, but the world has not been created yet" << endl;
486                 cout << "great, this will totally screw up everything :(" << endl;
487                 return;
488         }
489         state->GetChunkReceiver().Handle(pack);
490 }
491
492 void MasterState::On(const Packet::ChunkData &pack) {
493         if (!state) {
494                 cout << "got chunk data, but the world has not been created yet" << endl;
495                 cout << "great, this will totally screw up everything :(" << endl;
496                 return;
497         }
498         state->GetChunkReceiver().Handle(pack);
499 }
500
501 void MasterState::On(const Packet::BlockUpdate &pack) {
502         if (!state) {
503                 cout << "received block update, but the world has not been created yet" << endl;
504                 return;
505         }
506         state->Handle(pack);
507 }
508
509 }
510 }