-
Notifications
You must be signed in to change notification settings - Fork 37
/
data_channel.js
970 lines (895 loc) · 30.6 KB
/
data_channel.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
/**
* Manages a data channel between the two peers.
*
* A large portion (mainly, {@link createRoom}, {@link joinRoom}, {@link registerPeerConnectionListeners} and {@link collectIceCandidates} functions)
* of the code in this module is copied (or edited after copied) from the links below:
* https://github.com/webrtc/FirebaseRTC
* https://webrtc.org/getting-started/firebase-rtc-codelab
* https://webrtc.org/getting-started/data-channels
*/
'use strict';
import { initializeApp } from 'firebase/app';
import {
getFirestore,
collection,
doc,
addDoc,
setDoc,
getDocFromServer,
updateDoc,
deleteDoc,
onSnapshot,
serverTimestamp,
} from 'firebase/firestore';
import { firebaseConfig } from './firebase_config.js';
import seedrandom from 'seedrandom';
import { setCustomRng } from '../offline_version_js/rand.js';
import { mod, isInModRange } from '../utils/mod.js';
import { bufferLength, PikaUserInputWithSync } from '../keyboard_online.js';
import {
noticeDisconnected,
enableChatOpenBtnAndChatDisablingBtn,
hideWaitingPeerAssetsLoadingBox,
hidePingBox,
printAvgPing,
printStartsIn,
printLog,
printPeriodInLog,
printNotValidRoomIdMessage,
printNoRoomMatchingMessage,
printNoRoomMatchingMessageInQuickMatch,
printSomeoneElseAlreadyJoinedRoomMessage,
printConnectionFailed,
disableCancelQuickMatchBtn,
askOptionsChangeReceivedFromPeer,
noticeAgreeMessageFromPeer,
notifyBySound,
autoAskChangingToFastSpeedToPeer,
applyAutoAskChangingToFastSpeedWhenBothPeerDo,
MAX_NICKNAME_LENGTH,
} from '../ui_online.js';
import {
displayNicknameFor,
displayPartialIPFor,
} from '../nickname_display.js';
import {
setChatRngs,
displayMyChatMessage,
displayPeerChatMessage,
displayMyAndPeerChatEnabledOrDisabled,
} from '../chat_display.js';
import { rtcConfiguration } from './rtc_configuration.js';
import { parsePublicIPFromCandidate, getPartialIP } from './parse_candidate.js';
import {
convertUserInputTo5bitNumber,
convert5bitNumberToUserInput,
} from '../utils/input_conversion.js';
import {
sendQuickMatchSuccessMessageToServer,
sendWithFriendSuccessMessageToServer,
} from '../quick_match/quick_match.js';
import { replaySaver } from '../replay/replay_saver.js';
/** @typedef {{speed: string, winningScore: number}} Options */
const firebaseApp = initializeApp(firebaseConfig);
// It is set to (1 << 16) since syncCounter is to be sent as Uint16
// 1 << 16 === 65536 and it corresponds to about 36 minutes of syncCounter
// wrap-around time in 30 FPS (fast game speed).
export const SYNC_DIVISOR = 1 << 16; // 65536
export const channel = {
isOpen: false,
gameStartAllowed: false,
amICreatedRoom: false,
amIPlayer2: null, // set from pikavolley_online.js
isQuickMatch: null, // set from ui_online.js
myNickname: '', // set from ui_online.js
peerNickname: '',
myPartialPublicIP: '*.*.*.*',
peerPartialPublicIP: '*.*.*.*',
myChatEnabled: true,
peerChatEnabled: true,
willAskFastAutomatically: false,
/** @type {PikaUserInputWithSync[]} */
peerInputQueue: [],
_peerInputQueueSyncCounter: 0,
get peerInputQueueSyncCounter() {
return this._peerInputQueueSyncCounter;
},
set peerInputQueueSyncCounter(counter) {
this._peerInputQueueSyncCounter = mod(counter, SYNC_DIVISOR);
},
callbackAfterDataChannelOpened: null,
callbackAfterDataChannelOpenedForUI: null,
callbackAfterPeerInputQueueReceived: null,
};
const pingTestManager = {
pingSentTimeArray: new Array(5),
receivedPingResponseNumber: 0,
pingMesurementArray: [],
};
/**
* Return a message sync manager
* @param {number} offset syncCounter offset (even number)
*/
function createMessageSyncManager(offset) {
return {
pendingMessage: '',
resendIntervalID: null,
_syncCounter: offset,
_peerSyncCounter: offset + ((offset + 1) % 2),
get syncCounter() {
return this._syncCounter;
},
set syncCounter(n) {
this._syncCounter = offset + (n % 2);
},
get peerSyncCounter() {
return this._peerSyncCounter;
},
set peerSyncCounter(n) {
this._peerSyncCounter = offset + (n % 2);
},
get nextPeerSyncCounter() {
return offset + ((this._peerSyncCounter + 1) % 2);
},
};
}
const chatManager = createMessageSyncManager(0); // use 0, 1 for syncCounter
const optionsChangeManager = createMessageSyncManager(2); // use 2, 3 for syncCounter
const optionsChangeAgreeManager = createMessageSyncManager(4); // use 4, 5 for syncCounter
const chatEnabledManager = createMessageSyncManager(6); // use 6, 7 for syncCounter
let peerConnection = null;
let dataChannel = null;
let roomId = null;
let roomRef = null;
const localICECandDocRefs = [];
let roomSnapshotUnsubscribe = null;
let iceCandOnSnapshotUnsubscribe = null;
let isDataChannelEverOpened = false;
let isFirstInputQueueFromPeer = true;
// first chat message is used for nickname transmission
let isFirstChatMessageToPeerUsedForNickname = true;
let isFirstChatMessageFromPeerUsedForNickname = true;
let isAutoAskingFastWhenBothPeerDoApplied = false;
/**
* Create a room
* @param {string} roomIdToCreate
*/
export async function createRoom(roomIdToCreate) {
channel.amICreatedRoom = true;
roomId = roomIdToCreate;
const db = getFirestore(firebaseApp);
roomRef = doc(db, 'rooms', roomId);
console.log('Create PeerConnection with configuration: ', rtcConfiguration);
peerConnection = new RTCPeerConnection(rtcConfiguration);
registerPeerConnectionListeners(peerConnection);
collectIceCandidates(
roomRef,
peerConnection,
'offerorCandidates',
'answererCandidates'
);
// Create an unreliable and unordered data channel, which is UDP-like channel.
//
// An reliable and ordered data channel can be used but,
// even if a reliable channel is used, the sync is broken somehow after one of the peer,
// for example, stops the game a while by minimizing the browser window.
// So, I decided to manage the transmission reliability on the application layer.
//
// SYNC_DIVISOR is 1 << 16 === 65536 and it corresponds to about 36 minutes of
// syncCounter wrap-around time in 30 FPS (fast game speed).
// This 36 minutes of wrap-around time, I think, is practically very safe
// since no packet would live hanging around more than 36 minutes in
// the network. (The maximum possible value for IPv4 TTL (or IPv6 Hop Limit)
// field is 255. If we generously assume 1 second per 1 hop, it would be
// 255 seconds which is just 4.25 minutes.) So, after a wrap-around has
// occurred, an old packet with the same syncCounter value would not survive
// and hence would not be erroneously accepted instead of a new packet.
//
// references:
// https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createDataChannel
// https://www.w3.org/TR/webrtc/#rtcpeerconnection-interface-extensions-0
// https://www.w3.org/TR/webrtc/#methods-11
// https://www.w3.org/TR/webrtc/#rtcdatachannel
// https://www.w3.org/TR/webrtc/#dictionary-rtcdatachannelinit-members
// https://www.w3.org/TR/webrtc/#bib-rtcweb-data
// https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-13#section-6.1
dataChannel = peerConnection.createDataChannel('pikavolley_p2p_channel', {
ordered: false,
maxRetransmits: 0,
});
console.log('Created data channel', dataChannel);
dataChannel.addEventListener('open', dataChannelOpened);
dataChannel.addEventListener('message', recieveFromPeer);
dataChannel.addEventListener('close', dataChannelClosed);
roomSnapshotUnsubscribe = onSnapshot(roomRef, async (snapshot) => {
console.log('Got updated room:', snapshot.data());
const data = snapshot.data();
if (!peerConnection.currentRemoteDescription && data.answer) {
printLog('Answer received');
console.log('Set remote description');
const answer = data.answer;
await peerConnection.setRemoteDescription(answer);
roomSnapshotUnsubscribe();
roomSnapshotUnsubscribe = null;
}
});
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
console.log('Created offer and set local description:', offer);
const roomWithOffer = {
timestamp: serverTimestamp(),
offer: {
type: offer.type,
sdp: offer.sdp,
},
};
await setDoc(roomRef, roomWithOffer);
console.log(`New room created with SDP offer. Room ID: ${roomRef.id}`);
printLog('Offer sent');
}
/**
* Join the room
* @param {string} roomIdToJoin
*/
export async function joinRoom(roomIdToJoin) {
roomId = roomIdToJoin;
if (roomId.length !== 20) {
printNotValidRoomIdMessage();
return false;
}
console.log('Join room: ', roomId);
const db = getFirestore(firebaseApp);
const roomRef = doc(db, 'rooms', `${roomId}`);
const roomSnapshot = await getDocFromServer(roomRef);
const doesRoomExist = roomSnapshot.exists();
console.log('Got room:', doesRoomExist);
if (!doesRoomExist) {
console.log('No room is mathing the ID');
if (channel.isQuickMatch) {
printNoRoomMatchingMessageInQuickMatch();
printConnectionFailed();
} else {
printNoRoomMatchingMessage();
}
return false;
}
const data = roomSnapshot.data();
if (data.answer) {
console.log('The room is already joined by someone else');
printSomeoneElseAlreadyJoinedRoomMessage();
return false;
}
console.log('Create PeerConnection with configuration: ', rtcConfiguration);
peerConnection = new RTCPeerConnection(rtcConfiguration);
registerPeerConnectionListeners(peerConnection);
// Code for collecting ICE candidates below
collectIceCandidates(
roomRef,
peerConnection,
'answererCandidates',
'offerorCandidates'
);
// Code for creating SDP answer below
const offer = data.offer;
await peerConnection.setRemoteDescription(offer);
console.log('Set remote description');
printLog('Offer received');
const answer = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(answer);
console.log('set local description:', answer);
const roomWithAnswer = {
answer: {
type: answer.type,
sdp: answer.sdp,
},
};
await updateDoc(roomRef, roomWithAnswer);
printLog('Answer sent');
console.log('joined room!');
return true;
}
/**
* Clean up the relevants of Cloud Firestore.
*/
export function cleanUpFirestoreRelevants() {
if (roomSnapshotUnsubscribe) {
roomSnapshotUnsubscribe();
roomSnapshotUnsubscribe = null;
}
if (iceCandOnSnapshotUnsubscribe) {
iceCandOnSnapshotUnsubscribe();
iceCandOnSnapshotUnsubscribe = null;
}
// Delete ice candidates documents
while (localICECandDocRefs.length > 0) {
deleteDoc(localICECandDocRefs.pop()).then(() => {
console.log('deleted an ICE candidate doc');
});
}
// Delete the room document
if (channel.amICreatedRoom && roomRef) {
deleteDoc(roomRef).then(() => {
console.log('deleted the room');
});
roomRef = null;
}
}
export function closeConnection() {
if (dataChannel) {
dataChannel.close();
}
if (peerConnection) {
peerConnection.close();
}
console.log('Did close data channel and peer connection');
}
/**
* Send my input queue to the peer.
*
* Input is transmitted by 5 bits (so fit in 1 byte = 8 bits).
* Refer: {@link convertUserInputTo5bitNumber}
*
* @param {PikaUserInputWithSync[]} inputQueue
*/
export function sendInputQueueToPeer(inputQueue) {
const buffer = new ArrayBuffer(2 + inputQueue.length);
const dataView = new DataView(buffer);
dataView.setUint16(0, inputQueue[0].syncCounter, true);
for (let i = 0; i < inputQueue.length; i++) {
const input = inputQueue[i];
const byte = convertUserInputTo5bitNumber(input);
dataView.setUint8(2 + i, byte);
}
dataChannel.send(buffer);
}
/**
* Receive peer's input queue from the peer
* @param {ArrayBuffer} data
*/
function receiveInputQueueFromPeer(data) {
if (isFirstInputQueueFromPeer) {
isFirstInputQueueFromPeer = false;
hideWaitingPeerAssetsLoadingBox();
}
const dataView = new DataView(data);
const syncCounter0 = dataView.getUint16(0, true);
for (let i = 0; i < data.byteLength - 2; i++) {
const syncCounter = mod(syncCounter0 + i, SYNC_DIVISOR);
// isInModeRange in the below if statement is
// to prevent overflow of the queue by a corrupted peer code
if (
syncCounter === channel.peerInputQueueSyncCounter &&
(channel.peerInputQueue.length === 0 ||
isInModRange(
syncCounter,
channel.peerInputQueue[0].syncCounter,
channel.peerInputQueue[0].syncCounter + 2 * bufferLength - 1,
SYNC_DIVISOR
))
) {
const byte = dataView.getUint8(2 + i);
const input = convert5bitNumberToUserInput(byte);
const peerInputWithSync = new PikaUserInputWithSync(
syncCounter,
input.xDirection,
input.yDirection,
input.powerHit
);
channel.peerInputQueue.push(peerInputWithSync);
channel.peerInputQueueSyncCounter++;
}
}
}
/**
* Send chat message to the peer
* @param {string} chatMessage
*/
export function sendChatMessageToPeer(chatMessage) {
chatManager.pendingMessage = chatMessage;
// append syncCounter at the end of chat message;
const chatMessageToPeer = chatMessage + String(chatManager.syncCounter);
dataChannel.send(chatMessageToPeer);
chatManager.resendIntervalID = setInterval(
() => dataChannel.send(chatMessageToPeer),
1000
);
return;
}
/**
* Receive chat message ACK(acknowledgment) array buffer from peer.
* @param {ArrayBuffer} data array buffer with length 1
*/
function receiveChatMessageAckFromPeer(data) {
const dataView = new DataView(data);
const syncCounter = dataView.getInt8(0);
if (syncCounter === chatManager.syncCounter) {
chatManager.syncCounter++;
clearInterval(chatManager.resendIntervalID);
if (isFirstChatMessageToPeerUsedForNickname) {
isFirstChatMessageToPeerUsedForNickname = false;
} else {
displayMyChatMessage(chatManager.pendingMessage);
enableChatOpenBtnAndChatDisablingBtn();
}
}
}
/**
* Receive chat meesage from the peer
* @param {string} chatMessage
*/
function receiveChatMessageFromPeer(chatMessage) {
// Read syncCounter at the end of chat message
const peerSyncCounter = Number(chatMessage.slice(-1));
if (peerSyncCounter === chatManager.peerSyncCounter) {
// if peer resend prevMessage since peer did not recieve
// the message ACK(acknowledgment) array buffer with length 1
console.log('arraybuffer with length 1 for chat message ACK resent');
} else if (peerSyncCounter === chatManager.nextPeerSyncCounter) {
// if peer send new message
chatManager.peerSyncCounter++;
if (isFirstChatMessageFromPeerUsedForNickname) {
isFirstChatMessageFromPeerUsedForNickname = false;
channel.peerNickname = chatMessage
.slice(0, -1)
.trim()
.slice(0, MAX_NICKNAME_LENGTH);
displayNicknameFor(channel.peerNickname, channel.amICreatedRoom);
displayNicknameFor(channel.myNickname, !channel.amICreatedRoom);
displayPartialIPFor(channel.peerPartialPublicIP, channel.amICreatedRoom);
displayPartialIPFor(channel.myPartialPublicIP, !channel.amICreatedRoom);
if (channel.amICreatedRoom) {
replaySaver.recordNicknames(channel.myNickname, channel.peerNickname);
replaySaver.recordPartialPublicIPs(
channel.myPartialPublicIP,
channel.peerPartialPublicIP
);
} else {
replaySaver.recordNicknames(channel.peerNickname, channel.myNickname);
replaySaver.recordPartialPublicIPs(
channel.peerPartialPublicIP,
channel.myPartialPublicIP
);
}
} else {
displayPeerChatMessage(chatMessage.slice(0, -1));
}
} else {
console.log('invalid chat message received.');
return;
}
// Send the message ACK array buffer with length 1.
const buffer = new ArrayBuffer(1);
const dataView = new DataView(buffer);
dataView.setInt8(0, peerSyncCounter);
dataChannel.send(buffer);
}
/**
* Send options change message to peer
*
* speed: one of 'slow', 'medium', 'fast', null
* winningScore: one of 5, 10, 15, null
* @param {Options} options
*/
export function sendOptionsChangeMessageToPeer(options) {
if (!options.speed && !options.winningScore) {
return;
}
let optionsChangeMessageToPeer = JSON.stringify(options);
// append syncCounter at the end of options change message;
optionsChangeMessageToPeer += String(optionsChangeManager.syncCounter);
dataChannel.send(optionsChangeMessageToPeer);
optionsChangeManager.resendIntervalID = setInterval(
() => dataChannel.send(optionsChangeMessageToPeer),
1000
);
return;
}
/**
* Receive options change message ACK(acknowledgment) array buffer from peer.
* @param {ArrayBuffer} data array buffer with length 1
*/
function receiveOptionsChangeMessageAckFromPeer(data) {
const dataView = new DataView(data);
const syncCounter = dataView.getInt8(0);
if (syncCounter === optionsChangeManager.syncCounter) {
optionsChangeManager.syncCounter++;
clearInterval(optionsChangeManager.resendIntervalID);
}
}
/**
* Receive options change meesage from the peer
* @param {string} optionsChangeMessage
*/
function receiveOptionsChangeMessageFromPeer(optionsChangeMessage) {
// Read syncCounter at the end of options change message
const peerSyncCounter = Number(optionsChangeMessage.slice(-1));
if (peerSyncCounter === optionsChangeManager.peerSyncCounter) {
// if peer resend prevMessage since peer did not recieve
// the message ACK(acknowledgment) array buffer with length 1
console.log(
'arraybuffer with length 1 for options change message ACK resent'
);
} else if (peerSyncCounter === optionsChangeManager.nextPeerSyncCounter) {
// if peer send new message
optionsChangeManager.peerSyncCounter++;
const options = JSON.parse(optionsChangeMessage.slice(0, -1));
if (
options.auto &&
options.speed === 'fast' &&
channel.willAskFastAutomatically
) {
applyAutoAskChangingToFastSpeedWhenBothPeerDo();
isAutoAskingFastWhenBothPeerDoApplied = true;
return;
}
askOptionsChangeReceivedFromPeer(options);
} else {
console.log('invalid options change message received.');
return;
}
// Send the message ACK array buffer with length 1.
const buffer = new ArrayBuffer(1);
const dataView = new DataView(buffer);
dataView.setInt8(0, peerSyncCounter);
dataChannel.send(buffer);
}
/**
* Send options change agree/disagree message to peer
* @param {boolean} agree agree (true) or disagree (false)
*/
export function sendOptionsChangeAgreeMessageToPeer(agree) {
let agreeMessageToPeer = String(agree);
agreeMessageToPeer += String(optionsChangeAgreeManager.syncCounter);
dataChannel.send(agreeMessageToPeer);
optionsChangeAgreeManager.resendIntervalID = setInterval(
() => dataChannel.send(agreeMessageToPeer),
1000
);
return;
}
/**
* Receive options change agree message ACK(acknowledgment) array buffer from peer.
* @param {ArrayBuffer} data array buffer with length 1
*/
function receiveOptionsChangeAgreeMessageAckFromPeer(data) {
const dataView = new DataView(data);
const syncCounter = dataView.getInt8(0);
if (syncCounter === optionsChangeAgreeManager.syncCounter) {
optionsChangeAgreeManager.syncCounter++;
clearInterval(optionsChangeAgreeManager.resendIntervalID);
}
}
/**
* Receive options change meesage from the peer
* @param {string} optionsChangeAgreeMessage
*/
function receiveOptionsChangeAgreeMessageFromPeer(optionsChangeAgreeMessage) {
// Read syncCounter at the end of options change agree message
const peerSyncCounter = Number(optionsChangeAgreeMessage.slice(-1));
if (peerSyncCounter === optionsChangeAgreeManager.peerSyncCounter) {
// if peer resend prevMessage since peer did not recieve
// the message ACK(acknowledgment) array buffer with length 1
console.log(
'arraybuffer with length 1 for options change message ACK resent'
);
} else if (
peerSyncCounter === optionsChangeAgreeManager.nextPeerSyncCounter
) {
// if peer send new message
optionsChangeAgreeManager.peerSyncCounter++;
const agree = optionsChangeAgreeMessage.slice(0, -1) === 'true';
noticeAgreeMessageFromPeer(agree);
} else {
console.log('invalid options change message received.');
return;
}
// Send the message ACK array buffer with length 1.
const buffer = new ArrayBuffer(1);
const dataView = new DataView(buffer);
dataView.setInt8(0, peerSyncCounter);
dataChannel.send(buffer);
}
/**
* Send chat enabled/disabled message to peer
* @param {boolean} enabled true or false
*/
export function sendChatEnabledMessageToPeer(enabled) {
let enabledMessageToPeer = String(enabled);
enabledMessageToPeer += String(chatEnabledManager.syncCounter);
dataChannel.send(enabledMessageToPeer);
chatEnabledManager.resendIntervalID = setInterval(
() => dataChannel.send(enabledMessageToPeer),
1000
);
return;
}
/**
* Receive chat enabled/disabled message ACK(acknowledgment) array buffer from peer.
* @param {ArrayBuffer} data array buffer with length 1
*/
function receiveChatEnabledMessageAckFromPeer(data) {
const dataView = new DataView(data);
const syncCounter = dataView.getInt8(0);
if (syncCounter === chatEnabledManager.syncCounter) {
chatEnabledManager.syncCounter++;
clearInterval(chatEnabledManager.resendIntervalID);
}
}
/**
* Receive hat enabled/disabled meesage from the peer
* @param {string} chatEnabledMessage
*/
function receiveChatEnabledMessageFromPeer(chatEnabledMessage) {
// Read syncCounter at the end of chat enabled/disabled message
const peerSyncCounter = Number(chatEnabledMessage.slice(-1));
if (peerSyncCounter === chatEnabledManager.peerSyncCounter) {
// if peer resend prevMessage since peer did not recieve
// the message ACK(acknowledgment) array buffer with length 1
console.log(
'arraybuffer with length 1 for chat enabled/disabled message ACK resent'
);
} else if (peerSyncCounter === chatEnabledManager.nextPeerSyncCounter) {
// if peer send new message
chatEnabledManager.peerSyncCounter++;
const chatEnabled = chatEnabledMessage.slice(0, -1) === 'true';
channel.peerChatEnabled = chatEnabled;
displayMyAndPeerChatEnabledOrDisabled();
} else {
console.log('invalid chat enabled/disabled message received.');
return;
}
// Send the message ACK array buffer with length 1.
const buffer = new ArrayBuffer(1);
const dataView = new DataView(buffer);
dataView.setInt8(0, peerSyncCounter);
dataChannel.send(buffer);
}
/**
* Test average ping by sending ping test arraybuffers, then start the game
*/
function startGameAfterPingTest() {
// Send my nick name to peer
sendChatMessageToPeer(channel.myNickname);
if (channel.willAskFastAutomatically) {
autoAskChangingToFastSpeedToPeer(!isAutoAskingFastWhenBothPeerDoApplied);
}
printLog('start ping test');
const buffer = new ArrayBuffer(1);
const view = new DataView(buffer);
view.setInt8(0, -1);
let n = 0;
const intervalID = setInterval(() => {
if (n === 5) {
window.clearInterval(intervalID);
const sum = pingTestManager.pingMesurementArray.reduce(
(acc, val) => acc + val,
0
);
const avg = sum / pingTestManager.pingMesurementArray.length;
console.log(
`average ping: ${avg} ms, ping list: ${pingTestManager.pingMesurementArray}`
);
channel.callbackAfterDataChannelOpened();
channel.callbackAfterDataChannelOpenedForUI();
printAvgPing(avg);
let t = 10;
printStartsIn(t);
const intervalID2 = setInterval(() => {
t--;
printStartsIn(t);
if (t === 0) {
window.clearInterval(intervalID2);
hidePingBox();
channel.gameStartAllowed = true;
return;
}
}, 1000);
return;
}
pingTestManager.pingSentTimeArray[n] = Date.now();
dataChannel.send(buffer);
printPeriodInLog();
n++;
}, 1000);
}
/**
* Respond to received ping test array buffer.
* @param {ArrayBuffer} data array buffer with length 1
*/
function respondToPingTest(data) {
const dataView = new DataView(data);
if (dataView.getInt8(0) === -1) {
const buffer = new ArrayBuffer(1);
const view = new DataView(buffer);
view.setInt8(0, -2);
console.log('respond to ping');
dataChannel.send(buffer);
} else if (dataView.getInt8(0) === -2) {
pingTestManager.pingMesurementArray.push(
Date.now() -
pingTestManager.pingSentTimeArray[
pingTestManager.receivedPingResponseNumber
]
);
pingTestManager.receivedPingResponseNumber++;
}
}
/**
* Event handler for the message event (which has data received from the peer) of data channel
* @param {MessageEvent} event
*/
function recieveFromPeer(event) {
const data = event.data;
if (data instanceof ArrayBuffer) {
if (data.byteLength > 2 && data.byteLength <= 2 + 2 * bufferLength) {
receiveInputQueueFromPeer(data);
if (channel.callbackAfterPeerInputQueueReceived !== null) {
const callback = channel.callbackAfterPeerInputQueueReceived;
channel.callbackAfterPeerInputQueueReceived = null;
window.setTimeout(callback, 0);
}
} else if (data.byteLength === 1) {
const view = new DataView(data);
const value = view.getInt8(0);
if (value >= 6) {
receiveChatEnabledMessageAckFromPeer(data);
} else if (value >= 4) {
receiveOptionsChangeAgreeMessageAckFromPeer(data);
} else if (value >= 2) {
receiveOptionsChangeMessageAckFromPeer(data);
} else if (value >= 0) {
receiveChatMessageAckFromPeer(data);
} else if (value < 0) {
respondToPingTest(data);
}
}
} else if (typeof data === 'string') {
const syncCounter = Number(data.slice(-1));
if (syncCounter >= 6) {
receiveChatEnabledMessageFromPeer(data);
} else if (syncCounter >= 4) {
receiveOptionsChangeAgreeMessageFromPeer(data);
} else if (syncCounter >= 2) {
receiveOptionsChangeMessageFromPeer(data);
} else if (syncCounter >= 0) {
receiveChatMessageFromPeer(data);
}
}
}
/**
* Data channel open event listener
*/
function dataChannelOpened() {
printLog('data channel opened!');
console.log('data channel opened!');
console.log(`dataChannel.ordered: ${dataChannel.ordered}`);
console.log(`dataChannel.maxRetransmits: ${dataChannel.maxRetransmits}`);
dataChannel.binaryType = 'arraybuffer';
channel.isOpen = true;
isDataChannelEverOpened = true;
notifyBySound();
cleanUpFirestoreRelevants();
if (channel.isQuickMatch) {
disableCancelQuickMatchBtn();
}
if (channel.amICreatedRoom) {
if (channel.isQuickMatch) {
sendQuickMatchSuccessMessageToServer();
} else {
sendWithFriendSuccessMessageToServer();
}
}
// record roomId for RNG in replay
replaySaver.recordRoomID(roomId);
// Set the same RNG (used for the game) for both peers
const customRng = seedrandom.alea(roomId.slice(10));
setCustomRng(customRng);
// Set the same RNG (used for displaying chat messages) for both peers
const rngForPlayer1Chat = seedrandom.alea(roomId.slice(10, 15));
const rngForPlayer2Chat = seedrandom.alea(roomId.slice(15));
setChatRngs(rngForPlayer1Chat, rngForPlayer2Chat);
startGameAfterPingTest();
}
/**
* Data channel close event listener
*/
function dataChannelClosed() {
console.log('data channel closed');
channel.isOpen = false;
noticeDisconnected();
}
function registerPeerConnectionListeners(peerConnection) {
peerConnection.addEventListener('icegatheringstatechange', () => {
console.log(
`ICE gathering state changed: ${peerConnection.iceGatheringState}`
);
printLog(
`ICE gathering state changed: ${peerConnection.iceGatheringState}`
);
});
peerConnection.addEventListener('connectionstatechange', () => {
console.log(`Connection state change: ${peerConnection.connectionState}`);
printLog(`Connection state change: ${peerConnection.connectionState}`);
if (
peerConnection.connectionState === 'disconnected' ||
peerConnection.connectionState === 'closed'
) {
channel.isOpen = false;
noticeDisconnected();
}
if (
peerConnection.connectionState === 'failed' &&
isDataChannelEverOpened === false
) {
notifyBySound();
printConnectionFailed();
}
});
peerConnection.addEventListener('signalingstatechange', () => {
console.log(`Signaling state change: ${peerConnection.signalingState}`);
printLog(`Signaling state change: ${peerConnection.signalingState}`);
});
peerConnection.addEventListener('iceconnectionstatechange ', () => {
console.log(
`ICE connection state change: ${peerConnection.iceConnectionState}`
);
printLog(
`ICE connection state change: ${peerConnection.iceConnectionState}`
);
});
peerConnection.addEventListener('datachannel', (event) => {
dataChannel = event.channel;
console.log('data channel received!', dataChannel);
printLog('data channel received!');
dataChannel.addEventListener('open', dataChannelOpened);
dataChannel.addEventListener('message', recieveFromPeer);
dataChannel.addEventListener('close', dataChannelClosed);
});
}
function collectIceCandidates(roomRef, peerConnection, localName, remoteName) {
const candidatesCollection = collection(roomRef, localName);
peerConnection.addEventListener('icecandidate', (event) => {
if (!event.candidate) {
console.log('Got final candidate!');
return;
}
const json = event.candidate.toJSON();
addDoc(candidatesCollection, json).then((ref) =>
localICECandDocRefs.push(ref)
);
console.log('Got candidate: ', event.candidate);
if (event.candidate.candidate === '') {
// This if statement is for Firefox browser.
return;
}
const myPublicIP = parsePublicIPFromCandidate(event.candidate.candidate);
if (myPublicIP !== null) {
channel.myPartialPublicIP = getPartialIP(myPublicIP);
console.log('part of my public IP address:', channel.myPartialPublicIP);
}
});
iceCandOnSnapshotUnsubscribe = onSnapshot(
collection(roomRef, remoteName),
(snapshot) => {
snapshot.docChanges().forEach(async (change) => {
if (change.type === 'added') {
const data = change.doc.data();
await peerConnection.addIceCandidate(data);
console.log('Got new remote ICE candidate');
if (data.candidate === '') {
// This if statement is for Firefox browser.
return;
}
const peerPublicIP = parsePublicIPFromCandidate(data.candidate);
if (peerPublicIP !== null) {
channel.peerPartialPublicIP = getPartialIP(peerPublicIP);
console.log(
"part of the peer's public IP address:",
channel.peerPartialPublicIP
);
}
}
});
}
);
}