-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1982 lines (1781 loc) · 73.2 KB
/
server.js
File metadata and controls
1982 lines (1781 loc) · 73.2 KB
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
/*
* Copyright (C) 2025-2026 Tim Riker <timriker@gmail.com>
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3).
* Source: https://github.com/BZFlag-Dev/bzo
* See LICENSE or https://www.gnu.org/licenses/agpl-3.0.html
*/
const express = require('express');
const logPath = require('path').join(__dirname, 'server.log');
// Clear server.log on restart
require('fs').writeFileSync(logPath, '');
const { WebSocketServer } = require('ws');
const path = require('path');
const fs = require('fs');
// Common log function: logs to console and to server.log
function log(...args) {
const now = new Date();
const timestamp = now.toISOString();
const msg = args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ');
const logMsg = `[${timestamp}] ${msg}`;
// Write to console
console.log(logMsg);
// Append to server.log
fs.appendFileSync(path.join(__dirname, 'server.log'), logMsg + '\n');
}
function logError(...args) {
const now = new Date();
const timestamp = now.toISOString();
const msg = args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ');
const logMsg = `[${timestamp}] [ERROR] ${msg}`;
console.error(logMsg);
fs.appendFileSync(path.join(__dirname, 'server.log'), logMsg + '\n');
}
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const PORT = process.env.PORT || 3000;
const CONFIG_PATH = process.env.SERVER_CONFIG_PATH
? path.resolve(process.env.SERVER_CONFIG_PATH)
: path.join(__dirname, 'server-config.json');
const EXAMPLE_CONFIG_PATH = path.join(__dirname, 'example-server-config.json');
// Serve static files
app.use(express.static('public'));
function getAvailableTankModels() {
const objDir = path.join(__dirname, 'public', 'obj');
const hiddenModelFiles = new Set(['tank.obj']);
try {
return fs.readdirSync(objDir)
.filter((fileName) => fileName.toLowerCase().endsWith('.obj'))
.filter((fileName) => !hiddenModelFiles.has(fileName.toLowerCase()))
.map((fileName) => {
const id = fileName.slice(0, -4).toLowerCase();
const label = id === 'bzflag'
? 'BZFlag'
: id === 'wheeled6'
? 'Wheeled 6'
: id
.split(/[-_\s]+/)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ');
return {
id,
path: `/obj/${fileName}`,
label: label || id,
};
})
.sort((left, right) => {
if (left.id === 'bzflag') return -1;
if (right.id === 'bzflag') return 1;
return left.id.localeCompare(right.id);
});
} catch (error) {
logError('Failed to list tank models:', error.message || error);
return [];
}
}
function isAllowedTankModel(modelId) {
if (typeof modelId !== 'string') return false;
const normalized = modelId.trim().toLowerCase();
if (!/^[a-z0-9_-]+$/.test(normalized)) return false;
return getAvailableTankModels().some((model) => model.id === normalized);
}
function normalizeTankModelId(modelId) {
const normalized = typeof modelId === 'string' ? modelId.trim().toLowerCase() : '';
if (normalized === 'default') return 'bzflag';
if (normalized === 'bzflag-tank') return 'bzflag';
if (normalized === 'tank') return 'bzflag';
return normalized;
}
app.get('/api/tank-models', (req, res) => {
res.json({ models: getAvailableTankModels() });
});
// AGPL §13: provide source code access to network users
app.get('/source', (req, res) => {
res.redirect(302, 'https://github.com/BZFlag-Dev/bzo');
});
// --- Admin API Endpoints ---
const server = app.listen(PORT, '::', () => {
log(`Server running on http://[::]:${PORT}`);
});
// WebSocket server
const wss = new WebSocketServer({ server });
// Game constants
const GAME_CONFIG = {
MAP_SIZE: 400,
TANK_SPEED: 25.0, // BZFlag-like default (units per second)
TANK_ROTATION_SPEED: 0.785398, // BZFlag _tankAngVel default (radians per second)
REVERSE_SPEED_RATIO: 0.5, // Max reverse speed as fraction of forward speed
FORWARD_ACCEL: 1.8, // Forward input acceleration (normalized units per second)
REVERSE_ACCEL: 1.2, // Reverse input acceleration (normalized units per second)
FORWARD_DECEL: 2.5, // Forward/reverse input deceleration to zero
TURN_ACCEL: 3.0, // Turn input acceleration (normalized units per second)
TURN_DECEL: 4.0, // Turn input deceleration to zero
SHOT_SPEED: 100, // BZFlag _shotSpeed default (units per second)
SHOT_RANGE: 350, // BZFlag _shotRange default (world units)
SHOT_DISTANCE: 350, // Legacy alias for client/radar code
SHOT_RELOAD_TIME: 1000, // ms; configurable independently until shot-slot behavior matches BZFlag
SHOT_COOLDOWN: 1000, // Legacy alias used by existing client fire gating
SHOT_MAX_ACTIVE: 1, // BZFlag maxShots default
SHOT_RADIUS: 0.5, // BZFlag _shotRadius default
SHOT_TAIL_LENGTH: 4.0, // BZFlag _shotTailLength default
SHOTS_KEEP_VERTICAL_VELOCITY: false, // BZFlag _shotsKeepVerticalVelocity default
MAX_SPEED_TOLERANCE: 1.5, // Allow 50% tolerance for latency
SHOT_POSITION_TOLERANCE: 2, // Max distance shot can be from claimed position
PAUSE_COUNTDOWN: 2000, // ms
JUMP_VELOCITY: 19, // BZFlag _jumpVelocity default
GRAVITY: 9.8, // BZFlag _gravity magnitude (units per second squared)
JUMP_COOLDOWN: 500, // ms between jumps
FOG_MODE: 'none', // BZFlag _fogMode default
FOG_DENSITY: 0.001, // BZFlag _fogDensity default
FOG_START: null, // Defaults to 0.5 * map size like BZFlag
FOG_END: null, // Defaults to map size like BZFlag
};
// WebSocket keep-alive configuration
const WS_PING_INTERVAL = 30000; // Send ping every 30 seconds
const WS_PONG_TIMEOUT = 60000; // Close connection if no pong after 60 seconds
// --- Map selection: load from config and maps/ directory ---
function ensureServerConfig(configPath) {
if (fs.existsSync(configPath)) {
return;
}
try {
fs.mkdirSync(path.dirname(configPath), { recursive: true });
fs.copyFileSync(EXAMPLE_CONFIG_PATH, configPath);
log(`Created default server config at ${configPath}`);
} catch (error) {
logError(`Could not create default server config at ${configPath}:`, error);
}
}
const configPath = CONFIG_PATH;
let serverConfig = {};
ensureServerConfig(configPath);
try {
serverConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch (e) {
logError('Could not load server-config.json:', e);
}
let MAP_SOURCE = serverConfig.mapFile || 'random';
let mapPath = '';
// Anti-cheat configuration
const ANTICHEAT_CONFIG = {
mode: serverConfig.antiCheat?.mode || 'strict', // 'strict', 'warning', or 'disabled'
linearDriftThreshold: serverConfig.antiCheat?.linearDriftThreshold || 3.0,
linearDriftThresholdVelocityChanged: serverConfig.antiCheat?.linearDriftThresholdVelocityChanged || 20.0,
angularDriftThreshold: serverConfig.antiCheat?.angularDriftThreshold || 0.5,
};
// Optional gameplay overrides from server-config.json
const configTankSpeed = Number(serverConfig.tankSpeed);
if (Number.isFinite(configTankSpeed) && configTankSpeed > 0) {
GAME_CONFIG.TANK_SPEED = configTankSpeed;
}
const configTankRotationSpeed = Number(serverConfig.tankRotationSpeed);
if (Number.isFinite(configTankRotationSpeed) && configTankRotationSpeed > 0) {
GAME_CONFIG.TANK_ROTATION_SPEED = configTankRotationSpeed;
}
const configReverseSpeedRatio = Number(serverConfig.reverseSpeedRatio);
if (Number.isFinite(configReverseSpeedRatio) && configReverseSpeedRatio >= 0 && configReverseSpeedRatio <= 1) {
GAME_CONFIG.REVERSE_SPEED_RATIO = configReverseSpeedRatio;
}
const configForwardAccel = Number(serverConfig.forwardAccel);
if (Number.isFinite(configForwardAccel) && configForwardAccel > 0) {
GAME_CONFIG.FORWARD_ACCEL = configForwardAccel;
}
const configReverseAccel = Number(serverConfig.reverseAccel);
if (Number.isFinite(configReverseAccel) && configReverseAccel > 0) {
GAME_CONFIG.REVERSE_ACCEL = configReverseAccel;
}
const configForwardDecel = Number(serverConfig.forwardDecel);
if (Number.isFinite(configForwardDecel) && configForwardDecel > 0) {
GAME_CONFIG.FORWARD_DECEL = configForwardDecel;
}
const configTurnAccel = Number(serverConfig.turnAccel);
if (Number.isFinite(configTurnAccel) && configTurnAccel > 0) {
GAME_CONFIG.TURN_ACCEL = configTurnAccel;
}
const configTurnDecel = Number(serverConfig.turnDecel);
if (Number.isFinite(configTurnDecel) && configTurnDecel > 0) {
GAME_CONFIG.TURN_DECEL = configTurnDecel;
}
const configJumpVelocity = Number(serverConfig.jumpVelocity);
if (Number.isFinite(configJumpVelocity) && configJumpVelocity >= 0) {
GAME_CONFIG.JUMP_VELOCITY = configJumpVelocity;
}
const configGravity = Number(serverConfig.gravity);
if (Number.isFinite(configGravity) && configGravity > 0) {
GAME_CONFIG.GRAVITY = configGravity;
}
const configShotSpeed = Number(serverConfig.shotSpeed);
if (Number.isFinite(configShotSpeed) && configShotSpeed > 0) {
GAME_CONFIG.SHOT_SPEED = configShotSpeed;
}
const configShotRange = Number(serverConfig.shotRange);
if (Number.isFinite(configShotRange) && configShotRange > 0) {
GAME_CONFIG.SHOT_RANGE = configShotRange;
}
const configShotDuration = Number(serverConfig.shotDuration);
if (Number.isFinite(configShotDuration) && configShotDuration > 0) {
GAME_CONFIG.SHOT_RANGE = GAME_CONFIG.SHOT_SPEED * configShotDuration;
}
const configShotDistance = Number(serverConfig.shotDistance);
if (Number.isFinite(configShotDistance) && configShotDistance > 0) {
GAME_CONFIG.SHOT_RANGE = configShotDistance;
}
const configShotReloadTime = Number(serverConfig.shotReloadTime);
if (Number.isFinite(configShotReloadTime) && configShotReloadTime > 0) {
GAME_CONFIG.SHOT_RELOAD_TIME = configShotReloadTime;
}
const configShotCooldown = Number(serverConfig.shotCooldown);
if (Number.isFinite(configShotCooldown) && configShotCooldown > 0) {
GAME_CONFIG.SHOT_RELOAD_TIME = configShotCooldown;
}
const configShotMaxActive = Number(serverConfig.shotMaxActive);
if (Number.isInteger(configShotMaxActive) && configShotMaxActive > 0) {
GAME_CONFIG.SHOT_MAX_ACTIVE = configShotMaxActive;
}
const configShotRadius = Number(serverConfig.shotRadius);
if (Number.isFinite(configShotRadius) && configShotRadius > 0) {
GAME_CONFIG.SHOT_RADIUS = configShotRadius;
}
const configShotTailLength = Number(serverConfig.shotTailLength);
if (Number.isFinite(configShotTailLength) && configShotTailLength >= 0) {
GAME_CONFIG.SHOT_TAIL_LENGTH = configShotTailLength;
}
if (typeof serverConfig.shotsKeepVerticalVelocity === 'boolean') {
GAME_CONFIG.SHOTS_KEEP_VERTICAL_VELOCITY = serverConfig.shotsKeepVerticalVelocity;
}
GAME_CONFIG.SHOT_DISTANCE = GAME_CONFIG.SHOT_RANGE;
GAME_CONFIG.SHOT_COOLDOWN = GAME_CONFIG.SHOT_RELOAD_TIME;
const validFogModes = new Set(['none', 'linear', 'exp', 'exp2']);
const configFogMode = typeof serverConfig.fogMode === 'string' ? serverConfig.fogMode.trim().toLowerCase() : '';
if (validFogModes.has(configFogMode)) {
GAME_CONFIG.FOG_MODE = configFogMode;
}
const configFogDensity = Number(serverConfig.fogDensity);
if (Number.isFinite(configFogDensity) && configFogDensity >= 0) {
GAME_CONFIG.FOG_DENSITY = configFogDensity;
}
const configFogStart = Number(serverConfig.fogStart);
if (Number.isFinite(configFogStart) && configFogStart >= 0) {
GAME_CONFIG.FOG_START = configFogStart;
}
const configFogEnd = Number(serverConfig.fogEnd);
if (Number.isFinite(configFogEnd) && configFogEnd >= 0) {
GAME_CONFIG.FOG_END = configFogEnd;
}
if (!Number.isFinite(GAME_CONFIG.FOG_START)) {
GAME_CONFIG.FOG_START = 0.5 * GAME_CONFIG.MAP_SIZE;
}
if (!Number.isFinite(GAME_CONFIG.FOG_END)) {
GAME_CONFIG.FOG_END = GAME_CONFIG.MAP_SIZE;
}
log(`Anti-cheat mode: ${ANTICHEAT_CONFIG.mode}`);
log(
`Gameplay config: tankSpeed=${GAME_CONFIG.TANK_SPEED}, tankRotationSpeed=${GAME_CONFIG.TANK_ROTATION_SPEED}, reverseSpeedRatio=${GAME_CONFIG.REVERSE_SPEED_RATIO}, forwardAccel=${GAME_CONFIG.FORWARD_ACCEL}, reverseAccel=${GAME_CONFIG.REVERSE_ACCEL}, forwardDecel=${GAME_CONFIG.FORWARD_DECEL}, turnAccel=${GAME_CONFIG.TURN_ACCEL}, turnDecel=${GAME_CONFIG.TURN_DECEL}, jumpVelocity=${GAME_CONFIG.JUMP_VELOCITY}, gravity=${GAME_CONFIG.GRAVITY}, shotSpeed=${GAME_CONFIG.SHOT_SPEED}, shotRange=${GAME_CONFIG.SHOT_RANGE}, shotReloadTime=${GAME_CONFIG.SHOT_RELOAD_TIME}ms, shotDuration≈${(GAME_CONFIG.SHOT_RANGE / GAME_CONFIG.SHOT_SPEED).toFixed(2)}s, shotMaxActive=${GAME_CONFIG.SHOT_MAX_ACTIVE}, shotRadius=${GAME_CONFIG.SHOT_RADIUS}, shotTailLength=${GAME_CONFIG.SHOT_TAIL_LENGTH}, shotsKeepVerticalVelocity=${GAME_CONFIG.SHOTS_KEEP_VERTICAL_VELOCITY}`
);
log(
`Fog config: mode=${GAME_CONFIG.FOG_MODE}, density=${GAME_CONFIG.FOG_DENSITY}, start=${GAME_CONFIG.FOG_START}, end=${GAME_CONFIG.FOG_END}, color=time-of-day`
);
if (MAP_SOURCE !== 'random') {
mapPath = path.join(__dirname, 'maps', MAP_SOURCE);
if (!fs.existsSync(mapPath)) {
logError(`Map file not found: ${mapPath}. Reverting to random map.`);
MAP_SOURCE = 'random';
} else {
// Watch the map file for changes and restart the server if it changes
try {
fs.watch(mapPath, (eventType, filename) => {
if (eventType === 'change' || eventType === 'rename') {
console.log(`\n📝 Map file changed: ${filename || mapPath}`);
console.log('🔄 Restarting server due to map file change...\n');
requestServerRestart('map file change');
}
});
// console.log(` ✓ Watching map file: ${path.basename(mapPath)}`);
} catch (err) {
logError(`Failed to watch map file: ${mapPath}`, err);
}
}
}
// Parse a BZW file and convert to obstacle format
function parseBZWMap(filename) {
const text = fs.readFileSync(filename, 'utf8');
const lines = text.split(/\r?\n/);
const obstacles = [];
let current = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.startsWith('world')) {
// Look ahead for size
for (let j = i + 1; j < lines.length; j++) {
const wline = lines[j].trim();
if (wline.startsWith('size')) {
const [, size] = wline.split(/\s+/);
if (size) {
GAME_CONFIG.MAP_SIZE = parseFloat(size) * 2;
}
break;
}
if (wline === 'end') break;
}
} else if (line.startsWith('box')) {
current = { type: 'box' };
} else if (line.startsWith('pyramid')) {
current = { type: 'pyramid' };
} else if (line.startsWith('base')) {
current = { type: 'box' };
} else if (line.startsWith('teleporter')) {
current = { type: 'box' };
} else if (current && line.startsWith('name')) {
// name <string>
const [, ...nameParts] = line.split(/\s+/);
const name = nameParts.join(' ').replace(/"/g, '').trim();
if (name) current.name = name;
} else if (current && line.startsWith('position')) {
// position x y z (BZFlag +Y north maps to our -Z north)
const [, x, y, z] = line.split(/\s+/);
current.x = parseFloat(x);
current.z = -parseFloat(y); // BZFlag +Y (north) -> our -Z (north)
current.baseY = parseFloat(z) || 0;
} else if (current && line.startsWith('size')) {
// size w d h (BZFlag x/y are center-to-edge half extents, z is full height)
const [, w, d, h] = line.split(/\s+/);
const rawW = parseFloat(w);
const rawD = parseFloat(d);
const rawH = parseFloat(h);
current.w = Math.abs(rawW) * 2;
current.d = Math.abs(rawD) * 2;
current.h = Math.abs(rawH);
if (current.type === 'pyramid') {
current.inverted = rawH < 0;
}
} else if (current && line.startsWith('rotation')) {
// BZFlag rotation is CCW around +Z; our world maps BZFlag +Y (north) to -Z,
// which flips the depth axis. The correct conversion is +deg + π.
const [, deg] = line.split(/\s+/);
current.rotation = (parseFloat(deg) || 0) * Math.PI / 180 + Math.PI;
} else if (current && line === 'end') {
// Use BZW name if present, otherwise assign a generated name
if (!current.name) {
current.name = `${current.type[0].toUpperCase()}${obstacles.length}`;
}
obstacles.push(current);
current = null;
}
}
return obstacles;
}
// Generate random obstacles on server start
function generateObstacles() {
const obstacles = [];
GAME_CONFIG.MAP_SIZE = 100;
const mapSize = GAME_CONFIG.MAP_SIZE;
const numBoxes = Math.floor(mapSize * mapSize / 2000 + Math.random() * 3);
const numPyramids = Math.floor(numBoxes / 2);
const minDistance = 15; // Minimum distance from center and other obstacles
// Helper to check overlap for both types
function isTooClose(x, z, w, d, others) {
for (const other of others) {
const dist = Math.sqrt(Math.pow(x - other.x, 2) + Math.pow(z - other.z, 2));
if (dist < (w + other.w) / 2 + minDistance) {
return true;
}
}
return false;
}
// Generate boxes
for (let i = 0; i < numBoxes; i++) {
let attempts = 0;
let validPosition = false;
let obstacle;
while (!validPosition && attempts < 50) {
const x = (Math.random() - 0.5) * (mapSize * 0.8);
const z = (Math.random() - 0.5) * (mapSize * 0.8);
const w = 6 + Math.random() * 6;
const d = 6 + Math.random() * 6;
const rotation = Math.random() * Math.PI * 2;
let h, baseY;
if (Math.random() < 0.6) {
h = 4 + Math.random() * 4;
baseY = 0;
} else {
h = 3 + Math.random() * 2;
baseY = 3 + Math.random() * 3;
}
obstacle = { x, z, w, d, h, baseY, rotation, name: `O${i}` , type: 'box'};
const distFromCenter = Math.sqrt(x * x + z * z);
if (distFromCenter < minDistance) {
attempts++;
continue;
}
if (isTooClose(x, z, w, d, obstacles)) {
attempts++;
continue;
}
validPosition = true;
}
if (validPosition && obstacle) {
obstacles.push(obstacle);
}
}
// Generate pyramids
for (let i = 0; i < numPyramids; i++) {
let attempts = 0;
let validPosition = false;
let pyramid;
while (!validPosition && attempts < 50) {
const x = (Math.random() - 0.5) * (mapSize * 0.8);
const z = (Math.random() - 0.5) * (mapSize * 0.8);
const w = 6 + Math.random() * 6;
const d = 6 + Math.random() * 6;
const rotation = Math.random() * Math.PI * 2;
let h, baseY;
if (Math.random() < 0.6) {
h = 4 + Math.random() * 4;
baseY = 0;
} else {
h = 3 + Math.random() * 2;
baseY = 3 + Math.random() * 3;
}
const inverted = Math.random() < 0.2; // 20% chance for random inverted pyramid
pyramid = { x, z, w, d, h, baseY, rotation, name: `P${i}` , type: 'pyramid', inverted };
const distFromCenter = Math.sqrt(x * x + z * z);
if (distFromCenter < minDistance) {
attempts++;
continue;
}
if (isTooClose(x, z, w, d, obstacles)) {
attempts++;
continue;
}
validPosition = true;
}
if (validPosition && pyramid) {
obstacles.push(pyramid);
}
}
return obstacles;
}
let OBSTACLES;
if (MAP_SOURCE === 'random') {
OBSTACLES = generateObstacles();
log(`Generated ${OBSTACLES.length} random obstacles`);
} else {
// Always look for maps in maps/ directory
const mapFilePath = path.join(__dirname, 'maps', MAP_SOURCE);
OBSTACLES = parseBZWMap(mapFilePath);
log(`Loaded ${OBSTACLES.length} obstacles from maps/${MAP_SOURCE}`);
}
log(OBSTACLES);
function getMaxObstacleTopY(obstacles = []) {
return obstacles.reduce((maxTop, obstacle) => {
const baseY = Number.isFinite(obstacle?.baseY) ? obstacle.baseY : 0;
const height = Number.isFinite(obstacle?.h) ? obstacle.h : 4;
return Math.max(maxTop, baseY + height);
}, 0);
}
function getJumpApexHeight() {
const jumpVelocity = Number.isFinite(GAME_CONFIG.JUMP_VELOCITY) ? GAME_CONFIG.JUMP_VELOCITY : 19;
const gravity = Number.isFinite(GAME_CONFIG.GRAVITY) && GAME_CONFIG.GRAVITY > 0 ? GAME_CONFIG.GRAVITY : 9.8;
return (jumpVelocity * jumpVelocity) / (2 * gravity);
}
// Generate random clouds with fractal patter.
function generateClouds(obstacles = OBSTACLES) {
const clouds = [];
const numClouds = 15;
const maxObstacleTopY = getMaxObstacleTopY(obstacles);
const jumpApexHeight = getJumpApexHeight();
const cloudBaseY = maxObstacleTopY + jumpApexHeight;
for (let i = 0; i < numClouds; i++) {
// Random position in sky
const x = (Math.random() - 0.5) * 200;
const y = cloudBaseY + Math.random() * 40;
const z = (Math.random() - 0.5) * 200;
// Fractal puffs (multiple spheres clustered together)
const puffs = [];
const numPuffs = 5 + Math.floor(Math.random() * 8);
for (let j = 0; j < numPuffs; j++) {
puffs.push({
offsetX: (Math.random() - 0.5) * 10,
offsetY: (Math.random() - 0.5) * 3,
offsetZ: (Math.random() - 0.5) * 10,
radius: 2 + Math.random() * 4
});
}
clouds.push({ x, y, z, puffs });
}
return clouds;
}
// Game state
const players = new Map();
const projectiles = new Map();
let projectileIdCounter = 0;
// Minecraft-style world time (0-23999, 20 min per day, 20 ticks/sec)
let worldTime = Math.floor(Math.random() * 24000); // randomize start
// Get next available player number
function getNextPlayerNumber() {
let num = 1;
const takenNumbers = new Set(Array.from(players.values()).map(p => p.playerNumber));
while (takenNumbers.has(num)) {
num++;
}
return num;
}
// Player class
class Player {
constructor(ws, name = null, playerNumber = null) {
this.playerNumber = playerNumber !== null ? playerNumber : getNextPlayerNumber();
this.id = this.playerNumber.toString();
this.ws = ws;
// Always assign a default name if none provided
this.name = name && name.trim() ? name : `Player ${this.playerNumber}`;
this.x = 0;
this.y = 0;
this.z = 0;
this.rotation = 0;
this.health = 0;
this.lastShot = 0;
this.lastUpdate = Date.now();
this.kills = 0;
this.deaths = 0;
this.paused = false;
this.pauseCountdownStart = 0;
this.verticalVelocity = 0;
this.isJumping = false;
this.lastJumpTime = 0;
this.onObstacle = false;
this.connectDate = new Date();
// Spread new tank colors away from currently connected players.
this.color = Player.pickDistinctColor();
this.tankModel = 'bzflag';
// Extrapolation state
this.forwardSpeed = 0;
this.rotationSpeed = 0;
this.jumpDirection = null;
this.slideDirection = undefined;
this.airVelocityX = 0;
this.airVelocityZ = 0;
// Keep-alive tracking
this.lastPongTime = Date.now();
this.isAlive = true;
// Anti-cheat tracking
this.cheatWarnings = {
linearDrift: 0,
angularDrift: 0,
totalWarnings: 0,
lastWarningTime: 0,
};
}
static colorIntToRgb(color) {
return {
r: (color >> 16) & 0xff,
g: (color >> 8) & 0xff,
b: color & 0xff
};
}
static hslToRgb(h, s, l) {
s /= 100;
l /= 100;
const k = (n) => (n + h / 30) % 12;
const a = s * Math.min(l, 1 - l);
const f = (n) => l - a * Math.max(-1, Math.min(Math.min(k(n) - 3, 9 - k(n)), 1));
return {
r: Math.round(255 * f(0)),
g: Math.round(255 * f(8)),
b: Math.round(255 * f(4))
};
}
static rgbToColorInt({ r, g, b }) {
return (r << 16) | (g << 8) | b;
}
static rgbToHsl(r, g, b) {
const rn = r / 255;
const gn = g / 255;
const bn = b / 255;
const max = Math.max(rn, gn, bn);
const min = Math.min(rn, gn, bn);
const light = (max + min) / 2;
const delta = max - min;
if (delta === 0) {
return { hue: 0, sat: 0, light: light * 100 };
}
const sat = delta / (1 - Math.abs(2 * light - 1));
let hue;
switch (max) {
case rn:
hue = 60 * (((gn - bn) / delta) % 6);
break;
case gn:
hue = 60 * ((bn - rn) / delta + 2);
break;
default:
hue = 60 * ((rn - gn) / delta + 4);
break;
}
if (hue < 0) hue += 360;
return { hue, sat: sat * 100, light: light * 100 };
}
static hueDistance(a, b) {
const diff = Math.abs(a - b) % 360;
return Math.min(diff, 360 - diff);
}
static scoreCandidateColor(candidate, existingColors) {
if (existingColors.length === 0) {
return Number.POSITIVE_INFINITY;
}
let minScore = Number.POSITIVE_INFINITY;
for (const existing of existingColors) {
const dr = candidate.rgb.r - existing.rgb.r;
const dg = candidate.rgb.g - existing.rgb.g;
const db = candidate.rgb.b - existing.rgb.b;
const rgbDistanceSq = dr * dr + dg * dg + db * db;
const hueDistance = Player.hueDistance(candidate.hue, existing.hue);
const satDistance = Math.abs(candidate.sat - existing.sat);
const lightDistance = Math.abs(candidate.light - existing.light);
const separationScore = rgbDistanceSq + hueDistance * 64 + satDistance * 12 + lightDistance * 10;
if (separationScore < minScore) {
minScore = separationScore;
}
}
return minScore;
}
// Pick a pastel-ish color that is as far as practical from current players.
static pickDistinctColor() {
const existingColors = Array.from(players.values())
.map((player) => player.color)
.filter((color) => Number.isFinite(color))
.map((color) => {
const rgb = Player.colorIntToRgb(color);
const hsl = Player.rgbToHsl(rgb.r, rgb.g, rgb.b);
return {
rgb,
hue: hsl.hue,
sat: hsl.sat,
light: hsl.light
};
});
const saturationOptions = [58, 66, 74];
const lightnessOptions = [58, 64, 70];
const hueStep = 12;
const scoredCandidates = [];
let bestScore = -1;
for (let hue = 0; hue < 360; hue += hueStep) {
for (const sat of saturationOptions) {
for (const light of lightnessOptions) {
const rgb = Player.hslToRgb(hue, sat, light);
const candidate = { hue, sat, light, rgb };
const score = Player.scoreCandidateColor(candidate, existingColors);
scoredCandidates.push({ candidate, score });
if (score > bestScore) {
bestScore = score;
}
}
}
}
if (scoredCandidates.length === 0) {
const fallbackRgb = Player.hslToRgb(Math.floor(Math.random() * 360), 66, 64);
return Player.rgbToColorInt(fallbackRgb);
}
const scoreThreshold = bestScore * 0.72;
const topCandidates = scoredCandidates
.filter(({ score }) => score >= scoreThreshold)
.sort((left, right) => right.score - left.score)
.slice(0, 28);
const chosen = topCandidates[Math.floor(Math.random() * topCandidates.length)] || scoredCandidates[0];
return Player.rgbToColorInt(chosen.candidate.rgb);
}
respawn() {
const spawnPos = findValidSpawnPosition();
this.x = spawnPos.x;
this.y = spawnPos.y;
this.z = spawnPos.z;
this.rotation = spawnPos.rotation;
this.health = 100;
this.verticalVelocity = 0;
this.isJumping = false;
this.onObstacle = false;
this.jumpDirection = null;
this.slideDirection = undefined;
this.forwardSpeed = 0;
this.rotationSpeed = 0;
this.airVelocityX = 0;
this.airVelocityZ = 0;
}
getState() {
return {
id: this.id,
name: this.name,
x: this.x,
y: this.y,
z: this.z,
rotation: this.rotation,
health: this.health,
kills: this.kills,
deaths: this.deaths,
paused: this.paused,
forwardSpeed: this.forwardSpeed,
rotationSpeed: this.rotationSpeed,
verticalVelocity: this.verticalVelocity,
jumpDirection: this.jumpDirection,
slideDirection: this.slideDirection,
airVelocityX: this.airVelocityX,
airVelocityZ: this.airVelocityZ,
connectDate: this.connectDate ? this.connectDate.toISOString() : undefined,
color: this.color,
tankModel: this.tankModel,
};
}
/**
* Get extrapolated position at a specific time based on last known state.
* @param {number} atTime - Timestamp (ms) to extrapolate to
* @returns {{x: number, y: number, z: number, r: number}}
*/
getExtrapolatedPosition(atTime) {
const dt = (atTime - this.lastUpdate) / 1000; // Convert to seconds
if (dt <= 0) return { x: this.x, y: this.y, z: this.z, r: this.rotation };
// Apply rotation
const rotSpeed = GAME_CONFIG.TANK_ROTATION_SPEED || 1.5;
const newR = this.rotation + this.rotationSpeed * rotSpeed * dt;
// Determine if player is in air based on jumpDirection
const isInAir = this.jumpDirection !== null && this.jumpDirection !== undefined;
if (isInAir) {
const hasAirVelocity = Number.isFinite(this.airVelocityX) && Number.isFinite(this.airVelocityZ);
const speed = GAME_CONFIG.TANK_SPEED || 15;
const moveDirection = this.slideDirection !== undefined ? this.slideDirection : this.jumpDirection;
const dx = hasAirVelocity ? this.airVelocityX * dt : -Math.sin(moveDirection) * this.forwardSpeed * speed * dt;
const dz = hasAirVelocity ? this.airVelocityZ * dt : -Math.cos(moveDirection) * this.forwardSpeed * speed * dt;
// Apply gravity to vertical velocity
const gravity = GAME_CONFIG.GRAVITY || 9.8;
const vv = this.verticalVelocity - gravity * dt;
const dy = (this.verticalVelocity + vv) / 2 * dt; // Average velocity over dt
return {
x: this.x + dx,
y: Math.max(0, this.y + dy), // Don't go below ground
z: this.z + dz,
r: newR
};
}
// On ground: check for circular vs straight motion
const speed = GAME_CONFIG.TANK_SPEED || 15;
const rs = this.rotationSpeed || 0;
const fs = this.forwardSpeed || 0;
// Use slide direction if present, otherwise use rotation
const moveDirection = this.slideDirection !== undefined ? this.slideDirection : this.rotation;
if (Math.abs(rs) < 0.001) {
// Straight line motion (or sliding)
const dx = -Math.sin(moveDirection) * fs * speed * dt;
const dz = -Math.cos(moveDirection) * fs * speed * dt;
return { x: this.x + dx, y: this.y, z: this.z + dz, r: newR };
} else {
// Circular arc motion
// Radius of curvature: R = |linear_velocity / angular_velocity|
const R = Math.abs((fs * speed) / (rs * rotSpeed));
// Arc angle traveled
const theta = rs * rotSpeed * dt;
// Center of circle in world space
// Forward is (-sin(r), -cos(r)), perpendicular at r - π/2
const perpAngle = this.rotation - Math.PI / 2;
const centerSign = -(rs * fs); // Negated to match correct circular motion
const cx = this.x + Math.sign(centerSign) * R * (-Math.sin(perpAngle));
const cz = this.z + Math.sign(centerSign) * R * (-Math.cos(perpAngle));
// New position rotated around center
// Negate theta for clockwise rotation (rs > 0 means turn right = clockwise)
const dx = this.x - cx;
const dz = this.z - cz;
const cosTheta = Math.cos(-theta);
const sinTheta = Math.sin(-theta);
const newDx = dx * cosTheta - dz * sinTheta;
const newDz = dx * sinTheta + dz * cosTheta;
return {
x: cx + newDx,
y: this.y,
z: cz + newDz,
r: this.rotation + theta
};
}
}
}
// Projectile class
class Projectile {
constructor(id, playerId, shotSlot, x, y, z, dirX, dirZ) {
this.id = id;
this.playerId = playerId;
this.shotSlot = shotSlot;
this.x = x;
this.y = y || 2.2; // Default height if not specified (tank height + barrel height)
this.z = z;
this.dirX = dirX;
this.dirZ = dirZ;
this.createdAt = Date.now();
this.originX = x;
this.originZ = z;
}
}
// Helper functions
// Returns a unique player name. If the given name is empty or taken, returns 'Player n' with the lowest available n.
function nameCheck(requestedName, excludeId = null) {
let name = requestedName && requestedName.trim() ? requestedName.trim() : '';
// Get the player number for excludeId
let playerNumber = null;
if (excludeId) {
const playerObj = Array.from(players.values()).find(p => p.id === excludeId);
if (playerObj) playerNumber = playerObj.playerNumber;
}
// If name is empty, assign 'Player n' for their own player number
if (name.length === 0) {
if (playerNumber !== null) {
return `Player ${playerNumber}`;
}
}
// Prevent picking a 'Player n' name unless n matches their player number
const playerNameMatch = name.match(/^Player\s*(\d+)$/i);
if (playerNameMatch) {
const n = parseInt(playerNameMatch[1], 10);
if (playerNumber === null || n !== playerNumber) {
// Not allowed to pick a Player n name unless n matches their player number
return `Player ${playerNumber !== null ? playerNumber : 1}`;
}
}
// Check if name is already taken
const nameTaken = Array.from(players.values()).some(p => p.id !== excludeId && p.name && p.name.toLowerCase() === name.toLowerCase());
if (nameTaken) {
// Assign 'Player n' for their own player number
if (playerNumber !== null) {
return `Player ${playerNumber}`;
}
}
return name;
}
function distance(x1, z1, x2, z2) {
return Math.sqrt((x2 - x1) ** 2 + (z2 - z1) ** 2);
}
function normalizeAngle(angle) {
while (angle > Math.PI) angle -= Math.PI * 2;
while (angle < -Math.PI) angle += Math.PI * 2;
return angle;
}
function getColliderLocalPoint(x, z, obs) {
const rotation = obs.rotation || 0;
const dx = x - obs.x;
const dz = z - obs.z;
const cos = Math.cos(rotation);
const sin = Math.sin(rotation);
return {
x: dx * cos - dz * sin,
z: dx * sin + dz * cos
};
}
function getBoxCollisionDistanceSquared(localX, localZ, halfW, halfD) {
const closestX = Math.max(-halfW, Math.min(localX, halfW));
const closestZ = Math.max(-halfD, Math.min(localZ, halfD));
const distX = localX - closestX;
const distZ = localZ - closestZ;
return distX * distX + distZ * distZ;
}
function getWorldBorderColliders() {
const halfMap = GAME_CONFIG.MAP_SIZE / 2;
const thickness = 4;
const boundaryHeight = 1000;
const span = GAME_CONFIG.MAP_SIZE + thickness * 2;
return [
{ type: 'box', name: 'boundary_north', collisionKind: 'boundary', infiniteHeight: true, x: 0, z: -halfMap - thickness / 2, w: span, d: thickness, h: boundaryHeight, baseY: 0, rotation: 0 },
{ type: 'box', name: 'boundary_south', collisionKind: 'boundary', infiniteHeight: true, x: 0, z: halfMap + thickness / 2, w: span, d: thickness, h: boundaryHeight, baseY: 0, rotation: 0 },
{ type: 'box', name: 'boundary_east', collisionKind: 'boundary', infiniteHeight: true, x: halfMap + thickness / 2, z: 0, w: thickness, d: span, h: boundaryHeight, baseY: 0, rotation: 0 },
{ type: 'box', name: 'boundary_west', collisionKind: 'boundary', infiniteHeight: true, x: -halfMap - thickness / 2, z: 0, w: thickness, d: span, h: boundaryHeight, baseY: 0, rotation: 0 }
];
}
function getCollisionColliders() {
return [...OBSTACLES, ...getWorldBorderColliders()];
}
function checkCollision(x, y, z, tankRadius = 2) {
for (const obs of getCollisionColliders()) {
const obstacleHeight = obs.h || 4;
const obstacleBase = obs.baseY || 0;
const obstacleTop = obstacleBase + obstacleHeight;