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