-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo.js
469 lines (392 loc) · 12.9 KB
/
demo.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
// =============================================================================
// An Entity in the world.
// =============================================================================
let Entity = function () {
this.x = 0;
this.speed = 2; // units/s
this.position_buffer = [];
};
// Apply user's input to this entity.
Entity.prototype.applyInput = function (input) {
this.x += input.press_time * this.speed;
};
// =============================================================================
// A message queue with simulated network lag.
// =============================================================================
let LagNetwork = function () {
this.messages = [];
};
// "Send" a message. Store each message with the timestamp when it should be
// received, to simulate lag.
LagNetwork.prototype.send = function (lag_ms, message) {
this.messages.push({ recv_ts: +new Date() + lag_ms, payload: message });
};
// Returns a "received" message, or undefined if there are no messages available
// yet.
LagNetwork.prototype.receive = function () {
let now = +new Date();
for (let i = 0; i < this.messages.length; i++) {
let message = this.messages[i];
if (message.recv_ts <= now) {
this.messages.splice(i, 1);
return message.payload;
}
}
};
// =============================================================================
// The Client.
// =============================================================================
let Client = function (canvas, status) {
// Local representation of the entities.
this.entities = {};
// Input state.
this.key_left = false;
this.key_right = false;
// Simulated network connection.
this.network = new LagNetwork();
this.server = null;
this.lag = 0;
// Unique ID of our entity. Assigned by Server on connection.
this.entity_id = null;
// Data needed for reconciliation.
this.client_side_prediction = false;
this.server_reconciliation = false;
this.input_sequence_number = 0;
this.pending_inputs = [];
// Entity interpolation toggle.
this.entity_interpolation = true;
// UI.
this.canvas = canvas;
this.status = status;
// Update rate.
this.setUpdateRate(50);
};
Client.prototype.setUpdateRate = function (hz) {
this.update_rate = hz;
clearInterval(this.update_interval);
this.update_interval = setInterval(
(function (self) {
return function () {
self.update();
};
})(this),
1000 / this.update_rate
);
};
// Update Client state.
Client.prototype.update = function () {
// Listen to the server.
this.processServerMessages();
if (this.entity_id == null) {
return; // Not connected yet.
}
// Process inputs.
this.processInputs();
// Interpolate other entities.
if (this.entity_interpolation) {
this.interpolateEntities();
}
// Render the World.
renderWorld(this.canvas, this.entities);
// Show some info.
let info = 'Non-acknowledged inputs: ' + this.pending_inputs.length;
this.status.textContent = info;
};
// Get inputs and send them to the server.
// If enabled, do client-side prediction.
Client.prototype.processInputs = function () {
// Compute delta time since last update.
let now_ts = +new Date();
let last_ts = this.last_ts || now_ts;
let dt_sec = (now_ts - last_ts) / 1000.0;
this.last_ts = now_ts;
// Package player's input.
let input;
if (this.key_right) {
input = { press_time: dt_sec };
} else if (this.key_left) {
input = { press_time: -dt_sec };
} else {
// Nothing interesting happened.
return;
}
// Send the input to the server.
input.input_sequence_number = this.input_sequence_number++;
input.entity_id = this.entity_id;
this.server.network.send(this.lag, input);
// Do client-side prediction.
if (this.client_side_prediction) {
this.entities[this.entity_id].applyInput(input);
}
// Save this input for later reconciliation.
this.pending_inputs.push(input);
};
// Process all messages from the server, i.e. world updates.
// If enabled, do server reconciliation.
Client.prototype.processServerMessages = function () {
while (true) {
let message = this.network.receive();
if (!message) {
break;
}
// World state is a list of entity states.
for (const element of message) {
let state = element;
// If this is the first time we see this entity, create a local representation.
if (!this.entities[state.entity_id]) {
let entity = new Entity();
entity.entity_id = state.entity_id;
this.entities[state.entity_id] = entity;
}
let entity = this.entities[state.entity_id];
if (state.entity_id == this.entity_id) {
// Received the authoritative position of this client's entity.
entity.x = state.position;
if (this.server_reconciliation) {
// Server Reconciliation. Re-apply all the inputs not yet processed by
// the server.
let j = 0;
while (j < this.pending_inputs.length) {
let input = this.pending_inputs[j];
if (input.input_sequence_number <= state.last_processed_input) {
// Already processed. Its effect is already taken into account into the world update
// we just got, so we can drop it.
this.pending_inputs.splice(j, 1);
} else {
// Not processed by the server yet. Re-apply it.
entity.applyInput(input);
j++;
}
}
} else {
// Reconciliation is disabled, so drop all the saved inputs.
this.pending_inputs = [];
}
} else {
// Received the position of an entity other than this client's.
if (!this.entity_interpolation) {
// Entity interpolation is disabled - just accept the server's position.
entity.x = state.position;
} else {
// Add it to the position buffer.
let timestamp = +new Date();
entity.position_buffer.push([timestamp, state.position]);
}
}
}
}
};
Client.prototype.interpolateEntities = function () {
// Compute render timestamp.
let now = +new Date();
let render_timestamp = now - 1000.0 / server.update_rate;
for (let i in this.entities) {
let entity = this.entities[i];
// No point in interpolating this client's entity.
if (entity.entity_id == this.entity_id) {
continue;
}
// Find the two authoritative positions surrounding the rendering timestamp.
let buffer = entity.position_buffer;
// Drop older positions.
while (buffer.length >= 2 && buffer[1][0] <= render_timestamp) {
buffer.shift();
}
// Interpolate between the two surrounding authoritative positions.
if (
buffer.length >= 2 &&
buffer[0][0] <= render_timestamp &&
render_timestamp <= buffer[1][0]
) {
let x0 = buffer[0][1];
let x1 = buffer[1][1];
let t0 = buffer[0][0];
let t1 = buffer[1][0];
entity.x = x0 + ((x1 - x0) * (render_timestamp - t0)) / (t1 - t0);
}
}
};
// =============================================================================
// The Server.
// =============================================================================
let Server = function (canvas, status) {
// Connected clients and their entities.
this.clients = [];
this.entities = [];
// Last processed input for each client.
this.last_processed_input = [];
// Simulated network connection.
this.network = new LagNetwork();
// UI.
this.canvas = canvas;
this.status = status;
// Default update rate.
this.setUpdateRate(10);
};
Server.prototype.connect = function (client) {
// Give the Client enough data to identify itself.
client.server = this;
client.entity_id = this.clients.length;
this.clients.push(client);
// Create a new Entity for this Client.
let entity = new Entity();
this.entities.push(entity);
entity.entity_id = client.entity_id;
// Set the initial state of the Entity (e.g. spawn point)
let spawn_points = [4, 6];
entity.x = spawn_points[client.entity_id];
};
Server.prototype.setUpdateRate = function (hz) {
this.update_rate = hz;
clearInterval(this.update_interval);
this.update_interval = setInterval(
(function (self) {
return function () {
self.update();
};
})(this),
1000 / this.update_rate
);
};
Server.prototype.update = function () {
this.processInputs();
this.sendWorldState();
renderWorld(this.canvas, this.entities);
};
// Check whether this input seems to be valid (e.g. "make sense" according
// to the physical rules of the World)
Server.prototype.validateInput = function (input) {
return Math.abs(input.press_time) <= 1 / 40;
};
Server.prototype.processInputs = function () {
// Process all pending messages from clients.
while (true) {
let message = this.network.receive();
if (!message) {
break;
}
// 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(message)) {
let id = message.entity_id;
this.entities[id].applyInput(message);
this.last_processed_input[id] = message.input_sequence_number;
}
}
// Show some info.
let info = 'Last acknowledged input: ';
for (let i = 0; i < this.clients.length; ++i) {
info += 'Player ' + i + ': #' + (this.last_processed_input[i] || 0) + ' ';
}
this.status.textContent = info;
};
// Send the world state to all the connected clients.
Server.prototype.sendWorldState = function () {
// Gather the state of the world. In a real app, state could be filtered to avoid leaking data
// (e.g. position of invisible enemies).
let world_state = [];
let num_clients = this.clients.length;
for (let i = 0; i < num_clients; i++) {
let entity = this.entities[i];
world_state.push({
entity_id: entity.entity_id,
position: entity.x,
last_processed_input: this.last_processed_input[i],
});
}
// Broadcast the state to all the clients.
for (let i = 0; i < num_clients; i++) {
let client = this.clients[i];
client.network.send(client.lag, world_state);
}
};
// =============================================================================
// Helpers.
// =============================================================================
// Render all the entities in the given canvas.
let renderWorld = function (canvas, entities) {
// Clear the canvas.
canvas.width = canvas.width;
let colours = ['blue', 'red'];
for (let i in entities) {
let entity = entities[i];
// Compute size and position.
let radius = (canvas.height * 0.9) / 2;
let x = (entity.x / 10.0) * canvas.width;
// Draw the entity.
let ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(x, canvas.height / 2, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = colours[entity.entity_id];
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = 'dark' + colours[entity.entity_id];
ctx.stroke();
}
};
let element = function (id) {
return document.getElementById(id);
};
// =============================================================================
// Get everything up and running.
// =============================================================================
// World update rate of the Server.
let server_fps = 4;
// Update simulation parameters from UI.
let updateParameters = function () {
updatePlayerParameters(player1, 'player1');
updatePlayerParameters(player2, 'player2');
server.setUpdateRate(updateNumberFromUI(server.update_rate, 'server_fps'));
return true;
};
let updatePlayerParameters = function (client, prefix) {
client.lag = updateNumberFromUI(player1.lag, prefix + '_lag');
let cb_prediction = element(prefix + '_prediction');
let cb_reconciliation = element(prefix + '_reconciliation');
// Client Side Prediction disabled => disable Server Reconciliation.
if (client.client_side_prediction && !cb_prediction.checked) {
cb_reconciliation.checked = false;
}
// Server Reconciliation enabled => enable Client Side Prediction.
if (!client.server_reconciliation && cb_reconciliation.checked) {
cb_prediction.checked = true;
}
client.client_side_prediction = cb_prediction.checked;
client.server_reconciliation = cb_reconciliation.checked;
client.entity_interpolation = element(prefix + '_interpolation').checked;
};
let updateNumberFromUI = function (old_value, element_id) {
let input = element(element_id);
let new_value = parseInt(input.value);
if (isNaN(new_value)) {
new_value = old_value;
}
input.value = new_value;
return new_value;
};
// When the player presses the arrow keys, set the corresponding flag in the client.
let keyHandler = function (e) {
e = e || window.event;
if (e.keyCode == 39) {
player1.key_right = e.type == 'keydown';
} else if (e.keyCode == 37) {
player1.key_left = e.type == 'keydown';
} else if (e.key == 'd') {
player2.key_right = e.type == 'keydown';
} else if (e.key == 'a') {
player2.key_left = e.type == 'keydown';
} else {
console.log(e);
}
};
document.body.onkeydown = keyHandler;
document.body.onkeyup = keyHandler;
// Setup a server, the player's client, and another player.
let server = new Server(element('server_canvas'), element('server_status'));
let player1 = new Client(element('player1_canvas'), element('player1_status'));
let player2 = new Client(element('player2_canvas'), element('player2_status'));
// Connect the clients to the server.
server.connect(player1);
server.connect(player2);
// Read initial parameters from the UI.
updateParameters();