forked from OgarProject/Ogar
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathGameServer.js
1884 lines (1713 loc) · 66.3 KB
/
GameServer.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
// Library imports
var http = require('http');
var fs = require("fs");
var os = require('os');
var path = require('path');
var pjson = require('../package.json');
var ini = require('./modules/ini.js');
var QuadNode = require('quad-node');
var PlayerCommand = require('./modules/PlayerCommand');
var HttpsServer = require('./HttpsServer');
// Project imports
var Packet = require('./packet');
var PlayerTracker = require('./PlayerTracker');
var PacketHandler = require('./PacketHandler');
var Entity = require('./entity');
var Gamemode = require('./gamemodes');
var BotLoader = require('./ai/BotLoader');
var Logger = require('./modules/Logger');
var UserRoleEnum = require('./enum/UserRoleEnum');
// GameServer implementation
function GameServer() {
this.httpServer = null;
this.wsServer = null;
// Startup
this.run = true;
this.lastNodeId = 1;
this.lastPlayerId = 1;
this.clients = [];
this.socketCount = 0;
this.largestClient; // Required for spectators
this.nodes = [];
this.nodesVirus = []; // Virus nodes
this.nodesEjected = []; // Ejected mass nodes
this.quadTree = null;
this.currentFood = 0;
this.movingNodes = []; // For move engine
this.leaderboard = [];
this.leaderboardType = -1; // no type
this.bots = new BotLoader(this);
this.commands; // Command handler
// Main loop tick
this.startTime = Date.now();
this.stepDateTime = 0;
this.timeStamp = 0;
this.updateTime = 0;
this.updateTimeAvg = 0;
this.timerLoopBind = null;
this.mainLoopBind = null;
this.tickCounter = 0;
this.setBorder(10000, 10000);
// Config
this.config = {
logVerbosity: 4, // Console log level (0=NONE; 1=FATAL; 2=ERROR; 3=WARN; 4=INFO; 5=DEBUG)
logFileVerbosity: 5, // File log level
serverTimeout: 300, // Seconds to keep connection alive for non-responding client
serverWsModule: 'ws', // WebSocket module: 'ws' or 'uws' (install npm package before using uws)
serverMaxConnections: 64, // Maximum number of connections to the server. (0 for no limit)
serverIpLimit: 4, // Maximum number of connections from the same IP (0 for no limit)
serverMinionIgnoreTime: 30, // minion detection disable time on server startup [seconds]
serverMinionThreshold: 10, // max connections within serverMinionInterval time period, which will not be marked as minion
serverMinionInterval: 1000, // minion detection interval [milliseconds]
serverPort: 443, // Server port
serverBind: '0.0.0.0', // Network interface binding
serverTracker: 0, // Set to 1 if you want to show your server on the tracker http://ogar.mivabe.nl/master
serverGamemode: 0, // Gamemode, 0 = FFA, 1 = Teams
serverBots: 0, // Number of player bots to spawn
serverViewBaseX: 1920, // Base client screen resolution. Used to calculate view area. Warning: high values may cause lag
serverViewBaseY: 1080, // min value is 1920x1080
serverMinScale: 0.15, // Min scale for player (low value leads to lags due to large visible area)
serverSpectatorScale: 0.4, // Scale (field of view) used for free roam spectators (low value leads to lags, vanilla=0.4, old vanilla=0.25)
serverStatsPort: 88, // Port for stats server. Having a negative number will disable the stats server.
serverStatsUpdate: 60, // Update interval of server stats in seconds
serverScrambleLevel: 2, // Toggles scrambling of coordinates. 0 = No scrambling, 1 = lightweight scrambling. 2 = full scrambling (also known as scramble minimap); 3 - high scrambling (no border)
serverMaxLB: 10, // Controls the maximum players displayed on the leaderboard.
serverChat: 1, // Set to 1 to allow chat; 0 to disable chat.
serverChatAscii: 1, // Set to 1 to disable non-ANSI letters in the chat (english only mode)
serverName: 'MultiOgar #1', // Server name
serverWelcome1: 'Welcome to MultiOgar server!', // First server welcome message
serverWelcome2: '', // Second server welcome message (for info, etc)
borderWidth: 14142, // Map border size (Vanilla value: 14142)
borderHeight: 14142, // Map border size (Vanilla value: 14142)
foodMinSize: 10, // Minimum food size (vanilla 10)
foodMaxSize: 20, // Maximum food size (vanilla 20)
foodMinAmount: 1000, // Minimum food cells on the map
foodMaxAmount: 2000, // Maximum food cells on the map
foodSpawnAmount: 30, // The number of food to spawn per interval
foodMassGrow: 1, // Enable food mass grow ?
spawnInterval: 20, // The interval between each food cell spawn in ticks (1 tick = 50 ms)
virusMinSize: 100, // Minimum virus size (vanilla 100)
virusMaxSize: 140, // Maximum virus size (vanilla 140)
virusMinAmount: 50, // Minimum number of viruses on the map.
virusMaxAmount: 100, // Maximum number of viruses on the map. If this number is reached, then ejected cells will pass through viruses.
ejectSize: 38, // Size of ejected cells (vanilla 38)
ejectSizeLoss: 43, // Eject size which will be substracted from player cell (vanilla 43?)
ejectDistance: 780, // vanilla 780
ejectCooldown: 3, // min ticks between ejects
ejectSpawnPlayer: 1, // if 1 then player may be spawned from ejected mass
playerMinSize: 32, // Minimym size of the player cell (mass = 32*32/100 = 10.24)
playerMaxSize: 1500, // Maximum size of the player cell (mass = 1500*1500/100 = 22500)
playerMinSplitSize: 60, // Minimum player cell size allowed to split (mass = 60*60/100 = 36)
playerStartSize: 64, // Start size of the player cell (mass = 64*64/100 = 41)
playerMaxCells: 16, // Max cells the player is allowed to have
playerSpeed: 1, // Player speed multiplier
playerDecayRate: .002, // Amount of player cell size lost per second
playerRecombineTime: 30, // Base time in seconds before a cell is allowed to recombine
playerMaxNickLength: 15, // Maximum nick length
playerDisconnectTime: 60, // The time in seconds it takes for a player cell to be removed after disconnection (If set to -1, cells are never removed)
tourneyMaxPlayers: 12, // Maximum number of participants for tournament style game modes
tourneyPrepTime: 10, // Number of ticks to wait after all players are ready (1 tick = 1000 ms)
tourneyEndTime: 30, // Number of ticks to wait after a player wins (1 tick = 1000 ms)
tourneyTimeLimit: 20, // Time limit of the game, in minutes.
tourneyAutoFill: 0, // If set to a value higher than 0, the tournament match will automatically fill up with bots after this amount of seconds
tourneyAutoFillPlayers: 1, // The timer for filling the server with bots will not count down unless there is this amount of real players
};
this.ipBanList = [];
this.minionTest = [];
this.userList = [];
this.badWords = [];
// Parse config
this.loadConfig();
this.loadIpBanList();
this.loadUserList();
this.loadBadWords();
this.setBorder(this.config.borderWidth, this.config.borderHeight);
this.quadTree = new QuadNode(this.border, 64, 32);
// Gamemodes
this.gameMode = Gamemode.get(this.config.serverGamemode);
}
module.exports = GameServer;
GameServer.prototype.start = function () {
this.timerLoopBind = this.timerLoop.bind(this);
this.mainLoopBind = this.mainLoop.bind(this);
// Gamemode configurations
this.gameMode.onServerInit(this);
var dirSsl = path.join(path.dirname(module.filename), '../ssl');
var pathKey = path.join(dirSsl, 'key.pem');
var pathCert = path.join(dirSsl, 'cert.pem');
if (fs.existsSync(pathKey) && fs.existsSync(pathCert)) {
// HTTP/TLS
var options = {
key: fs.readFileSync(pathKey, 'utf8'),
cert: fs.readFileSync(pathCert, 'utf8')
};
Logger.info("TLS: supported");
this.httpServer = HttpsServer.createServer(options);
} else {
// HTTP only
Logger.warn("TLS: not supported (SSL certificate not found!)");
this.httpServer = http.createServer();
}
var wsOptions = {
server: this.httpServer,
perMessageDeflate: false,
maxPayload: 4096
};
Logger.info("WebSocket: " + this.config.serverWsModule);
WebSocket = require(this.config.serverWsModule);
// Custom prototype functions^M
WebSocket.prototype.sendPacket = function (packet) {
if (packet == null) return;
if (this.readyState == WebSocket.OPEN) {
if (this._socket.writable != null && !this._socket.writable) {
return;
}
var buffer = packet.build(this.playerTracker.socket.packetHandler.protocol);
if (buffer != null) {
this.send(buffer, { binary: true });
}
} else {
this.readyState = WebSocket.CLOSED;
this.emit('close');
}
};
this.wsServer = new WebSocket.Server(wsOptions);
this.wsServer.on('error', this.onServerSocketError.bind(this));
this.wsServer.on('connection', this.onClientSocketOpen.bind(this));
this.httpServer.listen(this.config.serverPort, this.config.serverBind, this.onHttpServerOpen.bind(this));
this.startStatsServer(this.config.serverStatsPort);
};
GameServer.prototype.onHttpServerOpen = function () {
// Spawn starting food
this.startingFood();
// Start Main Loop
setTimeout(this.timerLoopBind, 1);
// Done
Logger.info("Listening on port " + this.config.serverPort);
Logger.info("Current game mode is " + this.gameMode.name);
// Player bots (Experimental)
if (this.config.serverBots > 0) {
for (var i = 0; i < this.config.serverBots; i++) {
this.bots.addBot();
}
Logger.info("Added " + this.config.serverBots + " player bots");
}
};
GameServer.prototype.onServerSocketError = function (error) {
Logger.error("WebSocket: " + error.code + " - " + error.message);
switch (error.code) {
case "EADDRINUSE":
Logger.error("Server could not bind to port " + this.config.serverPort + "!");
Logger.error("Please close out of Skype or change 'serverPort' in gameserver.ini to a different number.");
break;
case "EACCES":
Logger.error("Please make sure you are running Ogar with root privileges.");
break;
}
process.exit(1); // Exits the program
};
GameServer.prototype.onClientSocketOpen = function (ws) {
var logip = ws._socket.remoteAddress + ":" + ws._socket.remotePort;
ws.on('error', function (err) {
Logger.writeError("[" + logip + "] " + err.stack);
});
if (this.config.serverMaxConnections > 0 && this.socketCount >= this.config.serverMaxConnections) {
ws.close(1000, "No slots");
return;
}
if (this.checkIpBan(ws._socket.remoteAddress)) {
ws.close(1000, "IP banned");
return;
}
if (this.config.serverIpLimit > 0) {
var ipConnections = 0;
for (var i = 0; i < this.clients.length; i++) {
var socket = this.clients[i];
if (!socket.isConnected || socket.remoteAddress != ws._socket.remoteAddress)
continue;
ipConnections++;
}
if (ipConnections >= this.config.serverIpLimit) {
ws.close(1000, "IP limit reached");
return;
}
}
ws.isConnected = true;
ws.remoteAddress = ws._socket.remoteAddress;
ws.remotePort = ws._socket.remotePort;
ws.lastAliveTime = Date.now();
Logger.write("CONNECTED " + ws.remoteAddress + ":" + ws.remotePort + ", origin: \"" + ws.upgradeReq.headers.origin + "\"");
ws.playerTracker = new PlayerTracker(this, ws);
ws.packetHandler = new PacketHandler(this, ws);
ws.playerCommand = new PlayerCommand(this, ws.playerTracker);
var self = this;
var onMessage = function (message) {
self.onClientSocketMessage(ws, message);
};
var onError = function (error) {
self.onClientSocketError(ws, error);
};
var onClose = function (reason) {
self.onClientSocketClose(ws, reason);
};
ws.on('message', onMessage);
ws.on('error', onError);
ws.on('close', onClose);
this.socketCount++;
this.clients.push(ws);
// Minion detection
if (this.config.serverMinionThreshold) {
if ((ws.lastAliveTime - this.startTime) / 1000 >= this.config.serverMinionIgnoreTime) {
if (this.minionTest.length >= this.config.serverMinionThreshold) {
ws.playerTracker.isMinion = true;
for (var i = 0; i < this.minionTest.length; i++) {
var playerTracker = this.minionTest[i];
if (!playerTracker.socket.isConnected) continue;
playerTracker.isMinion = true;
}
if (this.minionTest.length) {
this.minionTest.splice(0, 1);
}
}
this.minionTest.push(ws.playerTracker);
}
}
};
GameServer.prototype.onClientSocketClose = function (ws, code) {
if (ws._socket.destroy != null && typeof ws._socket.destroy == 'function') {
ws._socket.destroy();
}
if (this.socketCount < 1) {
Logger.error("GameServer.onClientSocketClose: socketCount=" + this.socketCount);
} else {
this.socketCount--;
}
ws.isConnected = false;
ws.sendPacket = function (data) { };
ws.closeReason = { code: ws._closeCode, message: ws._closeMessage };
ws.closeTime = Date.now();
Logger.write("DISCONNECTED " + ws.remoteAddress + ":" + ws.remotePort + ", code: " + ws._closeCode + ", reason: \"" + ws._closeMessage + "\", name: \"" + ws.playerTracker.getName() + "\"");
// disconnected effect
var color = this.getGrayColor(ws.playerTracker.getColor());
ws.playerTracker.setColor(color);
ws.playerTracker.setSkin("");
ws.playerTracker.cells.forEach(function (cell) {
cell.setColor(color);
}, this);
};
GameServer.prototype.onClientSocketError = function (ws, error) {
ws.sendPacket = function (data) { };
};
GameServer.prototype.onClientSocketMessage = function (ws, message) {
if (message.length == 0) {
return;
}
if (message.length > 256) {
ws.close(1009, "Spam");
return;
}
ws.packetHandler.handleMessage(message);
};
GameServer.prototype.setBorder = function (width, height) {
var hw = width / 2;
var hh = height / 2;
this.border = {
minx: -hw,
miny: -hh,
maxx: hw,
maxy: hh,
width: width,
height: height,
centerx: 0,
centery: 0
};
};
GameServer.prototype.getTick = function () {
return this.tickCounter;
};
GameServer.prototype.getMode = function () {
return this.gameMode;
};
GameServer.prototype.getNextNodeId = function () {
// Resets integer
if (this.lastNodeId > 2147483647) {
this.lastNodeId = 1;
}
return this.lastNodeId++ >>> 0;
};
GameServer.prototype.getNewPlayerID = function () {
// Resets integer
if (this.lastPlayerId > 2147483647) {
this.lastPlayerId = 1;
}
return this.lastPlayerId++ >>> 0;
};
GameServer.prototype.getRandomPosition = function () {
return {
x: Math.floor(this.border.minx + this.border.width * Math.random()),
y: Math.floor(this.border.miny + this.border.height * Math.random())
};
};
GameServer.prototype.getGrayColor = function (rgb) {
var luminance = Math.min(255, (rgb.r * 0.2125 + rgb.g * 0.7154 + rgb.b * 0.0721)) >>> 0;
return {
r: luminance,
g: luminance,
b: luminance
};
};
GameServer.prototype.getRandomColor = function () {
var h = 360 * Math.random();
var s = 248 / 255;
var v = 1;
// hsv to rgb
var rgb = { r: v, g: v, b: v }; // achromatic (grey)
if (s > 0) {
h /= 60; // sector 0 to 5
var i = Math.floor(h) >> 0;
var f = h - i; // factorial part of h
var p = v * (1 - s);
var q = v * (1 - s * f);
var t = v * (1 - s * (1 - f));
switch (i) {
case 0: rgb = { r: v, g: t, b: p }; break
case 1: rgb = { r: q, g: v, b: p }; break
case 2: rgb = { r: p, g: v, b: t }; break
case 3: rgb = { r: p, g: q, b: v }; break
case 4: rgb = { r: t, g: p, b: v }; break
default: rgb = { r: v, g: p, b: q }; break
}
}
// check color range
rgb.r = Math.max(rgb.r, 0);
rgb.g = Math.max(rgb.g, 0);
rgb.b = Math.max(rgb.b, 0);
rgb.r = Math.min(rgb.r, 1);
rgb.g = Math.min(rgb.g, 1);
rgb.b = Math.min(rgb.b, 1);
return {
r: (rgb.r * 255) >>> 0,
g: (rgb.g * 255) >>> 0,
b: (rgb.b * 255) >>> 0
};
};
GameServer.prototype.updateNodeQuad = function (node) {
var item = node.quadItem;
if (item == null) {
throw new TypeError("GameServer.updateNodeQuad: quadItem is null!");
}
var x = node.position.x;
var y = node.position.y;
var size = node.getSize();
// check for change
if (item.x === x && item.y === y && item.size === size) {
return;
}
// update quad tree
item.x = x;
item.y = y;
item.size = size;
item.bound.minx = x - size;
item.bound.miny = y - size;
item.bound.maxx = x + size;
item.bound.maxy = y + size;
this.quadTree.update(item);
};
GameServer.prototype.addNode = function (node) {
var x = node.position.x;
var y = node.position.y;
var size = node.getSize();
node.quadItem = {
cell: node,
x: x,
y: y,
size: size,
bound: { minx: x-size, miny: y-size, maxx: x+size, maxy: y+size }
};
this.quadTree.insert(node.quadItem);
this.nodes.push(node);
// Adds to the owning player's screen
if (node.owner) {
node.setColor(node.owner.getColor());
node.owner.cells.push(node);
node.owner.socket.sendPacket(new Packet.AddNode(node.owner, node));
}
// Special on-add actions
node.onAdd(this);
};
GameServer.prototype.removeNode = function (node) {
if (node.quadItem == null) {
throw new TypeError("GameServer.removeNode: attempt to remove invalid node!");
}
node.isRemoved = true;
this.quadTree.remove(node.quadItem);
node.quadItem = null;
// Remove from main nodes list
var index = this.nodes.indexOf(node);
if (index != -1) {
this.nodes.splice(index, 1);
}
// Remove from moving cells list
index = this.movingNodes.indexOf(node);
if (index != -1) {
this.movingNodes.splice(index, 1);
}
// Special on-remove actions
node.onRemove(this);
};
GameServer.prototype.updateClients = function () {
// check minions
for (var i = 0; i < this.minionTest.length; ) {
var playerTracker = this.minionTest[i];
if (this.stepDateTime - playerTracker.connectedTime > this.config.serverMinionInterval) {
this.minionTest.splice(i, 1);
} else {
i++;
}
}
// check dead clients
for (var i = 0; i < this.clients.length; ) {
var playerTracker = this.clients[i].playerTracker;
playerTracker.checkConnection();
if (playerTracker.isRemoved) {
// remove dead client
this.clients.splice(i, 1);
} else {
i++;
}
}
// update
for (var i = 0; i < this.clients.length; i++) {
this.clients[i].playerTracker.updateTick();
}
for (var i = 0; i < this.clients.length; i++) {
this.clients[i].playerTracker.sendUpdate();
}
};
GameServer.prototype.updateLeaderboard = function () {
// Update leaderboard with the gamemode's method
this.leaderboard = [];
this.leaderboardType = -1;
this.gameMode.updateLB(this);
if (!this.gameMode.specByLeaderboard) {
// Get client with largest score if gamemode doesn't have a leaderboard
var clients = this.clients.valueOf();
// Use sort function
clients.sort(function (a, b) {
return b.playerTracker.getScore() - a.playerTracker.getScore();
});
//this.largestClient = clients[0].playerTracker;
this.largestClient = null;
if (clients[0] != null)
this.largestClient = clients[0].playerTracker;
} else {
this.largestClient = this.gameMode.rankOne;
}
};
GameServer.prototype.onChatMessage = function (from, to, message) {
if (message == null) return;
message = message.trim();
if (message == "") return;
if (from && message.length > 0 && message[0] == '/') {
// player command
message = message.slice(1, message.length);
from.socket.playerCommand.executeCommandLine(message);
return;
}
if (!this.config.serverChat) {
// chat is disabled
return;
}
if (from && from.isMuted) {
// player is muted
return;
}
if (message.length > 64) {
message = message.slice(0, 64);
}
if (this.config.serverChatAscii) {
for (var i = 0; i < message.length; i++) {
var c = message.charCodeAt(i);
if (c < 0x20 || c > 0x7F) {
if (from) {
this.sendChatMessage(null, from, "You can use ASCII text only!");
}
return;
}
}
}
if (this.checkBadWord(message)) {
if (from) {
this.sendChatMessage(null, from, "Stop insulting others! Keep calm and be friendly please");
}
return;
}
if (from) {
Logger.writeDebug("[CHAT][" + from.socket.remoteAddress + ":" + from.socket.remotePort + "][" + from.getFriendlyName() + "] " + message);
} else {
Logger.writeDebug("[CHAT][][]: " + message);
}
this.sendChatMessage(from, to, message);
};
GameServer.prototype.sendChatMessage = function (from, to, message) {
for (var i = 0; i < this.clients.length; i++) {
var client = this.clients[i];
if (client == null) continue;
if (to == null || to == client.playerTracker)
client.sendPacket(new Packet.ChatMessage(from, message));
}
};
GameServer.prototype.timerLoop = function () {
var timeStep = 40;
var ts = Date.now();
var dt = ts - this.timeStamp;
if (dt < timeStep - 5) {
setTimeout(this.timerLoopBind, ((timeStep - 5) - dt) >> 0);
return;
}
if (dt < timeStep - 1) {
setTimeout(this.timerLoopBind, 0);
return;
}
if (dt < timeStep) {
//process.nextTick(this.timerLoopBind);
setTimeout(this.timerLoopBind, 0);
return;
}
if (dt > 120) {
// too high lag => resynchronize
this.timeStamp = ts-timeStep;
}
// update average
this.updateTimeAvg += 0.5 * (this.updateTime - this.updateTimeAvg);
// calculate next
if (this.timeStamp == 0)
this.timeStamp = ts;
this.timeStamp += timeStep;
//process.nextTick(this.mainLoopBind);
//process.nextTick(this.timerLoopBind);
setTimeout(this.mainLoopBind, 0);
setTimeout(this.timerLoopBind, 0);
};
GameServer.prototype.mainLoop = function () {
this.stepDateTime = Date.now();
var tStart = process.hrtime();
// Loop main functions
if (this.run) {
this.updateMoveEngine();
if ((this.getTick() % this.config.spawnInterval) == 0) {
this.updateFood(); // Spawn food
this.updateVirus(); // Spawn viruses
}
this.gameMode.onTick(this);
if (((this.getTick() + 3) % (1000 / 40)) == 0) {
// once per second
this.updateMassDecay();
}
}
this.updateClients();
if (((this.getTick() + 7) % (1000 / 40)) == 0) {
// once per second
this.updateLeaderboard();
}
// ping server tracker
if (this.config.serverTracker && (this.getTick() % (10000 / 40)) == 0) {
// once per 30 seconds
this.pingServerTracker();
}
if (this.run) {
this.tickCounter++;
}
var tEnd = process.hrtime(tStart);
this.updateTime = tEnd[0] * 1000 + tEnd[1] / 1000000;
};
GameServer.prototype.startingFood = function () {
// Spawns the starting amount of food cells
for (var i = 0; i < this.config.foodMinAmount; i++) {
this.spawnFood();
}
};
GameServer.prototype.updateFood = function () {
var maxCount = this.config.foodMinAmount - this.currentFood;
var spawnCount = Math.min(maxCount, this.config.foodSpawnAmount);
for (var i = 0; i < spawnCount; i++) {
this.spawnFood();
}
};
GameServer.prototype.updateVirus = function () {
var maxCount = this.config.virusMinAmount - this.nodesVirus.length;
var spawnCount = Math.min(maxCount, 2);
for (var i = 0; i < spawnCount; i++) {
this.spawnVirus();
}
};
GameServer.prototype.spawnFood = function () {
var cell = new Entity.Food(this, null, this.getRandomPosition(), this.config.foodMinSize);
if (this.config.foodMassGrow) {
var size = cell.getSize();
var maxGrow = this.config.foodMaxSize - size;
size += maxGrow * Math.random();
cell.setSize(size);
}
cell.setColor(this.getRandomColor());
this.addNode(cell);
};
GameServer.prototype.spawnVirus = function () {
// Spawns a virus
var pos = this.getRandomPosition();
if (this.willCollide(pos, this.config.virusMinSize)) {
// cannot find safe position => do not spawn
return;
}
var v = new Entity.Virus(this, null, pos, this.config.virusMinSize);
this.addNode(v);
};
GameServer.prototype.spawnPlayer = function (player, pos, size) {
// Check if can spawn from ejected mass
if (!pos && this.config.ejectSpawnPlayer && this.nodesEjected.length > 0) {
if (Math.random() >= 0.5) {
// Spawn from ejected mass
var index = (this.nodesEjected.length - 1) * Math.random() >>> 0;
var eject = this.nodesEjected[index];
if (!eject.isRemoved) {
this.removeNode(eject);
pos = {
x: eject.position.x,
y: eject.position.y
};
if (!size) {
size = Math.max(eject.getSize(), this.config.playerStartSize);
}
}
}
}
if (pos == null) {
// Get random pos
var pos = this.getRandomPosition();
// 10 attempts to find safe position
for (var i = 0; i < 10 && this.willCollide(pos, this.config.playerMinSize); i++) {
pos = this.getRandomPosition();
}
}
if (size == null) {
// Get starting mass
size = this.config.playerStartSize;
}
// Spawn player and add to world
var cell = new Entity.PlayerCell(this, player, pos, size);
this.addNode(cell);
// Set initial mouse coords
player.mouse = {
x: pos.x,
y: pos.y
};
};
GameServer.prototype.willCollide = function (pos, size) {
// Look if there will be any collision with the current nodes
var bound = {
minx: pos.x - size,
miny: pos.y - size,
maxx: pos.x + size,
maxy: pos.y + size
};
return this.quadTree.any(
bound,
function (item) {
return item.cell.cellType == 0; // check players only
});
};
// Checks cells for collision.
// Returns collision manifold or null if there is no collision
GameServer.prototype.checkCellCollision = function (cell, check) {
var r = cell.getSize() + check.getSize();
var dx = check.position.x - cell.position.x;
var dy = check.position.y - cell.position.y;
var squared = dx * dx + dy * dy; // squared distance from cell to check
if (squared > r * r) {
// no collision
return null;
}
// create collision manifold
return {
cell1: cell,
cell2: check,
r: r, // radius sum
dx: dx, // delta x from cell1 to cell2
dy: dy, // delta y from cell1 to cell2
squared: squared // squared distance from cell1 to cell2
};
};
// Resolves rigid body collision
GameServer.prototype.resolveRigidCollision = function (manifold, border) {
// distance from cell1 to cell2
var d = Math.sqrt(manifold.squared);
if (d <= 0) return;
var invd = 1 / d;
// normal
var nx = ~~manifold.dx * invd;
var ny = ~~manifold.dy * invd;
// body penetration distance
var penetration = manifold.r - d;
if (penetration <= 0) return;
// penetration vector = penetration * normal
var px = penetration * nx;
var py = penetration * ny;
// body impulse
var totalMass = manifold.cell1.getSizeSquared() + manifold.cell2.getSizeSquared();
if (totalMass <= 0) return;
var invTotalMass = 1 / totalMass;
var impulse1 = manifold.cell2.getSizeSquared() * invTotalMass;
var impulse2 = manifold.cell1.getSizeSquared() * invTotalMass;
// apply extrusion force
manifold.cell1.position.x -= px * impulse1;
manifold.cell1.position.y -= py * impulse1;
manifold.cell2.position.x += px * impulse2;
manifold.cell2.position.y += py * impulse2;
// clip to border bounds
manifold.cell1.checkBorder(border);
manifold.cell2.checkBorder(border);
};
// Checks if collision is rigid body collision
GameServer.prototype.checkRigidCollision = function (manifold) {
if (!manifold.cell1.owner || !manifold.cell2.owner)
return false;
if (manifold.cell1.owner != manifold.cell2.owner) {
// Different owners
return this.gameMode.haveTeams &&
manifold.cell1.owner.getTeam() == manifold.cell2.owner.getTeam();
}
// The same owner
if (manifold.cell1.owner.mergeOverride)
return false;
var tick = this.getTick();
if (manifold.cell1.getAge(tick) < 15 || manifold.cell2.getAge(tick) < 15) {
// just splited => ignore
return false;
}
return !manifold.cell1.canRemerge() || !manifold.cell2.canRemerge();
};
// Resolves non-rigid body collision
GameServer.prototype.resolveCollision = function (manifold) {
var minCell = manifold.cell1;
var maxCell = manifold.cell2;
// check if any cell already eaten
if (minCell.isRemoved || maxCell.isRemoved)
return;
if (minCell.getSize() > maxCell.getSize()) {
minCell = manifold.cell2;
maxCell = manifold.cell1;
}
// check distance
var eatDistance = maxCell.getSize() - minCell.getSize() / 3;
if (manifold.squared >= eatDistance * eatDistance) {
// too far => can't eat
return;
}
if (minCell.owner && minCell.owner == maxCell.owner) {
// collision owned/owned => ignore or resolve or remerge
var tick = this.getTick();
if (minCell.getAge(tick) < 15 || maxCell.getAge(tick) < 15) {
// just splited => ignore
return;
}
if (!minCell.owner.mergeOverride) {
// not force remerge => check if can remerge
if (!minCell.canRemerge() || !maxCell.canRemerge()) {
// cannot remerge
return;
}
}
} else {
// collision owned/enemy => check if can eat
// Team check
if (this.gameMode.haveTeams && minCell.owner && maxCell.owner) {
if (minCell.owner.getTeam() == maxCell.owner.getTeam()) {
// cannot eat team member
return;
}
}
// Size check
if (maxCell.getSize() <= minCell.getSize() * 1.15) {
// too large => can't eat
return;
}
}
if (!maxCell.canEat(minCell)) {
// maxCell don't want to eat
return;
}
// Now maxCell can eat minCell
minCell.isRemoved = true;
// Disable mergeOverride on the last merging cell
// We need to disable it before onCosume to prevent merging loop
// (onConsume may cause split for big mass)
if (minCell.owner && minCell.owner.cells.length <= 2) {
minCell.owner.mergeOverride = false;
}
var isMinion = (maxCell.owner && maxCell.owner.isMinion) ||
(minCell.owner && minCell.owner.isMinion);
if (!isMinion) {
// Consume effect
maxCell.onEat(minCell);
minCell.onEaten(maxCell);
// update bounds
this.updateNodeQuad(maxCell);
}
// Remove cell
minCell.setKiller(maxCell);
this.removeNode(minCell);
};
GameServer.prototype.updateMoveEngine = function () {
var tick = this.getTick();
// Move player cells
for (var i in this.clients) {
var client = this.clients[i].playerTracker;
var checkSize = !client.mergeOverride || client.cells.length == 1;
for (var j = 0; j < client.cells.length; j++) {
var cell1 = client.cells[j];
if (cell1.isRemoved)
continue;
cell1.updateRemerge(this);
cell1.moveUser(this.border);
cell1.move(this.border);
// check size limit
if (checkSize && cell1.getSize() > this.config.playerMaxSize && cell1.getAge(tick) >= 15) {
if (client.cells.length >= this.config.playerMaxCells) {
// cannot split => just limit
cell1.setSize(this.config.playerMaxSize);
} else {
// split
var maxSplit = this.config.playerMaxCells - client.cells.length;
var maxMass = this.config.playerMaxSize * this.config.playerMaxSize;
var count = (cell1.getSizeSquared() / maxMass) >> 0;
var count = Math.min(count, maxSplit);
var splitSize = cell1.getSize() / Math.sqrt(count + 1);
var splitMass = splitSize * splitSize / 100;
var angle = Math.random() * 2 * Math.PI;
var step = 2 * Math.PI / count;
for (var k = 0; k < count; k++) {
this.splitPlayerCell(client, cell1, angle, splitMass);
angle += step;
}
}
}
this.updateNodeQuad(cell1);
}
}
// Move moving cells