-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc2mp-peer.js
More file actions
1390 lines (1136 loc) · 36.3 KB
/
c2mp-peer.js
File metadata and controls
1390 lines (1136 loc) · 36.3 KB
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
(function () {
// Polyfill string.trim if missing
if (!String.prototype.trim)
{
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
var RTCPeerConnection = window["RTCPeerConnection"] || window["webkitRTCPeerConnection"] || window["mozRTCPeerConnection"] || window["msRTCPeerConnection"];
var MAGIC_NUMBER = 0x63326D70; // to identify non-fragmented messages originating from this protocol
// In some circumstances calling close() can throw an exception (e.g. if it already got closed by system sleep).
// Avoid this crashing the game by swallowing any exceptions.
function closeIgnoreException(o)
{
if (!o)
return;
try {
o.close();
}
catch (e)
{
}
};
function Peer(mp_, id_, alias_)
{
this.mp = mp_;
this.id = id_; // signalling-assigned ID
this.nid = 0; // network ID
this.alias = alias_;
this.pc = null; // WebRTC peer connection
this.dco = null; // Reliable and ordered channel
this.isOOpen = false;
this.dcr = null; // Reliable and unordered datachannel
this.isROpen = false;
this.dcu = null; // Unreliable and unordered datachannel
this.isUOpen = false;
this.firedOpen = false; // for firing onOpen
this.firedClose = false; // for firing onClose
this.wasRemoved = false;
this.hasConfirmed = false;
this.lastHeardFrom = 0; // last heard from in local time for timing out unreachable peers
this.connectTime = 0; // time host tried to connect to (will kick after a timeout)
this.errorCount = 0; // too many errors will remove a client
this.localClientState = [];
this.lastStateChange = 0;
this.lastStateTransmit = 0;
this.clientStateUpdates = []; // netupdates for received client states
this.priorUpdate2 = null; // the second update before interp time
this.priorUpdate = null; // the first update before interp time
this.nextUpdate = null; // the first update after interp time
// Latency measurement
this.lastPingSent = 0;
this.awaitingPong = false;
this.lastSentPingId = 1;
this.lastPingTimes = [];
this.latency = 0;
this.pdv = 0; // packet delay variation
// Add self to the multiplayer object peer list
this.mp.peers.push(this);
this.mp.peers_by_id[this.id] = this;
};
Peer.prototype.attachDatachannelHandlers = function (dc, type)
{
var self = this;
dc.binaryType = "arraybuffer";
dc.onopen = function ()
{
if (type === "o")
self.isOOpen = true;
else if (type === "r")
self.isROpen = true;
else if (type === "u")
self.isUOpen = true;
self.maybeFireOpen();
};
dc.onmessage = function (m)
{
self.onMessage(type, m);
};
dc.onerror = function (e)
{
console.error("Peer '" + self.id + "' datachannel '" + type + "' error: ", e);
if (self.mp.onpeererror)
self.mp.onpeererror(self, e);
// Host removes any datachannel which encounters an error.
if (self.mp.me === self.mp.host && self !== self.mp.host)
{
self.remove("network error");
}
};
dc.onclose = function ()
{
self.remove("disconnect");
};
};
Peer.prototype.connect = function ()
{
if (this.mp.me === this)
return; // cannot connect to self!
// Host creates offer, peer responds with answer
var iamhost = (this.mp.me === this.mp.host);
var self = this;
this.isOOpen = false;
this.isROpen = false;
this.isUOpen = false;
this.firedOpen = false;
this.firedClose = false;
this.connectTime = window.cr_performance_now();
// Create the peer connection. Enable Google's experimental IPv6 support.
this.pc = new RTCPeerConnection({"iceServers": this.mp.getIceServerList()}, {"optional": [{"googIPv6": true}]});
// Forward ICE candidates to this peer via signalling
this.pc.onicecandidate = function (e)
{
if (e.candidate)
{
self.mp.signallingSend({
message: "icecandidate",
toclientid: self.id,
icecandidate: e.candidate
});
}
};
// Detect if peerconnection closes
this.pc.onsignalingstatechange = function ()
{
if (!self.pc)
return;
if (self.pc.signalingState === "closed")
{
self.remove("disconnect");
}
};
// Detect if ICE connection closes
this.pc.oniceconnectionstatechange = function ()
{
if (!self.pc)
return;
if (self.pc.iceConnectionState === "connected")
{
//self.isConnected = true;
}
else if (self.pc.iceConnectionState === "failed" || self.pc.iceConnectionState === "closed")
{
self.remove("disconnect");
}
};
var dc_protocol = "c2mp_" + this.mp.game + "_" + this.mp.gameinstance + "_" + this.mp.room;
if (iamhost)
{
this.nid = this.mp.allocatePeerNid();
// 'reliable' property not in spec but is present in some code samples, so may still be understood by browsers
this.dco = this.pc.createDataChannel("o", {ordered: true, protocol: dc_protocol});
this.attachDatachannelHandlers(this.dco, "o");
this.dcr = this.pc.createDataChannel("r", {ordered: false, protocol: dc_protocol});
this.attachDatachannelHandlers(this.dcr, "r");
this.dcu = this.pc.createDataChannel("u", {ordered: false, maxRetransmits: 0, protocol: dc_protocol});
this.attachDatachannelHandlers(this.dcu, "u");
// Create an offer and dispatch it to the peer
this.pc.createOffer()
.then(function (offer)
{
self.pc.setLocalDescription(offer);
self.mp.signallingSend({
message: "offer",
toclientid: self.id,
offer: offer
});
})
.catch(function (err)
{
console.error("Host error creating offer for peer '" + self.id + "': " + err);
if (self.mp.onpeererror)
self.mp.onpeererror(self, "could not create offer for peer");
});
}
// I am not the host
else
{
// Fires when connection established and datachannel received
this.pc.ondatachannel = function (e)
{
if (e.channel.protocol !== dc_protocol)
{
console.error("Unexpected datachannel protocol '" + e.channel.protocol + "', should be '" + expect_protocol + "'");
if (self.mp.onpeererror)
{
self.mp.onpeererror(self, "unexpected datachannel protocol '" + e.channel.protocol + "', should be '" + expect_protocol + "'");
}
return;
}
var label = e.channel.label;
if (label === "o")
self.dco = e.channel;
else if (label === "r")
self.dcr = e.channel;
else if (label === "u")
self.dcu = e.channel;
else
{
console.error("Unknown datachannel label: " + e.channel.label);
if (self.mp.onpeererror)
{
self.mp.onpeererror(self, "unknown datachannel label '" + e.channel.label + "'");
}
}
self.attachDatachannelHandlers(e.channel, label);
};
}
};
Peer.prototype.maybeFireOpen = function ()
{
if (this.firedOpen)
return;
// Only ready to fire open event when all datachannels are open
if (this.isROpen && this.isUOpen && this.isOOpen)
{
this.onOpen();
this.firedOpen = true;
this.firedClose = false;
}
};
Peer.prototype.onOpen = function ()
{
this.lastHeardFrom = window.cr_performance_now();
// If host, notify other peers of join, and notify the joining peer of the other peers
if (this.mp.me === this.mp.host)
{
this.mp.hostBroadcast("o", JSON.stringify({
"c": "j",
"i": this.id,
"n": this.nid,
"a": this.alias
}), this);
this.send("o", JSON.stringify({
"c": "hi",
"hn": this.mp.host.nid, // host NID
"n": this.nid, // client's assigned NID
"d": this.mp.clientDelay, // mandatory client-side delay
"u": this.mp.peerUpdateRateSec, // advised upload rate
"objs": this.mp.getRegisteredObjectsMap(), // registered objects SID map
"cvs": this.mp.getClientValuesJSON() // client values host is expecting
}));
var i, len, p;
for (i = 0, len = this.mp.peers.length; i < len; ++i)
{
p = this.mp.peers[i];
if (p === this.mp.host || p === this || !p.isOpen())
continue;
this.send("o", JSON.stringify({
"c": "j",
"i": p.id,
"n": p.nid,
"a": p.alias
}));
}
}
else
{
// No need to confirm peers when not host
this.hasConfirmed = true;
// I am not host, but need to know host clock/latency info ASAP: ping
// the host upon connection
if (this === this.mp.host)
this.sendPing(window.cr_performance_now(), true);
}
if (this.mp.onpeeropen)
this.mp.onpeeropen(this);
};
Peer.prototype.maybeFireClose = function (reason)
{
if (this.firedClose || !this.firedOpen)
return;
this.onClose(reason);
this.firedClose = true;
this.firedOpen = false;
};
Peer.prototype.onClose = function (reason)
{
// If host, notify other peers of this peer leaving (unless it's host leaving, in which case it'll send disconnect instead)
if (this.mp.me === this.mp.host && this !== this.mp.me)
{
this.mp.hostBroadcast("o", JSON.stringify({
"c": "l",
"i": this.id,
"a": this.alias,
"r": reason
}), this);
}
// Don't fire close event for local client
if (this.mp.onpeerclose && this !== this.mp.me)
this.mp.onpeerclose(this, reason);
};
Peer.prototype.isOpen = function ()
{
return this.firedOpen && !this.firedClose;
};
Peer.prototype.send = function (type, m)
{
// Track outbound messages and bandwidth for statistics
this.mp.stats.outboundCount++;
if (m.length)
this.mp.stats.outboundBandwidthCount += m.length;
else if (m.byteLength)
this.mp.stats.outboundBandwidthCount += m.byteLength;
// Simulate packet loss on the unreliable channel by simply
// ignoring sends in some cases
if (this.mp.simPacketLoss > 0 && type === "u")
{
if (Math.random() < this.mp.simPacketLoss)
return;
}
// No latency simulation: dispatch immediately
if (this.mp.simLatency === 0 && this.mp.simPdv === 0)
{
this.doSend(type, m);
}
// Otherwise simulate a latency in this packet being sent outbound
else
{
var self = this;
// For the reliable channels, if we are simulating packet loss then we multiply up
// the simulated latency when a packet is "lost". This is to simulate a lost packet,
// a response from the other end indicating it's missing, then retransmission. Thus
// instead of a one-way journey there is a three-way journey, so we multiply by 3.
var multiplier = 1;
if (type !== "u" && Math.random() < this.mp.simPacketLoss)
multiplier = 3;
setTimeout(function () {
self.doSend(type, m);
}, this.mp.simLatency * multiplier + Math.random() * this.mp.simPdv * multiplier);
}
};
Peer.prototype.doSend = function (type, m)
{
try {
if (type === "o")
{
if (this.isOOpen && this.dco)
this.dco.send(m);
}
else if (type === "r")
{
if (this.isROpen && this.dcr)
this.dcr.send(m);
}
else if (type === "u")
{
if (this.isUOpen && this.dcu)
this.dcu.send(m);
}
}
catch (e)
{
// Ignore errors if peer already removed
if (this.wasRemoved)
return;
// If host, remove peers that encounter errors
if (this.mp.me === this.mp.host)
{
// Since the O and R channels are meant to be reliable, remove the peer if there's an error sending down
// these, since the message will have been lost. On the other hand U errors are acceptable (counts as packet
// loss), but in some cases unreachable peers will throw an error on every send(). In this case, remove
// the peer if an error limit is exceeded.
if (type === "o" || type === "r")
{
if (typeof m === "string")
{
console.error("Error sending " + m.length + "-char string on '" + type + "' to '" + this.alias + "', host kicking: ", e);
console.log("String that failed to send from previous error was: " + m);
}
else
{
console.error("Error sending " + (m.length || m.byteLength) + "-byte binary on '" + type + "' to '" + this.alias + "', host kicking: ", e);
}
this.remove("network error");
}
else
{
this.errorCount++;
if (this.errorCount >= 10) // too many errors, assume peer is no longer reachable
{
if (typeof m === "string")
{
console.error("Too many errors (" + this.errorCount + ") sending data on '" + type + "' to '" + this.alias + "', kicking; last error was for sending " + m.length + "-char string: ", e);
console.log("String that failed to send from previous error was: " + m);
}
else
{
console.error("Too many errors (" + this.errorCount + ") sending data on '" + type + "' to '" + this.alias + "', kicking; last error was for sending " + (m.length || m.byteLength) + "-byte binary: ", e);
}
this.remove("network error");
}
}
}
else
{
// Log an error but try to keep things going
console.error("Error sending data on '" + type + "': ", e);
}
}
};
Peer.prototype.sendPing = function (nowtime, force)
{
if (this.wasRemoved)
return;
// If not connected and has been unable to establish connection after 25 sec, time out the peer.
// Note signalling ought to send us quit notifications anyway if they don't get a confirmation
// within the signalling server's own time limit, but in some cases the host seems to be left
// with a timed out peer anyway, so this additional timeout is a backup.
if (!force && !this.isOpen() && this.pc && (nowtime - this.connectTime > 25000))
{
console.warn("Timed out '" + this.alias + "', could not establish connection after 25sec");
this.remove("timeout");
return;
}
// If connected but not heard from for 20 sec, time out the peer
if (!force && this.isOpen() && (nowtime - this.lastHeardFrom > 20000))
{
console.warn("Timed out '" + this.alias + "', not heard from for 20sec");
this.remove("timeout");
return;
}
this.lastPingSent = nowtime;
this.awaitingPong = true;
this.lastSentPingId++;
this.send("u", "ping:" + this.lastSentPingId);
};
Peer.prototype.sendPong = function (pingstr)
{
// Respond with the same ping ID as was sent, i.e. "ping:8" responds "pong:8"
var response = "pong:" + pingstr.substr(5);
// Is host: include current time in pong response for clock synchronisation, e.g. "pong:8/12045"
if (this.mp.host === this.mp.me)
{
response += "/";
response += Math.round(window.cr_performance_now()).toString();
}
this.send("u", response);
};
var tempArray = [];
function compareNumbers(a, b)
{
return a - b;
}
Peer.prototype.onPong = function (str)
{
if (!this.awaitingPong)
return; // ignore spurious or late pongs which could throw off measurements
// Check the pong returned the same ID we sent it with. This ensures we received the response
// to the last sent ping and not some other late or mixed up response.
var colon = str.indexOf(":");
if (colon > -1)
{
var pongId = parseFloat(str.substr(colon + 1));
if (pongId !== this.lastSentPingId)
return; // ignore
}
else
{
console.warn("Cannot parse off ping ID from pong");
return;
}
// Estimate the one-way transmission time. The packet has gone both ways, so we estimate the latency is half the round-trip time.
var nowtime = window.cr_performance_now();
this.awaitingPong = false;
var lastlatency = (nowtime - this.lastPingSent) / 2;
this.lastPingTimes.push(lastlatency);
// Keep last 10 pings
if (this.lastPingTimes.length > 10)
this.lastPingTimes.shift();
// Copy the last ping times, sort them, and remove the top and bottom two
// to eliminate any outliers. Take the latency as the average of the remaining
// six ping measurements.
window.cr_shallowAssignArray(tempArray, this.lastPingTimes);
tempArray.sort(compareNumbers);
// Update packet delay variation, including all values (outliers will be counted)
this.pdv = tempArray[tempArray.length - 1] - tempArray[0];
// If we're still getting going, the ping buffer won't be full. Remove the
// top and bottom entries depending on how many there are.
var start = 0;
var end = tempArray.length;
if (tempArray.length >= 4 && tempArray.length <= 6)
{
++start;
--end;
}
else if (tempArray.length > 6)
{
start += 2;
end -= 2;
}
// Set estimated latency to the average of the middle values.
var i, sum = 0;
for (i = start; i < end; ++i)
sum += tempArray[i];
this.latency = (sum / (end - start));
// If not the host, then parse off the host clock time to estimate the clock difference.
if (this.mp.host !== this.mp.me)
{
var slash = str.indexOf("/");
if (slash > -1)
{
var hosttime = parseFloat(str.substr(slash + 1));
if (isFinite(hosttime))
{
this.mp.addHostTime(hosttime, nowtime, lastlatency, this.latency);
}
else
console.warn("Invalid host time from pong response");
}
else
console.warn("Cannot parse off host time from pong response");
}
};
Peer.prototype.onMessage = function (type, m)
{
// Simulate packet loss on unreliable channel
if (this.mp.simPacketLoss > 0 && type === "u")
{
if (Math.random() < this.mp.simPacketLoss)
return;
}
// No latency simulation: dispatch immediately
if (this.mp.simLatency === 0 && this.mp.simPdv === 0)
{
this.doOnMessage(type, m);
}
// Otherwise simulate a latency in this packet being sent outbound
else
{
var self = this;
var multiplier = 1;
if (type !== "u" && Math.random() < this.mp.simPacketLoss)
multiplier = 3;
setTimeout(function () {
self.doOnMessage(type, m);
}, this.mp.simLatency * multiplier + Math.random() * this.mp.simPdv * multiplier);
}
};
Peer.prototype.doOnMessage = function (type, m)
{
// Ignore messages received after removing a peer
if (this.wasRemoved)
return;
this.lastHeardFrom = window.cr_performance_now();
// Track inbound count and bandwidth for statistics
this.mp.stats.inboundCount++;
if (m.data.length)
this.mp.stats.inboundBandwidthCount += m.data.length;
else if (m.data.byteLength)
this.mp.stats.inboundBandwidthCount += m.data.byteLength;
// Handle text message
if (typeof m.data === "string")
{
// Sometimes browsers seem to send empty or whitespace-only string messages on connection.
// Ignore any such whitespace messages or anything that looks too short to be a valid message.
if (m.data.trim() === "" || m.data.length < 4)
return;
// Respond to pings with pongs
var first4 = m.data.substr(0, 4);
if (first4 === "ping")
{
this.sendPong(m.data);
return;
}
if (first4 === "pong")
{
this.onPong(m.data);
return;
}
var o;
try {
o = JSON.parse(m.data);
}
catch (e)
{
if (this.mp.onpeererror)
this.mp.onpeererror(this, e);
if (this.mp.me === this.mp.host)
{
console.error("Error parsing message as JSON for peer '" + this.id + "', host kicking: ", e);
this.remove("data error");
}
else
{
console.error("Error parsing message as JSON for peer '" + this.id + "': ", e);
}
console.log("String that failed to parse from previous error: " + m.data);
return;
}
if (!o)
return;
// control message
try {
if (o["c"] && o["c"] !== "m")
{
this.onControlMessage(o);
}
// user message
else
{
if (this.mp.onpeermessage)
this.mp.onpeermessage(this, o);
}
}
catch (e)
{
if (this.mp.onpeererror)
this.mp.onpeererror(this, e);
if (this.mp.me === this.mp.host)
{
console.error("Error handling message for peer '" + this.id + "', host kicking: ", e);
this.remove("data error");
}
else
{
console.error("Error handling message for peer '" + this.id + "': ", e);
}
}
return;
}
// Handle binary message
else
{
// Confirm peer to server on first binary update on the "u" channel. Some peers appear to
// connect OK but then fail to receive any binary updates. Not sure why this is.
if (!this.hasConfirmed && this.mp.me === this.mp.host && type === "u")
{
// Tell signalling server we successfully connected to this peer
this.hasConfirmed = true;
this.mp.signallingConfirmPeer(this.id);
}
try {
this.onBinaryMessage(m.data);
}
catch (e) {
if (this.mp.onpeererror)
this.mp.onpeererror(this, e);
if (this.mp.me === this.mp.host)
{
console.error("Error handling binary update for peer '" + this.id + "', host kicking: ", e);
this.remove("data error");
}
else
{
console.error("Error handling binary update for peer '" + this.id + "': ", e);
}
return;
}
}
};
Peer.prototype.onControlMessage = function (o)
{
var peer;
var leave_room;
switch (o["c"]) {
case "disconnect": // connection being closed from other end
// If this is a kick, trigger 'On kicked'
if (o["k"])
this.mp.onPeerKicked();
// If not the host, we've lost the host connection and are therefore no longer
// in the room. So also leave the room on the signalling server too.
// This must be checked before remove() since it will clear the me/host peers.
leave_room = (this.mp.me !== this.mp.host && this === this.mp.host)
this.remove(o["r"]);
if (leave_room)
this.mp.signallingLeaveRoom();
break;
case "hi": // welcome message from host
if (this.mp.me !== this.mp.host)
{
this.mp.host.nid = o["hn"];
this.mp.me.nid = o["n"];
// adopt host-advised config
this.mp.clientDelay = o["d"];
this.mp.peerUpdateRateSec = o["u"];
// map object NIDs to SIDs
this.mp.mapObjectNids(o["objs"]);
// override client values with what the host advises
this.mp.mapClientValues(o["cvs"]);
}
break;
case "j": // peer joined (only valid if not host)
if (this.mp.me !== this.mp.host)
{
peer = new Peer(this.mp, o["i"], o["a"]);
peer.nid = o["n"];
// We don't really connect to them but fire the open event so client knows they're here
if (this.mp.onpeeropen)
this.mp.onpeeropen(peer);
}
break;
case "l": // peer left (only valid if not host)
if (this.mp.me !== this.mp.host)
{
peer = this.mp.peers_by_id[o["i"]];
if (peer)
{
if (this.mp.onpeerclose && peer !== this.mp.me)
this.mp.onpeerclose(peer, o["r"]);
peer.remove(o["r"]);
}
}
break;
default:
console.error("Unknown control message from peer '" + this.id + "': " + o["c"]);
if (this.mp.onpeererror)
this.mp.onpeererror(this, "unknown control message '" + o["c"] + "'");
break;
}
};
var value_arrs = [];
function allocValueArr()
{
if (value_arrs.length)
return value_arrs.pop();
else
return [];
};
function freeValueArr(a)
{
a.length = 0;
if (value_arrs.length < 10000)
value_arrs.push(a);
};
window["allocValueArr"] = allocValueArr;
window["freeValueArr"] = freeValueArr;
Peer.prototype.onBinaryMessage = function (buffer)
{
if (this.mp.me === this.mp.host)
this.onHostUpdate(buffer);
else
this.onPeerUpdate(buffer);
};
Peer.prototype.onHostUpdate = function (buffer)
{
var i, len, cv, value;
/* Net format:
uint32 MAGIC_NUMBER
float64 timestamp
uint8 flags (reserved)
uint8 client state value count
float32 client state 0
float32 client state 1
...
float32 client state N
*/
var view = new DataView(buffer);
var ptr = 0;
var magic_number = view.getUint32(ptr); ptr += 4;
if (magic_number !== MAGIC_NUMBER)
{
console.warn("Rejected packet with incorrect magic number (received '" + magic_number + "', expected '" + MAGIC_NUMBER + "'");
return;
}
var timestamp = view.getFloat64(ptr); ptr += 8;
// The timestamp is what the peer estimated the host's clock to be at the time it was sent.
// However it will be delayed in transmission, so add the peer's estimated latency on top of that.
// This means client input state packets should end up with timestamps close to the host time
// they were actually received, but varying by the network PDV which interpolation can then compensate for.
timestamp += this.latency;
// The peer could possibly try to manipulate the game by varying the timestamp deliberately. To try to
// avoid this, reject any incoming client state packets which are more than 3 seconds off the host time.
if (Math.abs(timestamp - window.cr_performance_now()) >= 3000)
return;
var flags = view.getUint8(ptr); ptr += 1;
// Number of client state values
var len = view.getUint8(ptr); ptr += 1;
var arr = allocValueArr();
arr.length = len;
var clientvalues = this.mp.clientvalues;
for (i = 0; i < len; ++i)
{
if (i >= clientvalues.length)
{
arr[i] = 0;
continue;
}
cv = clientvalues[i];
switch (cv.precision) {
case 0: // high, double
value = view.getFloat64(ptr);
ptr += 8;
break;
case 1: // normal, float
value = view.getFloat32(ptr);
ptr += 4;
break;
case 2: // low, int16
value = cv.maybeUnpack(view.getInt16(ptr));
ptr += 2;
break;
case 3: // very low, uint8
value = cv.maybeUnpack(view.getUint8(ptr));
ptr += 1;
break;
default:
value = view.getFloat32(ptr);
ptr += 4;
break;
}
arr[i] = value;
}
this.addClientUpdate(timestamp, arr);
};
Peer.prototype.addClientUpdate = function (timestamp_, data_)
{
// Insert the new update in to the correct place in the updates queue
// using its timestamp
var i, len, u;
for (i = 0, len = this.clientStateUpdates.length; i < len; ++i)
{
u = this.clientStateUpdates[i];
// Timestamp matches another update exactly: must be a duplicate packet; discard it
if (u.timestamp === timestamp_)
{
freeValueArr(data_);
return;
}
if (u.timestamp > timestamp_)
{
this.clientStateUpdates.splice(i, 0, allocNetUpdate(timestamp_, data_));
return;
}
}
// If not inserted by above loop, must be latest update so add to end
this.clientStateUpdates.push(allocNetUpdate(timestamp_, data_));