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