aboutsummaryrefslogtreecommitdiff
path: root/advtrains/helpers.lua
blob: 511d32ee18702d00ec4ba3562442f284dcec7ce5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
--advtrains by orwell96, see readme.txt

local dir_trans_tbl={
	[0]={x=0, z=1, y=0},
	[1]={x=1, z=2, y=0},
	[2]={x=1, z=1, y=0},
	[3]={x=2, z=1, y=0},
	[4]={x=1, z=0, y=0},
	[5]={x=2, z=-1, y=0},
	[6]={x=1, z=-1, y=0},
	[7]={x=1, z=-2, y=0},
	[8]={x=0, z=-1, y=0},
	[9]={x=-1, z=-2, y=0},
	[10]={x=-1, z=-1, y=0},
	[11]={x=-2, z=-1, y=0},
	[12]={x=-1, z=0, y=0},
	[13]={x=-2, z=1, y=0},
	[14]={x=-1, z=1, y=0},
	[15]={x=-1, z=2, y=0},
}

local dir_angle_tbl={}
for d,v in pairs(dir_trans_tbl) do
	local uvec = vector.normalize(v)
	dir_angle_tbl[d] = math.atan2(-uvec.x, uvec.z)
end


function advtrains.dir_to_angle(dir)
	return dir_angle_tbl[dir] or error("advtrains: in helpers.lua/dir_to_angle() given dir="..(dir or "nil"))
end

function advtrains.dirCoordSet(coord, dir)
	return vector.add(coord, advtrains.dirToCoord(dir))
end
advtrains.pos_add_dir = advtrains.dirCoordSet

function advtrains.pos_add_angle(pos, ang)
	-- 0 is +Z -> meaning of sin/cos swapped
	return vector.add(pos, {x = -math.sin(ang), y = 0, z = math.cos(ang)})
end

function advtrains.dirToCoord(dir)
	return dir_trans_tbl[dir] or error("advtrains: in helpers.lua/dir_to_vector() given dir="..(dir or "nil"))
end
advtrains.dir_to_vector = advtrains.dirToCoord

function advtrains.maxN(list, expectstart)
	local n=expectstart or 0
	while list[n] do
		n=n+1
	end
	return n-1
end

function advtrains.minN(list, expectstart)
	local n=expectstart or 0
	while list[n] do
		n=n-1
	end
	return n+1
end

function atround(number)
	return math.floor(number+0.5)
end
atfloor = math.floor


function advtrains.round_vector_floor_y(vec)
	return {x=math.floor(vec.x+0.5), y=math.floor(vec.y), z=math.floor(vec.z+0.5)}
end

function advtrains.yawToDirection(yaw, conn1, conn2)
	if not conn1 or not conn2 then
		error("given nil to yawToDirection: conn1="..(conn1 or "nil").." conn2="..(conn1 or "nil"))
	end
	local yaw1 = advtrains.dir_to_angle(conn1)
	local yaw2 = advtrains.dir_to_angle(conn2)
	local adiff1 = advtrains.minAngleDiffRad(yaw, yaw1)
	local adiff2 = advtrains.minAngleDiffRad(yaw, yaw2)
	
	if math.abs(adiff2)<math.abs(adiff1) then
		return conn2
	else
		return conn1
	end
end

function advtrains.yawToAnyDir(yaw)
	local min_conn, min_diff=0, 10
	for conn, vec in pairs(advtrains.dir_trans_tbl) do
		local yaw1 = advtrains.dir_to_angle(conn)
		local diff = math.abs(advtrains.minAngleDiffRad(yaw, yaw1))
		if diff < min_diff then
			min_conn = conn
			min_diff = diff
		end
	end
	return min_conn
end
function advtrains.yawToClosestConn(yaw, conns)
	local min_connid, min_diff=1, 10
	for connid, conn in ipairs(conns) do
		local yaw1 = advtrains.dir_to_angle(conn.c)
		local diff = math.abs(advtrains.minAngleDiffRad(yaw, yaw1))
		if diff < min_diff then
			min_connid = connid
			min_diff = diff
		end
	end
	return min_connid
end

local pi, pi2 = math.pi, 2*math.pi
function advtrains.minAngleDiffRad(r1, r2)
	while r1>pi2 do
		r1=r1-pi2
	end
	while r1<0 do
		r1=r1+pi2
	end
	while r2>pi2 do
		r2=r2-pi2
	end
	while r1<0 do
		r2=r2+pi2
	end
	local try1=r2-r1
	local try2=r2+pi2-r1
	local try3=r2-pi2-r1
	
	local minabs = math.min(math.abs(try1), math.abs(try2), math.abs(try3))
	if minabs==math.abs(try1) then
		return try1
	end
	if minabs==math.abs(try2) then
		return try2
	end
	if minabs==math.abs(try3) then
		return try3
	end
end


-- Takes 2 connections (0...AT_CMAX) as argument
-- Returns the angle median of those 2 positions from the pov
-- of standing on the cdir1 side and looking towards cdir2
-- cdir1 - >NODE> - cdir2
function advtrains.conn_angle_median(cdir1, cdir2)
	local ang1 = advtrains.dir_to_angle(advtrains.oppd(cdir1))
	local ang2 = advtrains.dir_to_angle(cdir2)
	return ang1 + advtrains.minAngleDiffRad(ang1, ang2)/2
end

function advtrains.merge_tables(a, ...)
	local new={}
	for _,t in ipairs({a,...}) do
		for k,v in pairs(t) do new[k]=v end
	end
	return new
end
function advtrains.save_keys(tbl, keys)
	local new={}
	for _,key in ipairs(keys) do
		new[key] = tbl[key]
	end
	return new
end

function advtrains.get_real_index_position(path, index)
	if not path or not index then return end
	
	local first_pos=path[math.floor(index)]
	local second_pos=path[math.floor(index)+1]
	
	if not first_pos or not second_pos then return nil end
	
	local factor=index-math.floor(index)
	local actual_pos={x=first_pos.x-(first_pos.x-second_pos.x)*factor, y=first_pos.y-(first_pos.y-second_pos.y)*factor, z=first_pos.z-(first_pos.z-second_pos.z)*factor,}
	return actual_pos
end
function advtrains.pos_median(pos1, pos2)
	return {x=pos1.x-(pos1.x-pos2.x)*0.5, y=pos1.y-(pos1.y-pos2.y)*0.5, z=pos1.z-(pos1.z-pos2.z)*0.5}
end
function advtrains.abs_ceil(i)
	return math.ceil(math.abs(i))*math.sign(i)
end

function advtrains.serialize_inventory(inv)
	local ser={}
	local liszts=inv:get_lists()
	for lisztname, liszt in pairs(liszts) do
		ser[lisztname]={}
		for idx, item in ipairs(liszt) do
			local istring=item:to_string()
			if istring~="" then
				ser[lisztname][idx]=istring
			end
		end
	end
	return minetest.serialize(ser)
end
function advtrains.deserialize_inventory(sers, inv)
	local ser=minetest.deserialize(sers)
	if ser then
		inv:set_lists(ser)
		return true
	end
	return false
end

--is_protected wrapper that checks for protection_bypass privilege
function advtrains.is_protected(pos, name)
	if not name then
		error("advtrains.is_protected() called without name parameter!")
	end
	if minetest.check_player_privs(name, {protection_bypass=true}) then
		--player can bypass protection
		return false
	end
	return minetest.is_protected(pos, name)
end

function advtrains.is_creative(name)
	if not name then
		error("advtrains.is_creative() called without name parameter!")
	end
	if minetest.check_player_privs(name, {creative=true}) then
		return true
	end
	return minetest.settings:get_bool("creative_mode")
end

function advtrains.ms_to_kmh(speed)
	return speed * 3.6
end

-- 4 possible inputs:
-- integer: just do that modulo calculation
-- table with c set: rotate c
-- table with tables: rotate each
-- table with integers: rotate each (probably no use case)
function advtrains.rotate_conn_by(conn, rotate)
	if tonumber(conn) then
		return (conn+rotate)%AT_CMAX
	elseif conn.c then
		return { c = (conn.c+rotate)%AT_CMAX, y = conn.y}
	end
	local tmp={}
	for connid, data in ipairs(conn) do
		tmp[connid]=advtrains.rotate_conn_by(data, rotate)
	end
	return tmp
end


function advtrains.oppd(dir)
	return advtrains.rotate_conn_by(dir, AT_CMAX/2)
end
--conn_to_match like rotate_conn_by
--other_conns have to be a table of conn tables!
function advtrains.conn_matches_to(conn, other_conns)
	if tonumber(conn) then
		for connid, data in ipairs(other_conns) do
			if advtrains.oppd(conn) == data.c then return connid end
		end
		return false
	elseif conn.c then
		for connid, data in ipairs(other_conns) do
			local cmp = advtrains.oppd(conn)
			if cmp.c == data.c and (cmp.y or 0) == (data.y or 0) then return connid end
		end
		return false
	end
	local tmp={}
	for connid, data in ipairs(conn) do
		local backmatch = advtrains.conn_matches_to(data, other_conns)
		if backmatch then return backmatch, connid end --returns <connid of other rail> <connid of this rail>
	end
	return false
end


-- returns: <adjacent pos>, <conn index of adjacent>, <my conn index>, <railheight of adjacent>
function advtrains.get_adjacent_rail(this_posnr, this_conns_p, conn_idx, drives_on)
	local this_pos = advtrains.round_vector_floor_y(this_posnr)
	local this_conns = this_conns_p
	if not this_conns then
		_, this_conns = advtrains.get_rail_info_at(this_pos)
	end
	if not conn_idx then
		for coni, _ in ipairs(this_conns) do
			local adj_pos, adj_conn_idx, _, nry, nco = advtrains.get_adjacent_rail(this_pos, this_conns, coni)
			if adj_pos then return adj_pos,adj_conn_idx,coni,nry, nco end
		end
		return nil
	end
	
	local conn = this_conns[conn_idx]
	local conn_y = conn.y or 0
	local adj_pos = advtrains.dirCoordSet(this_pos, conn.c);
	
	while conn_y>=1 do
		conn_y = conn_y - 1
		adj_pos.y = adj_pos.y + 1
	end
	
	local nextnode_ok, nextconns, nextrail_y=advtrains.get_rail_info_at(adj_pos, drives_on)
	if not nextnode_ok then
		adj_pos.y = adj_pos.y - 1
		conn_y = conn_y + 1
		nextnode_ok, nextconns, nextrail_y=advtrains.get_rail_info_at(adj_pos, drives_on)
		if not nextnode_ok then
			return nil
		end
	end
	local adj_connid = advtrains.conn_matches_to({c=conn.c, y=conn_y}, nextconns)
	if adj_connid then
		return adj_pos, adj_connid, conn_idx, nextrail_y, nextconns
	end
	return nil
end

local connlku={[2]={2,1}, [3]={2,1,1}, [4]={2,1,4,3}}
function advtrains.get_matching_conn(conn, nconns)
	return connlku[nconns][conn]
end

function advtrains.random_id()
	local idst=""
	for i=0,5 do
		idst=idst..(math.random(0,9))
	end
	return idst
end
-- Shorthand for pos_to_string and round_vector_floor_y
function advtrains.roundfloorpts(pos)
	return minetest.pos_to_string(advtrains.round_vector_floor_y(pos))
end

-- insert an element into a table if it does not yet exist there
-- equalfunc is a function to compare equality, defaults to ==
-- returns true if the element was inserted
function advtrains.insert_once(tab, elem, equalfunc)
	for _,e in pairs(tab) do
		if equalfunc and equalfunc(elem, e) or e==elem then return false end
	end
	tab[#tab+1] = elem
	return true
end

local hext = { [0]="0",[1]="1",[2]="2",[3]="3",[4]="4",[5]="5",[6]="6",[7]="7",[8]="8",[9]="9",[10]="A",[11]="B",[12]="C",[13]="D",[14]="E",[15]="F"}
local dect = { ["0"]=0,["1"]=1,["2"]=2,["3"]=3,["4"]=4,["5"]=5,["6"]=6,["7"]=7,["8"]=8,["9"]=9,["A"]=10,["B"]=11,["C"]=12,["D"]=13,["E"]=14,["F"]=15}

local f = atfloor

local function hex(i)
	local x=i+32768
	local c4 = x % 16
	x = f(x / 16)
	local c3 = x % 16
	x = f(x / 16)
	local c2 = x % 16
	x = f(x / 16)
	local c1 = x % 16
	return (hext[c1]) .. (hext[c2]) .. (hext[c3]) .. (hext[c4])
end

local function c(s,i) return dect[string.sub(s,i,i)] end

local function dec(s)
	return (c(s,1)*4096 + c(s,2)*256 + c(s,3)*16 + c(s,4))-32768
end
-- Takes a position vector and outputs a encoded value suitable as table index
-- This is essentially a hexadecimal representation of the position (+32768)
-- Order (YYY)YXXXXZZZZ
function advtrains.encode_pos(pos)
	return hex(pos.y) .. hex(pos.x) .. hex(pos.z)
end

-- decodes a position encoded with encode_pos
function advtrains.decode_pos(pts)
	local stry = string.sub(pts, 1,4)
	local strx = string.sub(pts, 5,8)
	local strz = string.sub(pts, 9,12)
	return vector.new(dec(strx), dec(stry), dec(strz))
end

--[[ Benchmarking code
local tdt = {}
local tlt = {}
local tet = {}

for i=1,1000000 do
	tdt[i] = vector.new(math.random(-65536, 65535), math.random(-65536, 65535), math.random(-65536, 65535))
	if i%1000 == 0 then
		tlt[#tlt+1] = tdt[i]
	end
end

local t1=os.clock()
for i=1,1000000 do
	local pe = advtrains.encode_pos(tdt[i])
	local pb = advtrains.decode_pos(pe)
	tet[pe] = i
end
for i,v in ipairs(tlt) do
	local lk = tet[advtrains.encode_pos(v)]
end
atdebug("endec",os.clock()-t1,"s")

tet = {}

t1=os.clock()
for i=1,1000000 do
	local pe = minetest.pos_to_string(tdt[i])
	local pb = minetest.string_to_pos(pe)
	tet[pe] = i
end
for i,v in ipairs(tlt) do
	local lk = tet[minetest.pos_to_string(v)]
end
atdebug("pts",os.clock()-t1,"s")

--Results:
--2018-11-29 16:57:08: ACTION[Main]: [advtrains]endec 1.786451 s 
--2018-11-29 16:57:10: ACTION[Main]: [advtrains]pts 2.566377 s 
]]


="hl opt">); void UpdateBytesLost(unsigned int bytes); void UpdateBytesReceived(unsigned int bytes); void UpdateTimers(float dtime, bool legacy_peer); const float getCurrentDownloadRateKB() { MutexAutoLock lock(m_internal_mutex); return cur_kbps; }; const float getMaxDownloadRateKB() { MutexAutoLock lock(m_internal_mutex); return max_kbps; }; const float getCurrentLossRateKB() { MutexAutoLock lock(m_internal_mutex); return cur_kbps_lost; }; const float getMaxLossRateKB() { MutexAutoLock lock(m_internal_mutex); return max_kbps_lost; }; const float getCurrentIncomingRateKB() { MutexAutoLock lock(m_internal_mutex); return cur_incoming_kbps; }; const float getMaxIncomingRateKB() { MutexAutoLock lock(m_internal_mutex); return max_incoming_kbps; }; const float getAvgDownloadRateKB() { MutexAutoLock lock(m_internal_mutex); return avg_kbps; }; const float getAvgLossRateKB() { MutexAutoLock lock(m_internal_mutex); return avg_kbps_lost; }; const float getAvgIncomingRateKB() { MutexAutoLock lock(m_internal_mutex); return avg_incoming_kbps; }; const unsigned int getWindowSize() const { return window_size; }; void setWindowSize(unsigned int size) { window_size = size; }; private: Mutex m_internal_mutex; int window_size; u16 next_incoming_seqnum; u16 next_outgoing_seqnum; u16 next_outgoing_split_seqnum; unsigned int current_packet_loss; unsigned int current_packet_too_late; unsigned int current_packet_successfull; float packet_loss_counter; unsigned int current_bytes_transfered; unsigned int current_bytes_received; unsigned int current_bytes_lost; float max_kbps; float cur_kbps; float avg_kbps; float max_incoming_kbps; float cur_incoming_kbps; float avg_incoming_kbps; float max_kbps_lost; float cur_kbps_lost; float avg_kbps_lost; float bpm_counter; unsigned int rate_samples; }; class Peer; enum PeerChangeType { PEER_ADDED, PEER_REMOVED }; struct PeerChange { PeerChangeType type; u16 peer_id; bool timeout; }; class PeerHandler { public: PeerHandler() { } virtual ~PeerHandler() { } /* This is called after the Peer has been inserted into the Connection's peer container. */ virtual void peerAdded(Peer *peer) = 0; /* This is called before the Peer has been removed from the Connection's peer container. */ virtual void deletingPeer(Peer *peer, bool timeout) = 0; }; class PeerHelper { public: PeerHelper(); PeerHelper(Peer* peer); ~PeerHelper(); PeerHelper& operator=(Peer* peer); Peer* operator->() const; bool operator!(); Peer* operator&() const; bool operator!=(void* ptr); private: Peer* m_peer; }; class Connection; typedef enum { MIN_RTT, MAX_RTT, AVG_RTT, MIN_JITTER, MAX_JITTER, AVG_JITTER } rtt_stat_type; typedef enum { CUR_DL_RATE, AVG_DL_RATE, CUR_INC_RATE, AVG_INC_RATE, CUR_LOSS_RATE, AVG_LOSS_RATE, } rate_stat_type; class Peer { public: friend class PeerHelper; Peer(Address address_,u16 id_,Connection* connection) : id(id_), m_increment_packets_remaining(9), m_increment_bytes_remaining(0), m_pending_deletion(false), m_connection(connection), address(address_), m_ping_timer(0.0), m_last_rtt(-1.0), m_usage(0), m_timeout_counter(0.0), m_last_timeout_check(porting::getTimeMs()) { m_rtt.avg_rtt = -1.0; m_rtt.jitter_avg = -1.0; m_rtt.jitter_max = 0.0; m_rtt.max_rtt = 0.0; m_rtt.jitter_min = FLT_MAX; m_rtt.min_rtt = FLT_MAX; }; virtual ~Peer() { MutexAutoLock usage_lock(m_exclusive_access_mutex); FATAL_ERROR_IF(m_usage != 0, "Reference counting failure"); }; // Unique id of the peer u16 id; void Drop(); virtual void PutReliableSendCommand(ConnectionCommand &c, unsigned int max_packet_size) {}; virtual bool getAddress(MTProtocols type, Address& toset) = 0; bool isPendingDeletion() { MutexAutoLock lock(m_exclusive_access_mutex); return m_pending_deletion; }; void ResetTimeout() {MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter=0.0; }; bool isTimedOut(float timeout); unsigned int m_increment_packets_remaining; unsigned int m_increment_bytes_remaining; virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; }; virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {}; virtual SharedBuffer<u8> addSpiltPacket(u8 channel, BufferedPacket toadd, bool reliable) { fprintf(stderr,"Peer: addSplitPacket called, this is supposed to be never called!\n"); return SharedBuffer<u8>(0); }; virtual bool Ping(float dtime, SharedBuffer<u8>& data) { return false; }; virtual float getStat(rtt_stat_type type) const { switch (type) { case MIN_RTT: return m_rtt.min_rtt; case MAX_RTT: return m_rtt.max_rtt; case AVG_RTT: return m_rtt.avg_rtt; case MIN_JITTER: return m_rtt.jitter_min; case MAX_JITTER: return m_rtt.jitter_max; case AVG_JITTER: return m_rtt.jitter_avg; } return -1; } protected: virtual void reportRTT(float rtt) {}; void RTTStatistics(float rtt, const std::string &profiler_id = "", unsigned int num_samples = 1000); bool IncUseCount(); void DecUseCount(); Mutex m_exclusive_access_mutex; bool m_pending_deletion; Connection* m_connection; // Address of the peer Address address; // Ping timer float m_ping_timer; private: struct rttstats { float jitter_min; float jitter_max; float jitter_avg; float min_rtt; float max_rtt; float avg_rtt; }; rttstats m_rtt; float m_last_rtt; // current usage count unsigned int m_usage; // Seconds from last receive float m_timeout_counter; u32 m_last_timeout_check; }; class UDPPeer : public Peer { public: friend class PeerHelper; friend class ConnectionReceiveThread; friend class ConnectionSendThread; friend class Connection; UDPPeer(u16 a_id, Address a_address, Connection* connection); virtual ~UDPPeer() {}; void PutReliableSendCommand(ConnectionCommand &c, unsigned int max_packet_size); bool getAddress(MTProtocols type, Address& toset); void setNonLegacyPeer(); bool getLegacyPeer() { return m_legacy_peer; } u16 getNextSplitSequenceNumber(u8 channel); void setNextSplitSequenceNumber(u8 channel, u16 seqnum); SharedBuffer<u8> addSpiltPacket(u8 channel, BufferedPacket toadd, bool reliable); protected: /* Calculates avg_rtt and resend_timeout. rtt=-1 only recalculates resend_timeout */ void reportRTT(float rtt); void RunCommandQueues( unsigned int max_packet_size, unsigned int maxcommands, unsigned int maxtransfer); float getResendTimeout() { MutexAutoLock lock(m_exclusive_access_mutex); return resend_timeout; } void setResendTimeout(float timeout) { MutexAutoLock lock(m_exclusive_access_mutex); resend_timeout = timeout; } bool Ping(float dtime,SharedBuffer<u8>& data); Channel channels[CHANNEL_COUNT]; bool m_pending_disconnect; private: // This is changed dynamically float resend_timeout; bool processReliableSendCommand( ConnectionCommand &c, unsigned int max_packet_size); bool m_legacy_peer; }; /* Connection */ enum ConnectionEventType{ CONNEVENT_NONE, CONNEVENT_DATA_RECEIVED, CONNEVENT_PEER_ADDED, CONNEVENT_PEER_REMOVED, CONNEVENT_BIND_FAILED, }; struct ConnectionEvent { enum ConnectionEventType type; u16 peer_id; Buffer<u8> data; bool timeout; Address address; ConnectionEvent(): type(CONNEVENT_NONE), peer_id(0), timeout(false) {} std::string describe() { switch(type) { case CONNEVENT_NONE: return "CONNEVENT_NONE"; case CONNEVENT_DATA_RECEIVED: return "CONNEVENT_DATA_RECEIVED"; case CONNEVENT_PEER_ADDED: return "CONNEVENT_PEER_ADDED"; case CONNEVENT_PEER_REMOVED: return "CONNEVENT_PEER_REMOVED"; case CONNEVENT_BIND_FAILED: return "CONNEVENT_BIND_FAILED"; } return "Invalid ConnectionEvent"; } void dataReceived(u16 peer_id_, const SharedBuffer<u8> &data_) { type = CONNEVENT_DATA_RECEIVED; peer_id = peer_id_; data = data_; } void peerAdded(u16 peer_id_, Address address_) { type = CONNEVENT_PEER_ADDED; peer_id = peer_id_; address = address_; } void peerRemoved(u16 peer_id_, bool timeout_, Address address_) { type = CONNEVENT_PEER_REMOVED; peer_id = peer_id_; timeout = timeout_; address = address_; } void bindFailed() { type = CONNEVENT_BIND_FAILED; } }; class ConnectionSendThread : public Thread { public: friend class UDPPeer; ConnectionSendThread(unsigned int max_packet_size, float timeout); void *run(); void Trigger(); void setParent(Connection* parent) { assert(parent != NULL); // Pre-condition m_connection = parent; } void setPeerTimeout(float peer_timeout) { m_timeout = peer_timeout; } private: void runTimeouts (float dtime); void rawSend (const BufferedPacket &packet); bool rawSendAsPacket(u16 peer_id, u8 channelnum, SharedBuffer<u8> data, bool reliable); void processReliableCommand (ConnectionCommand &c); void processNonReliableCommand (ConnectionCommand &c); void serve (Address bind_address); void connect (Address address); void disconnect (); void disconnect_peer(u16 peer_id); void send (u16 peer_id, u8 channelnum, SharedBuffer<u8> data); void sendReliable (ConnectionCommand &c); void sendToAll (u8 channelnum, SharedBuffer<u8> data); void sendToAllReliable(ConnectionCommand &c); void sendPackets (float dtime); void sendAsPacket (u16 peer_id, u8 channelnum, SharedBuffer<u8> data,bool ack=false); void sendAsPacketReliable(BufferedPacket& p, Channel* channel); bool packetsQueued(); Connection* m_connection; unsigned int m_max_packet_size; float m_timeout; std::queue<OutgoingPacket> m_outgoing_queue; Semaphore m_send_sleep_semaphore; unsigned int m_iteration_packets_avaialble; unsigned int m_max_commands_per_iteration; unsigned int m_max_data_packets_per_iteration; unsigned int m_max_packets_requeued; }; class ConnectionReceiveThread : public Thread { public: ConnectionReceiveThread(unsigned int max_packet_size); void *run(); void setParent(Connection *parent) { assert(parent); // Pre-condition m_connection = parent; } private: void receive(); // Returns next data from a buffer if possible // If found, returns true; if not, false. // If found, sets peer_id and dst bool getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst); bool checkIncomingBuffers(Channel *channel, u16 &peer_id, SharedBuffer<u8> &dst); /* Processes a packet with the basic header stripped out. Parameters: packetdata: Data in packet (with no base headers) peer_id: peer id of the sender of the packet in question channelnum: channel on which the packet was sent reliable: true if recursing into a reliable packet */ SharedBuffer<u8> processPacket(Channel *channel, SharedBuffer<u8> packetdata, u16 peer_id, u8 channelnum, bool reliable); Connection* m_connection; }; class Connection { public: friend class ConnectionSendThread; friend class ConnectionReceiveThread; Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6, PeerHandler *peerhandler); ~Connection(); /* Interface */ ConnectionEvent waitEvent(u32 timeout_ms); void putCommand(ConnectionCommand &c); void SetTimeoutMs(int timeout) { m_bc_receive_timeout = timeout; } void Serve(Address bind_addr); void Connect(Address address); bool Connected(); void Disconnect(); void Receive(NetworkPacket* pkt); void Send(u16 peer_id, u8 channelnum, NetworkPacket* pkt, bool reliable); u16 GetPeerID() { return m_peer_id; } Address GetPeerAddress(u16 peer_id); float getPeerStat(u16 peer_id, rtt_stat_type type); float getLocalStat(rate_stat_type type); const u32 GetProtocolID() const { return m_protocol_id; }; const std::string getDesc(); void DisconnectPeer(u16 peer_id); protected: PeerHelper getPeer(u16 peer_id); PeerHelper getPeerNoEx(u16 peer_id); u16 lookupPeer(Address& sender); u16 createPeer(Address& sender, MTProtocols protocol, int fd); UDPPeer* createServerPeer(Address& sender); bool deletePeer(u16 peer_id, bool timeout); void SetPeerID(u16 id) { m_peer_id = id; } void sendAck(u16 peer_id, u8 channelnum, u16 seqnum); void PrintInfo(std::ostream &out); void PrintInfo(); std::list<u16> getPeerIDs() { MutexAutoLock peerlock(m_peers_mutex); return m_peer_ids; } UDPSocket m_udpSocket; MutexedQueue<ConnectionCommand> m_command_queue; void putEvent(ConnectionEvent &e); void TriggerSend() { m_sendThread.Trigger(); } private: std::list<Peer*> getPeers();