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