]> git.localhorst.tv Git - blank.git/blob - src/client/net.cpp
fix comment handling in TokenStreamReader
[blank.git] / src / client / net.cpp
1 #include "ChunkReceiver.hpp"
2 #include "ChunkTransmission.hpp"
3 #include "Client.hpp"
4 #include "NetworkedInput.hpp"
5
6 #include "../app/init.hpp"
7 #include "../geometry/distance.hpp"
8 #include "../io/WorldSave.hpp"
9 #include "../net/Packet.hpp"
10 #include "../world/Chunk.hpp"
11 #include "../world/ChunkStore.hpp"
12 #include "../world/Player.hpp"
13 #include "../world/World.hpp"
14
15 #include <iostream>
16 #include <zlib.h>
17 #include <glm/gtx/io.hpp>
18
19 using namespace std;
20
21
22 namespace blank {
23 namespace client {
24
25
26 ChunkReceiver::ChunkReceiver(Client &client, ChunkStore &store, const WorldSave &save)
27 : client(client)
28 , store(store)
29 , save(save)
30 , transmissions()
31 , timer(5000) {
32         timer.Start();
33 }
34
35 ChunkReceiver::~ChunkReceiver() {
36
37 }
38
39 void ChunkReceiver::Update(int dt) {
40         timer.Update(dt);
41         for (ChunkTransmission &trans : transmissions) {
42                 if (trans.active && (timer.Elapsed() - trans.last_update) > timer.Interval()) {
43                         cout << "timeout for transmission of chunk " << trans.coords << endl;
44                         if (trans.header_received) {
45                                 client.SendChunkRequest(trans.coords);
46                                 trans.Reset();
47                                 trans.last_update = timer.Elapsed();
48                         } else {
49                                 // well shit
50                                 trans.Clear();
51                         }
52                 }
53         }
54         if (transmissions.size() > 3) {
55                 for (auto iter = transmissions.begin(), end = transmissions.end(); iter != end; ++iter) {
56                         if (!iter->active) {
57                                 transmissions.erase(iter);
58                                 break;
59                         }
60                 }
61         }
62         LoadN(10);
63         StoreN(10);
64 }
65
66 int ChunkReceiver::ToLoad() const noexcept {
67         return store.EstimateMissing();
68 }
69
70 void ChunkReceiver::LoadOne() {
71         if (!store.HasMissing()) return;
72
73         ExactLocation::Coarse pos = store.NextMissing();
74         Chunk *chunk = store.Allocate(pos);
75         if (!chunk) {
76                 // chunk store corrupted?
77                 return;
78         }
79
80         if (save.Exists(pos)) {
81                 save.Read(*chunk);
82         }
83 }
84
85 void ChunkReceiver::LoadN(size_t n) {
86         size_t end = min(n, size_t(ToLoad()));
87         for (size_t i = 0; i < end && store.HasMissing(); ++i) {
88                 LoadOne();
89         }
90 }
91
92 void ChunkReceiver::StoreN(size_t n) {
93         size_t saved = 0;
94         for (Chunk &chunk : store) {
95                 if (chunk.ShouldUpdateSave()) {
96                         save.Write(chunk);
97                         ++saved;
98                         if (saved >= n) {
99                                 break;
100                         }
101                 }
102         }
103 }
104
105
106 void ChunkReceiver::Handle(const Packet::ChunkBegin &pack) {
107         uint32_t id;
108         pack.ReadTransmissionId(id);
109         ChunkTransmission &trans = GetTransmission(id);
110         pack.ReadFlags(trans.flags);
111         pack.ReadChunkCoords(trans.coords);
112         pack.ReadDataSize(trans.data_size);
113         trans.last_update = timer.Elapsed();
114         trans.header_received = true;
115         Commit(trans);
116 }
117
118 void ChunkReceiver::Handle(const Packet::ChunkData &pack) {
119         uint32_t id, pos, size;
120         pack.ReadTransmissionId(id);
121         pack.ReadDataOffset(pos);
122         if (pos >= sizeof(ChunkTransmission::buffer)) {
123                 cout << "received chunk data offset outside of buffer size" << endl;
124                 return;
125         }
126         pack.ReadDataSize(size);
127         ChunkTransmission &trans = GetTransmission(id);
128         size_t len = min(size_t(size), sizeof(ChunkTransmission::buffer) - pos);
129         pack.ReadData(&trans.buffer[pos], len);
130         // TODO: this method breaks when a packet arrives twice
131         trans.data_received += len;
132         trans.last_update = timer.Elapsed();
133         Commit(trans);
134 }
135
136 ChunkTransmission &ChunkReceiver::GetTransmission(uint32_t id) {
137         // search for ongoing
138         for (ChunkTransmission &trans : transmissions) {
139                 if (trans.active && trans.id == id) {
140                         return trans;
141                 }
142         }
143         // search for unused
144         for (ChunkTransmission &trans : transmissions) {
145                 if (!trans.active) {
146                         trans.active = true;
147                         trans.id = id;
148                         return trans;
149                 }
150         }
151         // allocate new
152         transmissions.emplace_back();
153         transmissions.back().active = true;
154         transmissions.back().id = id;
155         return transmissions.back();
156 }
157
158 void ChunkReceiver::Commit(ChunkTransmission &trans) {
159         if (!trans.Complete()) return;
160
161         Chunk *chunk = store.Allocate(trans.coords);
162         if (!chunk) {
163                 // chunk no longer of interest, just drop the data
164                 // it should probably be cached to disk, but not now :P
165                 trans.Clear();
166                 return;
167         }
168
169         const Byte *src = &trans.buffer[0];
170         uLong src_len = min(size_t(trans.data_size), sizeof(ChunkTransmission::buffer));
171         Byte *dst = reinterpret_cast<Byte *>(chunk->BlockData());
172         uLong dst_len = Chunk::BlockSize();
173
174         if (trans.Compressed()) {
175                 if (uncompress(dst, &dst_len, src, src_len) != Z_OK) {
176                         // omg, now what?
177                         cout << "got corruped chunk data for " << trans.coords << endl;
178                         client.SendChunkRequest(trans.coords);
179                         trans.Reset();
180                         // chunk data can, and probably will, contain invalid block IDs, so
181                         // zero it to be safe
182                         memset(dst, 0, dst_len);
183                         return;
184                 }
185         } else {
186                 memcpy(dst, src, min(src_len, dst_len));
187         }
188         chunk->Invalidate();
189         trans.Clear();
190 }
191
192 ChunkTransmission::ChunkTransmission()
193 : id(0)
194 , flags(0)
195 , coords()
196 , data_size(0)
197 , data_received(0)
198 , last_update(0)
199 , header_received(false)
200 , active(false)
201 , buffer() {
202
203 }
204
205 void ChunkTransmission::Reset() noexcept {
206         data_size = 0;
207         data_received = 0;
208         last_update = 0;
209         header_received = false;
210 }
211
212 void ChunkTransmission::Clear() noexcept {
213         Reset();
214         active = false;
215 }
216
217 bool ChunkTransmission::Complete() const noexcept {
218         return header_received && data_received == data_size;
219 }
220
221 bool ChunkTransmission::Compressed() const noexcept {
222         return flags & 1;
223 }
224
225
226 namespace {
227
228 UDPsocket client_bind(Uint16 port) {
229         UDPsocket sock = SDLNet_UDP_Open(port);
230         if (!sock) {
231                 throw NetError("SDLNet_UDP_Open");
232         }
233         return sock;
234 }
235
236 IPaddress client_resolve(const char *host, Uint16 port) {
237         IPaddress addr;
238         if (SDLNet_ResolveHost(&addr, host, port) != 0) {
239                 throw NetError("SDLNet_ResolveHost");
240         }
241         return addr;
242 }
243
244 }
245
246 Client::Client(const Config::Network &conf)
247 : conn(client_resolve(conf.host.c_str(), conf.port))
248 , client_sock(client_bind(0))
249 , client_pack{ -1, nullptr, 0 } {
250         client_pack.data = new Uint8[sizeof(Packet)];
251         client_pack.maxlen = sizeof(Packet);
252         // establish connection
253         SendPing();
254 }
255
256 Client::~Client() {
257         delete[] client_pack.data;
258         SDLNet_UDP_Close(client_sock);
259 }
260
261
262 void Client::Handle() {
263         int result = SDLNet_UDP_Recv(client_sock, &client_pack);
264         while (result > 0) {
265                 HandlePacket(client_pack);
266                 result = SDLNet_UDP_Recv(client_sock, &client_pack);
267         }
268         if (result == -1) {
269                 // a boo boo happened
270                 throw NetError("SDLNet_UDP_Recv");
271         }
272 }
273
274 void Client::HandlePacket(const UDPpacket &udp_pack) {
275         if (!conn.Matches(udp_pack.address)) {
276                 // packet came from somewhere else, drop
277                 return;
278         }
279         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
280         if (pack.header.tag != Packet::TAG) {
281                 // mistagged packet, drop
282                 return;
283         }
284
285         conn.Received(udp_pack);
286 }
287
288 void Client::Update(int dt) {
289         conn.Update(dt);
290         if (conn.ShouldPing()) {
291                 SendPing();
292         }
293 }
294
295 uint16_t Client::SendPing() {
296         return conn.SendPing(client_pack, client_sock);
297 }
298
299 uint16_t Client::SendLogin(const string &name) {
300         auto pack = Packet::Make<Packet::Login>(client_pack);
301         pack.WritePlayerName(name);
302         return conn.Send(client_pack, client_sock);
303 }
304
305 uint16_t Client::SendPlayerUpdate(
306         const EntityState &prediction,
307         const glm::vec3 &movement,
308         float pitch,
309         float yaw,
310         uint8_t actions,
311         uint8_t slot
312 ) {
313         auto pack = Packet::Make<Packet::PlayerUpdate>(client_pack);
314         pack.WritePredictedState(prediction);
315         pack.WriteMovement(movement);
316         pack.WriteActions(actions);
317         pack.WriteSlot(slot);
318         return conn.Send(client_pack, client_sock);
319 }
320
321 uint16_t Client::SendPart() {
322         Packet::Make<Packet::Part>(client_pack);
323         return conn.Send(client_pack, client_sock);
324 }
325
326 uint16_t Client::SendChunkRequest(
327         const glm::ivec3 &coords
328 ) {
329         auto pack = Packet::Make<Packet::ChunkBegin>(client_pack);
330         pack.WriteChunkCoords(coords);
331         return conn.Send(client_pack, client_sock);
332 }
333
334 uint16_t Client::SendMessage(
335         uint8_t type,
336         uint32_t ref,
337         const string &msg
338 ) {
339         auto pack = Packet::Make<Packet::Message>(client_pack);
340         pack.WriteType(type);
341         pack.WriteReferral(ref);
342         pack.WriteMessage(msg);
343         client_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
344         return conn.Send(client_pack, client_sock);
345 }
346
347 NetworkedInput::NetworkedInput(World &world, Player &player, Client &client)
348 : PlayerController(world, player)
349 , client(client)
350 , player_hist()
351 , old_movement(0.0f)
352 , old_actions(0)
353 , actions(0) {
354
355 }
356
357 bool NetworkedInput::UpdateImportant() const noexcept {
358         return old_actions != actions || !iszero(old_movement - GetMovement());
359 }
360
361 void NetworkedInput::Update(Entity &, float dt) {
362         Invalidate();
363         UpdatePlayer();
364 }
365
366 void NetworkedInput::PushPlayerUpdate(int dt) {
367         const EntityState &state = GetPlayer().GetEntity().GetState();
368
369         uint16_t packet = client.SendPlayerUpdate(
370                 state,
371                 GetMovement(),
372                 GetPitch(),
373                 GetYaw(),
374                 actions,
375                 InventorySlot()
376         );
377         if (player_hist.size() < 16) {
378                 player_hist.emplace_back(state, GetMovement(), dt * 0.001f, packet);
379         } else {
380                 auto entry = player_hist.begin();
381                 entry->state = state;
382                 entry->movement = GetMovement();
383                 entry->delta_t = dt * 0.001f;
384                 entry->packet = packet;
385                 player_hist.splice(player_hist.end(), player_hist, entry);
386         }
387         old_movement = GetMovement();
388         old_actions = actions;
389 }
390
391 void NetworkedInput::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
392         if (player_hist.empty()) return;
393
394         auto entry = player_hist.begin();
395         auto end = player_hist.end();
396
397         // we may have received an older packet
398         int pack_diff = int16_t(seq) - int16_t(entry->packet);
399         if (pack_diff < 0) {
400                 // indeed we have, just ignore it
401                 return;
402         }
403
404         // drop anything older than the fix
405         while (entry != end) {
406                 pack_diff = int16_t(seq) - int16_t(entry->packet);
407                 if (pack_diff > 0) {
408                         entry = player_hist.erase(entry);
409                 } else {
410                         break;
411                 }
412         }
413
414         glm::vec3 restore_movement(GetMovement());
415
416         EntityState player_state = GetPlayer().GetEntity().GetState();
417         Entity replay(GetPlayer().GetEntity());
418         replay.SetState(corrected_state);
419
420         if (entry != end) {
421                 entry->state.pos = replay.GetState().pos;
422                 ++entry;
423         }
424
425         vector<WorldCollision> col;
426         while (entry != end) {
427                 SetMovement(entry->movement);
428                 GetWorld().Update(replay, entry->delta_t);
429                 entry->state.pos = replay.GetState().pos;
430                 ++entry;
431         }
432
433         glm::vec3 displacement(replay.GetState().Diff(player_state));
434         const float disp_squared = dot(displacement, displacement);
435
436         if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
437                 SetMovement(restore_movement);
438                 return;
439         }
440
441         // if offset > 10cm, warp the player
442         // otherwise, move at most 1cm per frame towards
443         // the fixed position (160ms, so shouldn't be too noticeable)
444         constexpr float warp_thresh = 0.01f; // (1/10)^2
445         constexpr float max_disp = 0.0001f; // (1/100)^2
446
447         if (disp_squared > warp_thresh) {
448                 player_state.pos = replay.GetState().pos;
449         } else if (disp_squared < max_disp) {
450                 player_state.pos.block += displacement;
451         } else {
452                 displacement *= 0.01f / sqrt(disp_squared);
453                 player_state.pos.block += displacement;
454         }
455         GetPlayer().GetEntity().SetState(player_state);
456         SetMovement(restore_movement);
457 }
458
459 void NetworkedInput::StartPrimaryAction() {
460         actions |= 0x01;
461 }
462
463 void NetworkedInput::StopPrimaryAction() {
464         actions &= ~0x01;
465 }
466
467 void NetworkedInput::StartSecondaryAction() {
468         actions |= 0x02;
469 }
470
471 void NetworkedInput::StopSecondaryAction() {
472         actions &= ~0x02;
473 }
474
475 void NetworkedInput::StartTertiaryAction() {
476         actions |= 0x04;
477 }
478
479 void NetworkedInput::StopTertiaryAction() {
480         actions &= ~0x04;
481 }
482
483 }
484 }