]> git.localhorst.tv Git - blank.git/blob - src/client/client.cpp
more parameters for world generation
[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         if (save.Exists(player)) {
135                 save.Read(player);
136         }
137 }
138
139 void InteractiveState::OnEnter() {
140         master.GetEnv().window.GrabMouse();
141 }
142
143 void InteractiveState::Handle(const SDL_Event &event) {
144         switch (event.type) {
145                 case SDL_KEYDOWN:
146                         interface.HandlePress(event.key);
147                         break;
148                 case SDL_KEYUP:
149                         interface.HandleRelease(event.key);
150                         break;
151                 case SDL_MOUSEBUTTONDOWN:
152                         interface.HandlePress(event.button);
153                         break;
154                 case SDL_MOUSEBUTTONUP:
155                         interface.HandleRelease(event.button);
156                         break;
157                 case SDL_MOUSEMOTION:
158                         interface.Handle(event.motion);
159                         break;
160                 case SDL_MOUSEWHEEL:
161                         interface.Handle(event.wheel);
162                         break;
163                 case SDL_QUIT:
164                         Exit();
165                         break;
166                 default:
167                         break;
168         }
169 }
170
171 void InteractiveState::Update(int dt) {
172         input.Update(dt);
173         if (input.BlockFocus()) {
174                 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
175         } else if (input.EntityFocus()) {
176                 hud.FocusEntity(*input.EntityFocus().entity);
177         } else {
178                 hud.FocusNone();
179         }
180         hud.Display(block_types[player.GetInventorySlot() + 1]);
181         loop_timer.Update(dt);
182         master.Update(dt);
183         chunk_receiver.Update(dt);
184         chunk_requester.Update(dt);
185
186         hud.Update(dt);
187         int world_dt = 0;
188         while (loop_timer.HitOnce()) {
189                 world.Update(loop_timer.Interval());
190                 world_dt += loop_timer.Interval();
191                 loop_timer.PopIteration();
192         }
193         chunk_renderer.Update(dt);
194
195         if (world_dt > 0) {
196                 input.PushPlayerUpdate(world_dt);
197         }
198
199         glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
200         glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
201         glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
202         master.GetEnv().audio.Position(player.GetEntity().Position());
203         master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
204         master.GetEnv().audio.Orientation(dir, up);
205 }
206
207 void InteractiveState::Render(Viewport &viewport) {
208         viewport.WorldPosition(player.GetEntity().Transform(player.GetEntity().ChunkCoords()));
209         if (master.GetConfig().video.world) {
210                 chunk_renderer.Render(viewport);
211                 world.Render(viewport);
212                 sky.Render(viewport);
213         }
214         hud.Render(viewport);
215 }
216
217 void InteractiveState::MergePlayerCorrection(std::uint16_t pack, const EntityState &state) {
218         input.MergePlayerCorrection(pack, state);
219 }
220
221 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
222         glm::ivec3 pos;
223         pack.ReadChunkCoords(pos);
224         Chunk *chunk = player.GetChunks().Get(pos);
225         if (!chunk) {
226                 // this change doesn't concern us
227                 return;
228         }
229         uint32_t count = 0;
230         pack.ReadBlockCount(count);
231         for (uint32_t i = 0; i < count; ++i) {
232                 uint16_t index;
233                 Block block;
234                 pack.ReadIndex(index, i);
235                 pack.ReadBlock(block, i);
236                 if (index < Chunk::size && block.type < block_types.Size()) {
237                         manip.SetBlock(*chunk, index, block);
238                 }
239         }
240 }
241
242 void InteractiveState::SetAudio(bool b) {
243         master.GetConfig().audio.enabled = b;
244         if (b) {
245                 hud.PostMessage("Audio enabled");
246         } else {
247                 hud.PostMessage("Audio disabled");
248         }
249 }
250
251 void InteractiveState::SetVideo(bool b) {
252         master.GetConfig().video.world = b;
253         if (b) {
254                 hud.PostMessage("World rendering enabled");
255         } else {
256                 hud.PostMessage("World rendering disabled");
257         }
258 }
259
260 void InteractiveState::SetHUD(bool b) {
261         master.GetConfig().video.hud = b;
262         if (b) {
263                 hud.PostMessage("HUD rendering enabled");
264         } else {
265                 hud.PostMessage("HUD rendering disabled");
266         }
267 }
268
269 void InteractiveState::SetDebug(bool b) {
270         master.GetConfig().video.debug = b;
271         if (b) {
272                 hud.PostMessage("Debug rendering enabled");
273         } else {
274                 hud.PostMessage("Debug rendering disabled");
275         }
276 }
277
278 void InteractiveState::Exit() {
279         save.Write(player);
280         master.Quit();
281 }
282
283
284 MasterState::MasterState(
285         Environment &env,
286         Config &config,
287         const World::Config &wc)
288 : env(env)
289 , config(config)
290 , world_conf(wc)
291 , state()
292 , client(config.net)
293 , init_state(*this)
294 , login_packet(-1)
295 , update_status()
296 , update_timer(16) {
297         client.GetConnection().SetHandler(this);
298         update_timer.Start();
299 }
300
301 void MasterState::Quit() {
302         if (!client.GetConnection().Closed()) {
303                 client.SendPart();
304         }
305         env.state.PopUntil(this);
306 }
307
308
309 void MasterState::OnEnter() {
310         login_packet = client.SendLogin(config.player.name);
311         env.state.Push(&init_state);
312 }
313
314
315 void MasterState::Handle(const SDL_Event &event) {
316
317 }
318
319
320 void MasterState::Update(int dt) {
321         update_timer.Update(dt);
322         client.Handle();
323         client.Update(dt);
324 }
325
326
327 void MasterState::Render(Viewport &) {
328
329 }
330
331
332 void MasterState::OnPacketLost(uint16_t id) {
333         if (id == login_packet) {
334                 login_packet = client.SendLogin(config.player.name);
335         }
336 }
337
338 void MasterState::OnTimeout() {
339         if (client.GetConnection().Closed()) {
340                 Quit();
341                 env.ShowMessage("connection timed out");
342         }
343 }
344
345 void MasterState::On(const Packet::Join &pack) {
346         pack.ReadWorldName(world_conf.name);
347
348         if (state) {
349                 // changing worlds
350                 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
351         } else {
352                 // joining game
353                 cout << "joined game \"" << world_conf.name << '"' << endl;
354                 // server received our login
355                 login_packet = -1;
356         }
357
358         uint32_t player_id;
359         pack.ReadPlayerID(player_id);
360         state.reset(new InteractiveState(*this, player_id));
361
362         pack.ReadPlayerState(state->GetPlayer().GetEntity().GetState());
363
364         env.state.PopAfter(this);
365         env.state.Push(state.get());
366 }
367
368 void MasterState::On(const Packet::Part &pack) {
369         Quit();
370         if (state) {
371                 // kicked
372                 env.ShowMessage("kicked by server");
373         } else {
374                 // join refused
375                 env.ShowMessage("login refused by server");
376         }
377 }
378
379 void MasterState::On(const Packet::SpawnEntity &pack) {
380         if (!state) {
381                 cout << "got entity spawn before world was created" << endl;
382                 return;
383         }
384         uint32_t entity_id;
385         pack.ReadEntityID(entity_id);
386         Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
387         UpdateEntity(entity_id, pack.Seq());
388         pack.ReadEntity(entity);
389         uint32_t skel_id;
390         pack.ReadSkeletonID(skel_id);
391         CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
392         if (skel) {
393                 skel->Instantiate(entity.GetModel());
394         }
395         cout << "spawned entity #" << entity_id << "  (" << entity.Name()
396                 << ") at " << entity.AbsolutePosition() << endl;
397 }
398
399 void MasterState::On(const Packet::DespawnEntity &pack) {
400         if (!state) {
401                 cout << "got entity despawn before world was created" << endl;
402                 return;
403         }
404         uint32_t entity_id;
405         pack.ReadEntityID(entity_id);
406         ClearEntity(entity_id);
407         for (Entity &entity : state->GetWorld().Entities()) {
408                 if (entity.ID() == entity_id) {
409                         entity.Kill();
410                         cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
411                         return;
412                 }
413         }
414 }
415
416 void MasterState::On(const Packet::EntityUpdate &pack) {
417         if (!state) {
418                 cout << "got entity update before world was created" << endl;
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                 return;
474         }
475         uint16_t pack_seq;
476         EntityState corrected_state;
477         pack.ReadPacketSeq(pack_seq);
478         pack.ReadPlayerState(corrected_state);
479         state->MergePlayerCorrection(pack_seq, corrected_state);
480 }
481
482 void MasterState::On(const Packet::ChunkBegin &pack) {
483         if (!state) {
484                 cout << "got chunk data, but the world has not been created yet" << endl;
485                 cout << "great, this will totally screw up everything :(" << endl;
486                 return;
487         }
488         state->GetChunkReceiver().Handle(pack);
489 }
490
491 void MasterState::On(const Packet::ChunkData &pack) {
492         if (!state) {
493                 cout << "got chunk data, but the world has not been created yet" << endl;
494                 cout << "great, this will totally screw up everything :(" << endl;
495                 return;
496         }
497         state->GetChunkReceiver().Handle(pack);
498 }
499
500 void MasterState::On(const Packet::BlockUpdate &pack) {
501         if (!state) {
502                 cout << "received block update, but the world has not been created yet" << endl;
503                 return;
504         }
505         state->Handle(pack);
506 }
507
508 }
509 }