85 lines
2.6 KiB
GDScript
85 lines
2.6 KiB
GDScript
class_name CoopLink
|
|
extends RefCounted
|
|
## The wire between the two machines of a co-op game (CoopSession talks only to this). send()
|
|
## delivers one message (a kind and a Variant) to the other side, reliably (in order, never
|
|
## lost) or not (may be dropped; for the 20 Hz snapshots and the partner's input, which the next
|
|
## one replaces). received is emitted on the other side.
|
|
## GDSyncLink is the real one (GD-Sync, LAN or online). CoopLink.pair() makes two loopback links
|
|
## for tests: messages go through var_to_bytes / bytes_to_var like on the wire, and are delivered
|
|
## when the receiving side polls. Every link counts what it sends; unreliable messages over
|
|
## UNRELIABLE_LIMIT bytes are counted as too big (GD-Sync splits datagrams at 1200 bytes).
|
|
|
|
signal received(kind: String, data: Variant)
|
|
|
|
const UNRELIABLE_LIMIT := 1100
|
|
|
|
var sent_messages: int = 0
|
|
var sent_bytes: int = 0
|
|
## The largest unreliable message so far (bytes) and how many were over the limit.
|
|
var largest_unreliable: int = 0
|
|
var oversized: int = 0
|
|
## Set when the other side went away.
|
|
var closed := false
|
|
|
|
|
|
func send(kind: String, data: Variant, reliable: bool) -> void:
|
|
var size := var_to_bytes([kind, data]).size()
|
|
sent_messages += 1
|
|
sent_bytes += size
|
|
if not reliable:
|
|
largest_unreliable = maxi(largest_unreliable, size)
|
|
if size > UNRELIABLE_LIMIT:
|
|
oversized += 1
|
|
_deliver(kind, data, reliable)
|
|
|
|
|
|
## Delivers what has arrived (loopback links; GD-Sync delivers on its own).
|
|
func poll() -> void:
|
|
pass
|
|
|
|
|
|
func close() -> void:
|
|
closed = true
|
|
|
|
|
|
func _deliver(_kind: String, _data: Variant, _reliable: bool) -> void:
|
|
pass
|
|
|
|
|
|
## Two loopback links, each the other's far end.
|
|
static func pair() -> Array[CoopLink]:
|
|
var a := Loopback.new()
|
|
var b := Loopback.new()
|
|
a.other = b
|
|
b.other = a
|
|
return [a, b]
|
|
|
|
|
|
class Loopback extends CoopLink:
|
|
var other: Loopback
|
|
## Drops every n-th unreliable message (0 = none), to test that nothing depends on them.
|
|
var drop_every: int = 0
|
|
var _inbox: Array = []
|
|
var _count: int = 0
|
|
|
|
func _deliver(kind: String, data: Variant, reliable: bool) -> void:
|
|
if other == null or other.closed:
|
|
return
|
|
_count += 1
|
|
if not reliable and drop_every > 0 and _count % drop_every == 0:
|
|
return
|
|
other._inbox.append(var_to_bytes([kind, data])) # as on the wire
|
|
|
|
func poll() -> void:
|
|
var batch := _inbox
|
|
_inbox = []
|
|
for bytes: PackedByteArray in batch:
|
|
var m: Array = bytes_to_var(bytes)
|
|
received.emit(String(m[0]), m[1])
|
|
|
|
func close() -> void:
|
|
closed = true
|
|
if other != null:
|
|
other.closed = true
|
|
other.other = null # the pair refers to each other: break the cycle
|
|
other = null
|