-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
1747 lines (1747 loc) · 78.9 KB
/
main.js
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
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
///////////////////////////////////////////////////////////////////////////////
// Collections
define("entity", ["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
///////////////////////////////////////////////////////////////////////////////
// Entity: Base entity
var Input = /** @class */ (function () {
function Input() {
}
Input.prototype.copy = function (src) {
this.pressTime = src.pressTime;
this.inputSequenceNumber = src.inputSequenceNumber;
this.entityID = src.entityID;
this.position = src.position;
};
return Input;
}());
exports.Input = Input;
var Entity = /** @class */ (function () {
function Entity() {
this.x = 0;
this.displayX = 0;
this.speed = 2;
this.connected = true;
this.error = false;
}
Entity.prototype.applyInput = function (input) {
this.x += input.pressTime * this.speed;
this.setPosition(this.x);
};
Entity.prototype.setPosition = function (x) {
this.x = x;
this.displayX = x;
};
return Entity;
}());
exports.Entity = Entity;
///////////////////////////////////////////////////////////////////////////////
// LocalEntity: Represents the player on the client
var LocalEntity = /** @class */ (function (_super) {
__extends(LocalEntity, _super);
function LocalEntity() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.inputSequenceNumber = 0;
_this.pendingInputs = [];
_this.smooth = false;
_this.errorTimer = 0;
return _this;
}
LocalEntity.prototype.incrementSequenceNumber = function () {
this.inputSequenceNumber++;
return this.inputSequenceNumber;
};
LocalEntity.prototype.numberOfPendingInputs = function () {
return this.pendingInputs.length;
};
LocalEntity.prototype.saveInput = function (input) {
this.pendingInputs.push(input);
};
LocalEntity.prototype.dropInputs = function () {
this.pendingInputs = [];
};
LocalEntity.prototype.setPosition = function (x) {
this.x = x;
};
LocalEntity.prototype.errorCorrect = function (dtSec) {
if (this.error && this.smooth) {
var weight = Math.max(0.0, 0.75 - this.errorTimer);
this.displayX = this.displayX * weight + this.x * (1.0 - weight);
this.errorTimer += dtSec;
var offset = this.displayX - this.x;
if (Math.abs(offset) < 0.00001) {
this.error = false;
}
}
else {
this.displayX = this.x;
if (!this.smooth) {
this.error = false;
}
}
};
LocalEntity.prototype.reconcile = function (state) {
// Set authoritative position
this.x = state.position;
var idx = 0;
while (idx < this.pendingInputs.length) {
var input = this.pendingInputs[idx];
if (input.inputSequenceNumber == state.lastProcessedInput) {
var offset = state.position - input.position;
if (Math.abs(offset) >= 0.00001) {
this.error = true;
this.errorTimer = 0.0;
}
}
idx++;
}
// Server Reconciliation. Re-apply all the inputs not yet processed by
// the server.
var j = 0;
while (j < this.pendingInputs.length) {
var input = this.pendingInputs[j];
if (input.inputSequenceNumber <= state.lastProcessedInput) {
// Already processed. Its effect is already taken into account into the world update
// we just got, so we can drop it.
this.pendingInputs.splice(j, 1);
}
else {
// Not processed by the server yet. Re-apply it.
this.applyInput(input);
j++;
}
}
};
return LocalEntity;
}(Entity));
exports.LocalEntity = LocalEntity;
///////////////////////////////////////////////////////////////////////////////
// RemoteEntity: Represents the other players on the client
var InterpolationPosition = /** @class */ (function () {
function InterpolationPosition(timestamp, position) {
this.timestamp = timestamp;
this.position = position;
}
return InterpolationPosition;
}());
exports.InterpolationPosition = InterpolationPosition;
var RemoteEntity = /** @class */ (function (_super) {
__extends(RemoteEntity, _super);
function RemoteEntity() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.positionBuffer = [];
return _this;
}
RemoteEntity.prototype.addPosition = function (position) {
this.positionBuffer.push(position);
};
RemoteEntity.prototype.interpolate = function (renderTimestamp) {
// Find the two authoritative positions surrounding the rendering timestamp
var buffer = this.positionBuffer;
// Drop older positions
while (buffer.length >= 2 && buffer[1].timestamp <= renderTimestamp) {
buffer.shift();
}
// Interpolate between the two surrounding authoritative positions
if (buffer.length >= 2 && buffer[0].timestamp <= renderTimestamp && renderTimestamp <= buffer[1].timestamp) {
var x0 = buffer[0].position;
var x1 = buffer[1].position;
var t0 = buffer[0].timestamp;
var t1 = buffer[1].timestamp;
this.x = x0 + (x1 - x0) * (renderTimestamp - t0) / (t1 - t0);
}
else if (buffer.length == 1) {
var x = buffer[0].position;
this.x = x;
}
};
return RemoteEntity;
}(Entity));
exports.RemoteEntity = RemoteEntity;
///////////////////////////////////////////////////////////////////////////////
// ServerEntity: Represents the players on the server
var ServerEntityState = /** @class */ (function () {
function ServerEntityState() {
}
ServerEntityState.prototype.copy = function (src) {
this.entityID = src.entityID;
this.position = src.position;
this.lastProcessedInput = src.lastProcessedInput;
};
return ServerEntityState;
}());
exports.ServerEntityState = ServerEntityState;
var ServerEntity = /** @class */ (function (_super) {
__extends(ServerEntity, _super);
function ServerEntity() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.lastProcessedInput = 0;
return _this;
}
ServerEntity.prototype.getLastProcessedInput = function () {
return this.lastProcessedInput;
};
ServerEntity.prototype.constructState = function () {
var state = new ServerEntityState();
state.entityID = this.entityID;
state.position = this.x;
state.lastProcessedInput = this.lastProcessedInput;
return state;
};
// Check whether this input seems to be valid (e.g. "make sense" according
// to the physical rules of the World)
ServerEntity.prototype.validateInput = function (input) {
// if (Math.abs(input.pressTime) > 1.0 / 40.0) {
// return false;
// }
return true;
};
ServerEntity.prototype.processInput = function (input) {
// Update the state of the entity, based on its input
// We just ignore inputs that don't look valid; this is what prevents clients from cheating
if (this.validateInput(input)) {
this.applyInput(input);
this.lastProcessedInput = input.inputSequenceNumber;
}
};
return ServerEntity;
}(Entity));
exports.ServerEntity = ServerEntity;
});
define("lagNetwork", ["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
var Message = /** @class */ (function () {
function Message(payload, fromNetworkID) {
this.payload = payload;
this.fromNetworkID = fromNetworkID;
}
return Message;
}());
var TimedMessage = /** @class */ (function () {
function TimedMessage(sendTS, recvTS, payload) {
this.sendTS = sendTS;
this.recvTS = recvTS;
this.payload = payload;
}
return TimedMessage;
}());
var NetworkState = /** @class */ (function () {
function NetworkState() {
this.lagMin = 0.0;
this.lagMax = 0.0;
this.dropChance = 0.0;
this.dropCorrelation = 0.0;
this.duplicateChance = 0.0;
this.lastDropRoll = 0.0;
}
NetworkState.prototype.set = function (lagMin, lagMax, dropChance, dropCorrelation, duplicateChance) {
this.lagMin = lagMin;
this.lagMax = lagMax;
this.dropChance = dropChance;
this.dropCorrelation = dropCorrelation;
this.duplicateChance = duplicateChance;
};
NetworkState.prototype.copyFrom = function (src) {
this.lagMin = src.lagMin;
this.lagMax = src.lagMax;
this.dropChance = src.dropChance;
this.dropCorrelation = src.dropCorrelation;
this.duplicateChance = src.duplicateChance;
};
NetworkState.prototype.randomLag = function () {
this.lagMax = Math.max(this.lagMax, this.lagMin);
return Math.floor(Math.random() * (this.lagMax - this.lagMin)) + this.lagMin;
};
NetworkState.prototype.shouldDrop = function () {
var newRoll = Math.random();
if (this.lastDropRoll <= this.dropChance) {
newRoll = this.lastDropRoll * this.dropCorrelation + newRoll * (1.0 - this.dropCorrelation);
}
this.lastDropRoll = newRoll;
return newRoll <= this.dropChance;
};
NetworkState.prototype.shouldDuplicate = function () {
return Math.random() <= this.duplicateChance;
};
return NetworkState;
}());
exports.NetworkState = NetworkState;
var LagNetwork = /** @class */ (function () {
function LagNetwork() {
this.debug = false;
this.messages = [];
}
LagNetwork.prototype.send = function (timestamp, state, payload, fromNetworkID) {
if (!state.shouldDrop()) {
this.directSend(new TimedMessage(timestamp, timestamp + state.randomLag(), new Message(payload, fromNetworkID)));
if (state.shouldDuplicate()) {
this.directSend(new TimedMessage(timestamp, timestamp + state.randomLag(), new Message(payload, fromNetworkID)));
}
}
};
LagNetwork.prototype.directSend = function (message) {
this.messages.push(message);
};
LagNetwork.prototype.receive = function (timestamp) {
if (this.debug)
console.log(this.messages.length); // Rudimentary estimation of bandwidth
for (var i = 0; i < this.messages.length; i++) {
var message = this.messages[i];
if (message.recvTS <= timestamp) {
this.messages.splice(i, 1);
return message.payload;
}
}
};
return LagNetwork;
}());
exports.LagNetwork = LagNetwork;
});
define("render", ["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
// Render all the entities in the given canvas
function renderWorld(canvas, entities) {
// Clear the canvas
canvas.width = canvas.width;
var colours = ["blue", "red"];
for (var i in entities) {
var entity = entities[i];
// Compute size and position
var radius = canvas.height * 0.9 / 2.0;
var x = (entity.displayX / 10.0) * canvas.width;
// Draw the entity
var ctx = canvas.getContext("2d");
if (ctx != undefined) {
ctx.beginPath();
ctx.arc(x, canvas.height / 2.0, radius, 0.0, 2.0 * Math.PI, false);
ctx.fillStyle = colours[entity.entityID];
ctx.fill();
ctx.lineWidth = 5;
if (!entity.connected) {
ctx.strokeStyle = "yellow";
}
else if (entity.error) {
ctx.strokeStyle = "green";
}
else {
ctx.strokeStyle = "dark" + colours[entity.entityID];
}
ctx.stroke();
}
}
}
exports.renderWorld = renderWorld;
});
define("netlib/message", ["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
var NetMessageType;
(function (NetMessageType) {
NetMessageType[NetMessageType["Unreliable"] = 0] = "Unreliable";
NetMessageType[NetMessageType["Reliable"] = 1] = "Reliable";
NetMessageType[NetMessageType["ReliableOrdered"] = 2] = "ReliableOrdered";
NetMessageType[NetMessageType["ReliableHeartbeat"] = 3] = "ReliableHeartbeat";
NetMessageType[NetMessageType["Disconnect"] = 4] = "Disconnect"; // For internal use
})(NetMessageType = exports.NetMessageType || (exports.NetMessageType = {}));
var NetMessage = /** @class */ (function () {
function NetMessage() {
}
NetMessage.prototype.getType = function () {
return this.type;
};
NetMessage.prototype.getWireForm = function () {
return {};
};
NetMessage.prototype.fromWireForm = function (src) {
this.type = src.type;
this.payload = src.payload;
this.seqID = src.seqID;
};
return NetMessage;
}());
exports.NetMessage = NetMessage;
var NetUnreliableMessage = /** @class */ (function (_super) {
__extends(NetUnreliableMessage, _super);
function NetUnreliableMessage(payload) {
var _this = _super.call(this) || this;
_this.type = NetMessageType.Unreliable;
_this.payload = payload;
return _this;
}
NetUnreliableMessage.prototype.getWireForm = function () {
return {
"type": this.type,
"payload": this.payload,
"seqID": this.seqID
};
};
return NetUnreliableMessage;
}(NetMessage));
exports.NetUnreliableMessage = NetUnreliableMessage;
var NetReliableMessage = /** @class */ (function (_super) {
__extends(NetReliableMessage, _super);
function NetReliableMessage(payload) {
var _this = _super.call(this, payload) || this;
_this.critical = true;
_this.originalRelSeqID = -1;
_this.type = NetMessageType.Reliable;
return _this;
}
NetReliableMessage.prototype.getWireForm = function () {
return {
"type": this.type,
"payload": this.payload,
"seqID": this.seqID,
"relSeqID": this.relSeqID,
"originalRelSeqID": this.originalRelSeqID,
"relRecvHeadID": this.relRecvHeadID,
"relRecvBuffer": this.relRecvBuffer
};
};
NetReliableMessage.prototype.fromWireForm = function (src) {
this.type = src.type;
this.payload = src.payload;
this.seqID = src.seqID;
this.relSeqID = src.relSeqID;
this.originalRelSeqID = src.originalRelSeqID;
this.relRecvHeadID = src.relRecvHeadID;
this.relRecvBuffer = src.relRecvBuffer;
};
return NetReliableMessage;
}(NetUnreliableMessage));
exports.NetReliableMessage = NetReliableMessage;
var NetReliableOrderedMessage = /** @class */ (function (_super) {
__extends(NetReliableOrderedMessage, _super);
function NetReliableOrderedMessage(payload) {
var _this = _super.call(this, payload) || this;
_this.type = NetMessageType.ReliableOrdered;
return _this;
}
NetReliableOrderedMessage.prototype.getWireForm = function () {
return {
"type": this.type,
"payload": this.payload,
"seqID": this.seqID,
"relSeqID": this.relSeqID,
"originalRelSeqID": this.originalRelSeqID,
"relRecvHeadID": this.relRecvHeadID,
"relRecvBuffer": this.relRecvBuffer,
"relOrderSeqID": this.relOrderSeqID
};
};
NetReliableOrderedMessage.prototype.fromWireForm = function (src) {
this.type = src.type;
this.payload = src.payload;
this.seqID = src.seqID;
this.relSeqID = src.relSeqID;
this.originalRelSeqID = src.originalRelSeqID;
this.relRecvHeadID = src.relRecvHeadID;
this.relRecvBuffer = src.relRecvBuffer;
this.relOrderSeqID = src.relOrderSeqID;
};
return NetReliableOrderedMessage;
}(NetReliableMessage));
exports.NetReliableOrderedMessage = NetReliableOrderedMessage;
var NetIncomingMessage = /** @class */ (function (_super) {
__extends(NetIncomingMessage, _super);
function NetIncomingMessage(fromPeerID) {
var _this = _super.call(this) || this;
_this.fromPeerID = fromPeerID;
return _this;
}
return NetIncomingMessage;
}(NetMessage));
exports.NetIncomingMessage = NetIncomingMessage;
var NetStoredReliableMessage = /** @class */ (function () {
function NetStoredReliableMessage(msg, curTimestamp) {
this.resendInterval = 100; // milliseconds
this.rtt = 0; // milliseconds
this.timesSent = 1;
this.obsolete = false;
this.acked = false;
this.resentSeqID = -1;
this.msg = msg;
this.sentTimestamp = curTimestamp;
this.lastSentTimestamp = curTimestamp;
}
return NetStoredReliableMessage;
}());
exports.NetStoredReliableMessage = NetStoredReliableMessage;
});
define("netlib/event", ["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
var NetEvent;
(function (NetEvent) {
NetEvent[NetEvent["DuplicatesBufferOverrun"] = 0] = "DuplicatesBufferOverrun";
NetEvent[NetEvent["DuplicatesBufferOverflow"] = 1] = "DuplicatesBufferOverflow";
NetEvent[NetEvent["ReliableRecvBufferOverflow"] = 2] = "ReliableRecvBufferOverflow";
NetEvent[NetEvent["ReliableSendBufferOverrun"] = 3] = "ReliableSendBufferOverrun";
NetEvent[NetEvent["ReliableOrderedRecvBufferOverflow"] = 4] = "ReliableOrderedRecvBufferOverflow";
NetEvent[NetEvent["ReliableOrderedRecvBufferOverrun"] = 5] = "ReliableOrderedRecvBufferOverrun";
NetEvent[NetEvent["ReliableDeliveryFailedNoncritical"] = 6] = "ReliableDeliveryFailedNoncritical";
NetEvent[NetEvent["ReliableDeliveryFailedCritical"] = 7] = "ReliableDeliveryFailedCritical";
NetEvent[NetEvent["DisconnectRecv"] = 8] = "DisconnectRecv";
NetEvent[NetEvent["Timeout"] = 9] = "Timeout";
NetEvent[NetEvent["ConnectionEstablished"] = 10] = "ConnectionEstablished";
})(NetEvent = exports.NetEvent || (exports.NetEvent = {}));
var NetEventUtils = /** @class */ (function () {
function NetEventUtils() {
}
NetEventUtils.getEventString = function (error) {
if (error == NetEvent.DuplicatesBufferOverrun) {
return "Duplicates buffer overrun";
}
else if (error == NetEvent.DuplicatesBufferOverflow) {
return "Duplicates buffer overflow";
}
else if (error == NetEvent.ReliableRecvBufferOverflow) {
return "Reliable receive buffer overflow";
}
else if (error == NetEvent.ReliableSendBufferOverrun) {
return "Reliable send buffer overrun";
}
else if (error == NetEvent.ReliableOrderedRecvBufferOverflow) {
return "Reliable ordered receive buffer overflow";
}
else if (error == NetEvent.ReliableOrderedRecvBufferOverrun) {
return "Reliable ordered receive buffer overrun";
}
else if (error == NetEvent.ReliableDeliveryFailedNoncritical) {
return "Reliable message delivery failed noncritical";
}
else if (error == NetEvent.ReliableDeliveryFailedCritical) {
return "Reliable message delivery failed critical";
}
else if (error == NetEvent.DisconnectRecv) {
return "Disconnect request received";
}
else if (error == NetEvent.Timeout) {
return "Timeout";
}
else {
// NetEvent.ConnectionEstablished
return "Connection established";
}
};
NetEventUtils.defaultHandler = function (host, peer, event, msg) {
if (event != NetEvent.ConnectionEstablished && event != NetEvent.ReliableDeliveryFailedNoncritical) {
console.log("netlib event: [" + NetEventUtils.getEventString(event) + "] on address: [" + peer.address + "] ID: [" + peer.id + "]");
host.disconnectPeer(peer.id);
}
};
return NetEventUtils;
}());
exports.NetEventUtils = NetEventUtils;
});
define("netlib/slidingBuffer", ["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
// Circular buffer
var SlidingArrayBuffer = /** @class */ (function () {
function SlidingArrayBuffer(maxSize, fillFunction) {
if (maxSize === void 0) { maxSize = 32; }
this.initialized = false;
this.tailID = 0;
this.headID = -1;
this.buffer = [];
this.maxSize = maxSize;
this.fillFunction = fillFunction;
for (var idx = 0; idx < this.maxSize; ++idx) {
this.buffer.push(fillFunction(idx));
}
}
SlidingArrayBuffer.prototype.getHeadID = function () {
return this.headID;
};
SlidingArrayBuffer.prototype.getMaxSize = function () {
return this.maxSize;
};
SlidingArrayBuffer.prototype.set = function (id, value) {
if (id > this.headID) {
// Reset the values that just went from tail to head
for (var seq = this.headID + 1; seq <= id; ++seq) {
var idx_1 = seq % this.maxSize;
this.buffer[idx_1] = this.fillFunction(seq);
}
// Update the most recently sent ID
this.headID = id;
}
var idx = id % this.maxSize;
this.buffer[idx] = value;
this.tailID = Math.min(this.tailID, id);
this.tailID = Math.max(this.tailID, this.headID - this.maxSize + 1);
this.initialized = true;
};
SlidingArrayBuffer.prototype.isNew = function (id) {
return id > this.headID;
};
SlidingArrayBuffer.prototype.canSet = function (id) {
if (!this.initialized) {
return true;
}
return this.headID - id < this.maxSize;
};
SlidingArrayBuffer.prototype.canGet = function (id) {
if (!this.initialized) {
return false;
}
if (id < this.tailID) {
return false;
}
return id <= this.headID;
};
SlidingArrayBuffer.prototype.get = function (id) {
var idx = id % this.maxSize;
return this.buffer[idx];
};
SlidingArrayBuffer.prototype.cloneBuffer = function () {
return this.buffer.slice(0);
};
return SlidingArrayBuffer;
}());
exports.SlidingArrayBuffer = SlidingArrayBuffer;
});
define("netlib/host", ["require", "exports", "netlib/event", "netlib/message", "netlib/slidingBuffer"], function (require, exports, event_1, message_1, slidingBuffer_1) {
"use strict";
exports.__esModule = true;
var NetSimpleAddress = /** @class */ (function () {
function NetSimpleAddress(netID) {
this.netID = netID;
}
NetSimpleAddress.prototype.getID = function () {
return this.netID;
};
NetSimpleAddress.prototype.toString = function () {
return "" + this.netID;
};
return NetSimpleAddress;
}());
exports.NetSimpleAddress = NetSimpleAddress;
var NetPeerInternal = /** @class */ (function () {
function NetPeerInternal() {
// To allow other peers to detect duplicates
this.msgSeqID = 0;
// The received seqIDs from this peer, to detect duplicates
this.recvSeqIDs = new slidingBuffer_1.SlidingArrayBuffer(4096, function (idx) { return false; });
// Sequence number for reliability algorithm
this.relSeqID = 0;
// The reliable messages sent to this peer
this.relSentMsgs = new slidingBuffer_1.SlidingArrayBuffer(2048, function (idx) { return undefined; });
this.relRecvAckTailID = -1;
// The reliable messages received from this peer
this.relRecvMsgs = new slidingBuffer_1.SlidingArrayBuffer(32, function (idx) { return false; });
this.relRecvMsgsOld = new slidingBuffer_1.SlidingArrayBuffer(4096, function (idx) { return false; });
// Packets are re-ordered here
this.relRecvOrderMsgs = new slidingBuffer_1.SlidingArrayBuffer(2048, function (idx) { return undefined; });
this.relRecvOrderStartSeqID = 0;
this.relOrderSeqID = 0;
// Flag indicates if this peer was sent a reliable message this frame
this.relSent = false;
this.sendBuffer = [];
// Disconnection and timeout
this.waitingForDisconnect = false;
this.lastReceivedTimestampSet = false;
// Stats
this.rtt = 100; // milliseconds, assume 100 when peer connects
this.rttVar = 0.0;
this.dropRate = 0.0;
// Automatically assing a unique ID
this.id = NetPeerInternal.curID++;
this.setRTTSmoothingFactor(64);
}
NetPeerInternal.prototype.updateTimeout = function (timestamp) {
this.lastReceivedTimestampSet = true;
this.lastReceivedTimestamp = timestamp;
};
NetPeerInternal.prototype.hasTimedOut = function (timestamp, timeout) {
// In case we never receive a message at all, we need
// to also set this here
if (!this.lastReceivedTimestampSet) {
this.lastReceivedTimestampSet = true;
this.lastReceivedTimestamp = timestamp;
return false;
}
return timestamp - this.lastReceivedTimestamp >= timeout;
};
NetPeerInternal.prototype.updateRTT = function (rtt) {
// Exponential smoothing
this.rttVar = Math.abs(this.rtt - rtt) * this.smoothingFactor + this.rttVar * (1.0 - this.smoothingFactor);
this.rtt = rtt * this.smoothingFactor + this.rtt * (1.0 - this.smoothingFactor);
};
NetPeerInternal.prototype.getRTT = function () {
return this.rtt;
};
NetPeerInternal.prototype.getDropRate = function () {
return this.dropRate;
};
NetPeerInternal.prototype.setRTTSmoothingFactor = function (factor) {
this.smoothingFactor = 2.0 / (1.0 + factor);
};
NetPeerInternal.curID = 0;
return NetPeerInternal;
}());
///////////////////////////////////////////////////////////////////////////////
// NetHost
var NetReliableHeartbeatMessage = /** @class */ (function (_super) {
__extends(NetReliableHeartbeatMessage, _super);
function NetReliableHeartbeatMessage() {
var _this = _super.call(this, undefined) || this;
_this.type = message_1.NetMessageType.ReliableHeartbeat;
return _this;
}
return NetReliableHeartbeatMessage;
}(message_1.NetReliableMessage));
var NetDisconnectMessage = /** @class */ (function (_super) {
__extends(NetDisconnectMessage, _super);
function NetDisconnectMessage() {
var _this = _super.call(this, undefined) || this;
_this.type = message_1.NetMessageType.Disconnect;
return _this;
}
return NetDisconnectMessage;
}(message_1.NetUnreliableMessage));
var NetHost = /** @class */ (function () {
function NetHost() {
this.debug = false;
this.timeoutSeconds = 5.0;
// Mapping peers by their network ID
this.peersNetID = {};
// Mapping peers by their internal ID
this.peersID = {};
this.recvBuffer = [];
this.eventHandler = event_1.NetEventUtils.defaultHandler;
}
NetHost.prototype.getPeerByAddress = function (address) {
return this.peersNetID[address.getID()];
};
NetHost.prototype.getPeerByID = function (id) {
return this.peersID[id];
};
NetHost.prototype.acceptNewPeer = function (address) {
var newPeer = new NetPeerInternal();
newPeer.address = address;
this.peersNetID[address.getID()] = newPeer;
this.peersID[newPeer.id] = newPeer;
this.eventHandler(this, newPeer, event_1.NetEvent.ConnectionEstablished, undefined);
return newPeer;
};
NetHost.prototype.disconnectPeer = function (id) {
var peer = this.peersID[id];
if (peer != undefined && !peer.waitingForDisconnect) {
// Clear all messages for this peer, and add a
// disconnect message
peer.sendBuffer.splice(0);
// Timestamp is 0 because it doesn't matter for the Disconnect message type
this.enqueueSend(new NetDisconnectMessage(), id, 0);
peer.waitingForDisconnect = true;
}
};
NetHost.prototype.finalDisconnectPeer = function (id) {
var peer = this.peersID[id];
if (peer != undefined) {
delete this.peersNetID[peer.address.getID()];
delete this.peersID[id];
}
};
NetHost.prototype.enqueueSend = function (msg, toID, curTimestamp) {
var peer = this.peersID[toID];
if (peer == undefined || peer.waitingForDisconnect) {
return;
}
var msgType = msg.getType();
msg.seqID = peer.msgSeqID++;
if (msgType == message_1.NetMessageType.Unreliable || msgType == message_1.NetMessageType.Disconnect) {
// No extra processing required
peer.sendBuffer.push(msg.getWireForm());
}
else {
// Create a reliable message
var reliableMsg = msg;
reliableMsg.relSeqID = peer.relSeqID++;
reliableMsg.originalRelSeqID = reliableMsg.relSeqID;
if (msgType == message_1.NetMessageType.ReliableOrdered) {
var reliableOrderedMsg = msg;
reliableOrderedMsg.relOrderSeqID = peer.relOrderSeqID++;
}
// Attach our acks
reliableMsg.relRecvHeadID = peer.relRecvMsgs.getHeadID();
reliableMsg.relRecvBuffer = peer.relRecvMsgs.cloneBuffer();
// Store message
this.checkLost(peer, reliableMsg.relSeqID);
peer.relSentMsgs.set(reliableMsg.relSeqID, new message_1.NetStoredReliableMessage(reliableMsg, curTimestamp));
// Enqueue
peer.sendBuffer.push(reliableMsg.getWireForm());
peer.relSent = true;
}
};
NetHost.prototype.enqueueRecv = function (msg, from, curTimestamp) {
var peer = this.peersNetID[from.getID()];
if (peer == undefined || peer.waitingForDisconnect) {
return;
}
peer.updateTimeout(curTimestamp);
// let incomingMsg = new NetIncomingMessage(msg, peer.id);
var incomingMsg = new message_1.NetIncomingMessage(peer.id);
incomingMsg.fromWireForm(msg);
var msgType = incomingMsg.getType();
// Detect and discard duplicates
if (peer.recvSeqIDs.isNew(incomingMsg.seqID)) {
peer.recvSeqIDs.set(incomingMsg.seqID, true); // Mark as received, and continue
}
else {
if (!peer.recvSeqIDs.canGet(incomingMsg.seqID)) {
this.eventHandler(this, peer, event_1.NetEvent.DuplicatesBufferOverrun, incomingMsg);
return;
// return; // Assume that it's a duplicate message
}
else if (peer.recvSeqIDs.get(incomingMsg.seqID) == true) {
return; // This is a duplicate message, discard it
}
else {
if (peer.recvSeqIDs.canSet(incomingMsg.seqID)) {
peer.recvSeqIDs.set(incomingMsg.seqID, true); // Mark as received, and continue
}
else {
this.eventHandler(this, peer, event_1.NetEvent.DuplicatesBufferOverflow, incomingMsg);
return;
}
}
}
if (msgType == message_1.NetMessageType.Unreliable) {
// No extra processing required
this.recvBuffer.push(incomingMsg);
}
else if (msgType == message_1.NetMessageType.Disconnect) {
this.eventHandler(this, peer, event_1.NetEvent.DisconnectRecv, incomingMsg);
this.finalDisconnectPeer(peer.id);
}
else {
var reliableMsg = new message_1.NetReliableMessage(undefined);
reliableMsg.fromWireForm(msg);
var reliableDuplicate = false;
var relSeqID = reliableMsg.originalRelSeqID;
// Detect and discard duplicates
if (!peer.relRecvMsgsOld.isNew(relSeqID)) {
if (peer.relRecvMsgsOld.canGet(relSeqID)) {
if (peer.relRecvMsgsOld.get(relSeqID) == true) {
reliableDuplicate = true; // This is a duplicate message
}
}
else {
this.eventHandler(this, peer, event_1.NetEvent.DuplicatesBufferOverrun, reliableMsg);
return;
}
}
if (peer.relRecvMsgsOld.canSet(relSeqID)) {
peer.relRecvMsgsOld.set(relSeqID, true); // Mark as received
}
if (reliableDuplicate) {
// Ignore duplicate
}
else if (msgType == message_1.NetMessageType.Reliable) {
// Let it be received right away
this.recvBuffer.push(incomingMsg);
}
else if (msgType == message_1.NetMessageType.ReliableOrdered) {
// Store in queue
var reliableOrderedMsg = new message_1.NetReliableOrderedMessage(undefined);
reliableOrderedMsg.fromWireForm(msg);
if (peer.relRecvOrderMsgs.canSet(reliableOrderedMsg.relOrderSeqID)) {
peer.relRecvOrderMsgs.set(reliableOrderedMsg.relOrderSeqID, incomingMsg);
}
else {
this.eventHandler(this, peer, event_1.NetEvent.ReliableOrderedRecvBufferOverflow, reliableOrderedMsg);
return;
}
for (var seq = peer.relRecvOrderStartSeqID; seq <= peer.relRecvOrderMsgs.getHeadID(); ++seq) {
if (!peer.relRecvOrderMsgs.canGet(seq)) {
this.eventHandler(this, peer, event_1.NetEvent.ReliableOrderedRecvBufferOverrun, reliableOrderedMsg);
}
var msg_1 = peer.relRecvOrderMsgs.get(seq);
if (msg_1 == undefined) {
break;
}
this.recvBuffer.push(msg_1);
peer.relRecvOrderStartSeqID++;
}
}
else {
// Process heartbeat messages but don't store them
}
// Update our acks
if (peer.relRecvMsgs.canSet(reliableMsg.relSeqID)) {
peer.relRecvMsgs.set(reliableMsg.relSeqID, true);
}
else {
// Message is too old, just ignore
// throw "can't update acks";
}
// Process the peer's acks
var start = reliableMsg.relRecvHeadID - reliableMsg.relRecvBuffer.length + 1;
var end = reliableMsg.relRecvHeadID;
peer.relRecvAckTailID = Math.max(peer.relRecvAckTailID, start);
for (var relSeqID_1 = start; relSeqID_1 <= end; ++relSeqID_1) {
var idx = relSeqID_1 % reliableMsg.relRecvBuffer.length;
if (reliableMsg.relRecvBuffer[idx] == true) {
if (peer.relSentMsgs.canGet(relSeqID_1)) {
var stored = peer.relSentMsgs.get(relSeqID_1);
if (stored == undefined) {
// Ignore
this.eventHandler(this, peer, event_1.NetEvent.ReliableSendBufferOverrun, reliableMsg);
return;
}
else if (!stored.acked) {
// Update peer RTT
var rtt = curTimestamp - stored.sentTimestamp;
stored.rtt = rtt;
peer.updateRTT(rtt);
// Traverse the linked list of resent messages
// Mark all nodes acked
// Call onAck on the root
while (true) {
// This is the root
if (stored.resentSeqID < 0) {
// Ack callback
if (!stored.acked && stored.msg.onAck != undefined) {
stored.msg.onAck(stored.msg, peer);
}
// Mark acked
stored.acked = true;
break;
}
else {
// Mark acked
stored.acked = true;
// Get next node
if (peer.relSentMsgs.canGet(stored.resentSeqID)) {
var newStored = peer.relSentMsgs.get(stored.resentSeqID);
if (newStored == undefined) {
this.eventHandler(this, peer, event_1.NetEvent.ReliableSendBufferOverrun, reliableMsg);
return;
}
else {
stored = newStored;
}
}
else {
this.eventHandler(this, peer, event_1.NetEvent.ReliableSendBufferOverrun, reliableMsg);
return;
}
}
}
}
}
else if (relSeqID_1 >= 0) {
this.eventHandler(this, peer, event_1.NetEvent.ReliableSendBufferOverrun, reliableMsg);
return;
}
}
}
// Calculate drop rate for the past 4 seconds
start = peer.relSentMsgs.getHeadID();
end = start - peer.relSentMsgs.getMaxSize() + 1;
var timeInterval = 4000;
var threshold = peer.rtt * 1.2;
var n = 0;
var dropped = 0;
for (var seqID = start; seqID >= end; --seqID) {
if (peer.relSentMsgs.canGet(seqID)) {
var storedMsg = peer.relSentMsgs.get(seqID);
if (storedMsg != undefined) {
if (curTimestamp - storedMsg.sentTimestamp > timeInterval) {
break;
}
n++;
if (!storedMsg.acked && curTimestamp - storedMsg.sentTimestamp >= threshold) {
dropped++;
}
else if (storedMsg.acked && storedMsg.rtt >= threshold) {
dropped++;
}
}
}
}
peer.dropRate = dropped / Math.max(1, n);
}
};
NetHost.prototype.getSendBuffer = function (toID, curTimestamp) {
var peer = this.peersID[toID];
if (peer == undefined) {
return [];
}
// Check if the peer has timed out, disconnect if he has
if (peer.hasTimedOut(curTimestamp, Math.round(this.timeoutSeconds * 1000.0))) {
this.eventHandler(this, peer, event_1.NetEvent.Timeout, undefined);
this.disconnectPeer(peer.id);
}
// If the peer is scheduled for disconnection,
// disconnect him and send the disconnection message
if (peer.waitingForDisconnect) {
var ret = peer.sendBuffer.splice(0);
this.finalDisconnectPeer(peer.id);
return ret;
}
// Resend un-acked packets at the chosen rates
var start = peer.relSentMsgs.getHeadID() - peer.relSentMsgs.getMaxSize() + 1;
var end = peer.relSentMsgs.getHeadID();