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