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