GekkoNet 1.0
C/C++ Peer to Peer Game Networking SDK
Loading...
Searching...
No Matches
net.cpp
Go to the documentation of this file.
1#include "gekko_types.h"
2#include "net.h"
3
4#include <cassert>
5#include <cstring>
6#include <iostream>
7
12
14{
15 _size = size;
16 _data = std::make_unique<u8[]>(_size);
17 // copy address data
18 std::memcpy(_data.get(), data, _size);
19}
20
22{
23 _size = 0;
24 _data = nullptr;
25}
26
28{
29 if (!other) {
30 return;
31 }
32
33 _size = other->_size;
34
35 if (_data) {
36 _data.reset();
37 }
38
39 _data = std::make_unique<u8[]>(_size);
40 // copy address data
41 std::memcpy(_data.get(), other->GetAddress(), _size);
42}
43
45{
46 return _size == other._size && std::memcmp(_data.get(), other._data.get(), _size) == 0;
47}
48
50{
51 return _data.get();
52}
53
55{
56 if (rtt.size() < 2) {
57 return 0.f;
58 }
59
60 float sum = 0.f;
61 for (i32 i = 1; i < rtt.size(); ++i) {
62 sum += std::abs((float)rtt[i] - (float)rtt[i - 1]);
63 }
64
65 float jitter = sum / (rtt.size() - 1);
66 return jitter;
67}
68
70{
71 if (rtt.empty()) {
72 return 0.f;
73 }
74
75 float sum = 0.f;
76 for (i32 i = 0; i < rtt.size(); i++) {
77 sum += rtt[i];
78 }
79
80 float avg_rtt = sum / rtt.size();
81 return avg_rtt;
82}
83
85{
86 rtt.push_back(rtt_ms);
87 while (rtt.size() > RTT_HISTORY_SIZE) {
88 rtt.erase(rtt.begin());
89 }
90}
91
93{
94 using namespace std::chrono;
95 u64 now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
96
97 if (last_bandwidth_update == 0) {
99 return;
100 }
101
102 u64 elapsed = now - last_bandwidth_update;
103 if (elapsed >= 1000) {
104 kb_sent_per_sec = (bytes_sent_accum * 1000.f / elapsed) / 1024.f;
105 kb_received_per_sec = (bytes_received_accum * 1000.f / elapsed) / 1024.f;
109 }
110}
111
113{
114 if (rtt.empty()) {
115 return 0;
116 }
117
118 return rtt.back();
119}
uint64_t u64
Definition gekko_types.h:8
int32_t i32
Definition gekko_types.h:12
uint8_t u8
Definition gekko_types.h:5
uint16_t u16
Definition gekko_types.h:6
uint32_t u32
Definition gekko_types.h:7
bool Equals(NetAddress &other)
Definition net.cpp:44
std::unique_ptr< u8[]> _data
Definition net.h:23
u8 * GetAddress()
Definition net.cpp:49
u32 GetSize()
Definition net.cpp:8
void Copy(NetAddress *other)
Definition net.cpp:27
float CalculateJitter()
Definition net.cpp:54
std::vector< u16 > rtt
Definition net.h:141
void AddRTT(u16 rtt_ms)
Definition net.cpp:84
u32 bytes_sent_accum
Definition net.h:137
static const u32 RTT_HISTORY_SIZE
Definition net.h:128
u32 bytes_received_accum
Definition net.h:138
float kb_received_per_sec
Definition net.h:136
u32 LastRTT()
Definition net.cpp:112
u64 last_bandwidth_update
Definition net.h:139
float kb_sent_per_sec
Definition net.h:135
void UpdateBandwidth()
Definition net.cpp:92
float CalculateAvgRTT()
Definition net.cpp:69