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