-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.js
624 lines (473 loc) · 17.2 KB
/
Client.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
/**
* Copyright (c) 2012 Ivo Wetzel.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*global Class, Twist, BISON, MozWebSocket, Maple */
/**
* {Maple.Client} A game client for synced multiplayer games.
*
* Maple is uses a tick based approach to syncing, it also handles client
* side frame rate management.
*
* Params: @update {Integer} and @render {Integer} frame rates.
*/
Maple.Client = Class(function(update, render) {
Twist(this, update, render);
this._socket = null;
this._tickRate = 0;
this._tickCount = 0;
this._tickSyncTime = -1;
this._baseTick = 0;
this._serverTick = 0;
this._lastTick = 0;
this._syncRate = 0;
this._logicRate = 0;
this._randomSeed = 0;
this._randomState = 0;
this._isBinary = false;
this._messageQueue = [];
this._messageUid = 0;
this._messageArray = [0, 0];
this._messageTypes = [];
this._ping = 0;
this._lastPingTime = -2000;
this._pingInterval = 500;
}, Twist, {
$version: '0.2',
/**
* {Boolean|Null} Connects with the Maple server at (@host {String} : @port {Number})
*
* Returns `false` in the case that there is already an open connection.
* Returns `null` in the case that WebSockets aren't supported.
*/
connect: function(host, port) {
if (this.isConnected()) {
return false;
}
// Figure out which object to use
var ws = typeof WebSocket !== 'undefined' ? WebSocket : MozWebSocket;
// Setup the socket
// If the connection get's rejected, this won't throw but instead
// call `onclose()`
try {
this._socket = new ws('ws://' + host + (port !== undefined ? ':' + port : ''));
this._isBinary = typeof ArrayBuffer !== 'undefined' && typeof this._socket.binaryType !== 'undefined';
if (this._isBinary) {
this._socket.binaryType = 'arraybuffer';
}
} catch(e) {
return null;
}
// Setup event handlers, also send intial message
var that = this;
this._socket.onopen = function() {
that.send(Maple.Message.CONNECT, [Maple.Client.$version, that._isBinary]);
};
this._socket.onmessage = function(msg) {
var data = msg.data;
if (msg.data instanceof ArrayBuffer) {
var bytes = new Uint8Array(msg.data);
data = String.fromCharCode.apply(null, bytes);
}
that._message(BISON.decode(data), true);
};
this._socket.onclose = function(msg) {
that.closed(!msg.wasClean, msg.code);
that._stop();
};
return true;
},
/**
* {Boolean} Disconnects the client from the Maple server its currently connected to.
*
* Returns `false` in case there is no server to disconnect from.
*/
disconnect: function() {
if (!this.isConnected()) {
return false;
} else {
this._socket.close();
this._socket = null;
return true;
}
},
/**
* {Boolean} Whether the client is currently connected to any server or not.
*/
isConnected: function() {
return !!this._socket;
},
/**
* Sends a @data {Array} to the server, @type {Number}.
*/
send: function(type, data) {
// Add type and tick to the message
this._messageArray.length = 2;
this._messageArray[0] = this.messageTypeToId(type);
this._messageArray[1] = this.getTick();
if (data !== undefined) {
this.log(data);
this._messageArray.push.apply(this._messageArray, data);
}
// Make the message as small as possible and send it
var encoded = BISON.encode(this._messageArray);
if (this._isBinary) {
var len = encoded.length,
bytes = new Uint8Array(len);
for(var i = 0; i < len; i++) {
bytes[i] = encoded.charCodeAt(i);
}
encoded = bytes.buffer;
}
this._socket.send(encoded);
},
// Internal handling of synced update / rendering -------------------------
_update: function() {
// Grab current values
var t = this.getTime(),
tick = this.getTick();
// Calculate passed difference in frames since last tick
var ct = 0,
diff = tick - this._lastTick,
lt = this._lastTick || 0;
// Run through all frames, calculate the intermediate tick
// and check for logic ticks
while(ct < diff) {
tick = lt + ct;
if (tick > this._lastTick && tick % this._logicRate === 0) {
// Check all messages in the queue to see whether we've
// got some for this tick
this._processMessageQueue();
// Re-seed random generator
this._randomState = tick;
this.update((tick * this._tickRate) - this._tickRate, tick);
this._lastTick = tick;
}
ct++;
}
// Send out a ping
var realTime = Twist.getTime(this, true);
if (realTime - this._lastPingTime >= this._pingInterval) {
this.send(Maple.Message.PING, [realTime, this._ping]);
this._lastPingTime = realTime;
this._pingInterval = Math.min(this._pingInterval + 500, 8000);
}
},
_stop: function() {
this._messageTypes = [];
this._socket = null;
Twist.stop(this);
this.stopped();
},
_render: function(t, dt, u) {
this.render(this.getTime(), this.getTick(), dt, u);
},
_message: function(msg, initial, flush) {
// Sync message consists of one plain Integer being send by the server
// The int is one byte and wraps around every 250 ticks.
if (typeof msg === 'number') {
var diff = msg - this._serverTick;
// Wrap around and increase base by 250
if (diff < 0) {
this._baseTick++;
}
this._serverTick = msg;
this._tickSyncTime = Date.now();
this._tickCount = this._baseTick * 250 + msg;
return false;
}
// Real messages (not protocol releated)
var type = msg[0],
tick = msg[1],
data = msg.slice(2);
// Handle basic message which are not synced with tick counts
// But only handle these ONCE.
// _message will be called again for all messages left in the queue
// so in case something is supposed to be synced, we don't want to
// invoke the normal handling all the time
var ret = false;
if (initial) {
ret = this._handleMessage(type, tick, data);
}
if (ret === false) {
// Messages which need to be in sync with the tick count
// these will be processed right before the next game tick
if (!flush && tick > 0 && tick > this._lastTick) {
if (initial) {
msg.uid = ++this._messageUid;
this._messageQueue.push(msg);
}
} else {
// this always returns true for now
ret = this._handleSyncedMessage(type, tick, data);
}
}
return ret;
},
/**
* Handle messages which aren't bound to a given tick.
*/
_handleMessage: function(type, tick, data) {
switch(type) {
case Maple.Message.START:
this._tickRate = data[0];
this._logicRate = data[1];
this._syncRate = data[2];
this._randomSeed = data[3];
this._messageTypes = data[4];
this._serverTick = 0;
this._baseTick = Math.floor(tick / 250);
this._tickSyncTime = Date.now();
this._tickCount = tick;
this._lastTick = this._tickCount;
// Start game loop
Twist.start(this);
this.started();
break;
case Maple.Message.ERROR:
this.error(data[0]);
break;
case Maple.Message.PONG:
this._ping = Math.ceil((Twist.getTime(this, true) - data[0]) / 2);
break;
default:
return this.message(this.messageTypeFromId(type), tick, data) || false;
}
// Return true in case we handled the message
return true;
},
/**
* Handles basic synced messages directly implements by Maple.
*
* Synced messages are messages which need to be handled at the exact
* tick count they were send off at the server.
*/
_handleSyncedMessage: function(type, tick, data) {
switch(type) {
case Maple.Message.STOP:
this._stop();
return true;
}
this.syncedMessage(this.messageTypeFromId(type), tick, data);
return true;
},
/**
* Walk through all pending messages. This ensures that they're always
* handled with the gametick they were send off at the server.
*/
_processMessageQueue: function(flush) {
// Sort messaged based on UID to ensure correct order
this._messageQueue.sort(function(a, b) {
return a.uid - b.uid;
});
for(var i = 0; i < this._messageQueue.length; i++) {
if (this._message(this._messageQueue[i], false, flush)) {
this._messageQueue.splice(i, 1);
i--;
}
}
},
// Abstract Game Methods --------------------------------------------------
/**
* Callback for when the "game" is started.
*/
started: function() {
},
/**
* The update game callback.
*
* - @t {Integer} is the current game time.
* - @tick {Integer} is the current tick count.
*/
update: function(t, tick) {
},
/**
* The game render callback.
*
* - @t {Integer} is the current render time,
* - @tick {Integer} is the current tick count,
* - @dt {Integer} the time passed since the last call to {Maple.Client#update} and @u {Float} is a represensation of @dt in the range of `0...1`
*/
render: function(t, tick, dt, u) {
},
/**
* Callback for when the "game" is stopped.
*/
stopped: function() {
},
// Abstract Network Methods -----------------------------------------------
/**
* The callback for when the connection to the server is intially established.
*
* Note: This is not the same as the `onopen` callback of the WebSocket.
* This actually means that the server acknowledged us.
*/
connected: function() {
},
/**
* {Boolean} Callback for any messages received from the server.
*
* Due to the nature of the network, messages may arrive "Out of sync".
*
* So you should only handle messages which are INDEPENDENT of the `tick`
* count in this method.
*
* - @type {Integer} Message type
* - @tick {Integer} Server side tick at which the message was send.
* - @data {Array} Message data
*
* Return `true` to indicate that the messag was handled.
*
*/
message: function(type, tick, data) {
},
/**
* {Boolean} Callback for synced messages received from the server.
*
* Due to the nature of the network, messages may arrive "Out of sync".
* So you should only handle messages which DEPEND of the `tick` count in
* this method.
*
* - @type {Integer} Message type
* - @tick {Integer} Server side tick at which the message was send.
* - @data {Array} Message data
*
* Return `true` to indicate that the messag was handled.
*
*/
syncedMessage: function(type, tick, data) {
},
/**
* The callback for when an error occurs and the server terminates the
* connection.
*
* - @type {Integer} The Error ID from {Maple.Error}
*/
error: function(type) {
},
/**
* The callback for when the connection to the server was closed.
*
* - @byRemote {Boolean} is `true` in case the connect was closed *by* the server.
* - @errorCode {Integer} Browser specific err
*/
closed: function(byRemote, errorCode) {
},
// Getter -----------------------------------------------------------------
/**
* {Integer} Returns the "synced" game time in milliseconds.
*
* Please note that this is not 100% accurate and should only be used for
* client side logic like drawing and effects.
*
* For synced actions between server and clinet always use the `tick` count.
*/
getTime: function() {
return this._tickCount * this._tickRate + (Date.now() - this._tickSyncTime);
},
/**
* {Integer} Returns the number of synced game ticks that happend since the
* server was started.
*/
getTick: function() {
// Ensure we don't return Infinite values here
if (!this.isRunning()) {
return 0;
} else {
var dt = (Date.now() - this._tickSyncTime),
tick = this._tickCount + Math.round(dt / this._tickRate) || 0;
return tick;
}
},
/**
* {Integer} Returns the ping to the server.
*/
getPing: function() {
return this._ping;
},
/**
* {Float} Returns a synced* random number between `0` and `1`.
*
* Note: This is only synced if the game code actual is the same on both sides.
*
* E.g: Doing 2 calls to this method on the client, but doing 3 on the server
* will have the potential to unsync the RNG until the next tick.
*/
getRandom: function() {
this._randomState = (1103515245 * (this._randomState + this._randomSeed) + 12345) % 0x100000000;
return this._randomState / 0x100000000;
},
// Conversions ------------------------------------------------------------
/**
* {Integer} Converts the message @type {String|Integer} into a integer ID representing for network transmission.
*/
messageTypeToId: function(type) {
if (typeof type === 'string') {
var id = this._messageTypes.indexOf(type);
if (id === -1) {
throw new Error('Undefined type id for "' + type + '"');
}
return id;
} else if (typeof type === 'number') {
return type;
} else {
this.logError('Invalid type value: "' + type + '"');
}
},
/**
* {String} Converts the message @id {Integer} into the corresponding message type string.
*/
messageTypeFromId: function(id) {
if (id >= 0 && id < this._messageTypes.length) {
return this._messageTypes[id];
} else {
this.logError('Undefined type string for "' + id + '"');
}
},
// Helpers ----------------------------------------------------------------
/**
* {var[]} A wrapper for `console.log()` which also gives information about the current state of the server.
*/
log: function() {
console.log.apply(console, this._log(arguments));
},
/**
* {var[]} A wrapper for `console.error()` which also gives information about the current state of the server.
*/
logError: function() {
console.error.apply(console, this._log(arguments));
},
/**
* {var[]} A wrapper for `console.warn()` which also gives information about the current state of the server.
*/
logWarning: function() {
console.warn.apply(console, this._log(arguments));
},
_log: function(args) {
var parts = Array.prototype.slice.call(args),
info = '[P: ' + this.getPing()
+ ' T: ' + this.getTime()
+ ' I: ' + this.getTick()
+ ' R: ' + this.getRandom() + ']\n';
parts.unshift(info);
parts.push('\n');
return parts;
}
});