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