This commit is contained in:
Andras Schmelczer 2026-08-22 20:59:46 +01:00
commit 98c4d63756
8 changed files with 155 additions and 223 deletions

View file

@ -1,5 +1,6 @@
import { PhysicalContainer } from './physics/containers/physical-container';
import { Server, Socket } from 'socket.io';
import { randomUUID } from 'node:crypto';
import {
TransportEvents,
deserialize,
@ -19,7 +20,7 @@ import {
} from 'shared';
import { createWorld } from './create-world';
import { Options } from './options';
import { PlayerContainer } from './players/player-container';
import { CarriedScore, PlayerContainer } from './players/player-container';
import { ServerFullError } from './players/server-full-error';
import { Player } from './players/player';
import { StepCommand, GeneratePointsCommand, AnnounceCommand } from './commands/commands';
@ -29,7 +30,7 @@ const gameStateSubscribedRoom = 'gameStateSubscribedRoom';
export class GameServer extends CommandReceiver {
private objects!: PhysicalContainer;
private players!: PlayerContainer;
private lastPhysicsBase: [number, number] = process.hrtime();
private lastPhysicsBase = process.hrtime.bigint();
private bluePoints = 0;
private redPoints = 0;
@ -50,7 +51,7 @@ export class GameServer extends CommandReceiver {
this.options.playerLimit,
this.options.npcCount,
);
this.lastPhysicsBase = process.hrtime();
this.lastPhysicsBase = process.hrtime.bigint();
this.bluePoints = 0;
this.redPoints = 0;
this.matchPointAnnounced = {};
@ -85,7 +86,10 @@ export class GameServer extends CommandReceiver {
});
}
private readonly joinedSockets = new Map<Socket, Player>();
private readonly joinedSockets = new Map<
Socket,
{ player: Player; release: () => void }
>();
private handleJoin(socket: Socket, playerInfo: PlayerInformation) {
if (this.joinedSockets.has(socket)) {
@ -98,6 +102,11 @@ export class GameServer extends CommandReceiver {
return;
}
// A reconnect arrives seconds after the drop, long before engine.io times
// the dead socket out. Retire that ghost first so its slot, team and score
// go back to the returning client.
const carried = this.retireGhost(playerInfo.reconnectToken);
if (this.players.isFull) {
socket.emit(TransportEvents.JoinRejected, JoinRejectionReason.ServerFull);
return;
@ -105,7 +114,7 @@ export class GameServer extends CommandReceiver {
let player: Player;
try {
player = this.players.createPlayer(playerInfo, socket);
player = this.players.createPlayer(playerInfo, socket, carried);
} catch (e) {
console.error('Failed to register joining player', e);
socket.emit(
@ -134,31 +143,22 @@ export class GameServer extends CommandReceiver {
};
const onDisconnect = () => {
const p = this.joinedSockets.get(socket);
this.joinedSockets.delete(socket);
this.inboundBudget.delete(socket);
if (!p) {
return;
}
p.detachFromSocket();
const { kills, deaths } = player.scoreSnapshot;
this.players.reserveScore(
player.reconnectToken,
player.team,
kills,
deaths,
Date.now(),
);
player.destroy();
this.players.deletePlayer(player);
this.removeJoined(socket);
this.sendServerStateUpdate();
};
socket.on(TransportEvents.PlayerToServer, onPlayerToServer);
socket.on('disconnect', onDisconnect);
this.joinedSockets.set(socket, player);
this.joinedSockets.set(socket, {
player,
release: () => {
socket.off(TransportEvents.PlayerToServer, onPlayerToServer);
socket.off('disconnect', onDisconnect);
player.detachFromSocket();
},
});
player.reconnectToken = this.players.issueToken();
player.reconnectToken = randomUUID();
socket.emit(TransportEvents.PlayerJoined, player.reconnectToken);
this.sendServerStateUpdate();
@ -188,11 +188,36 @@ export class GameServer extends CommandReceiver {
return true;
}
private releaseJoinedSockets() {
for (const [socket, player] of this.joinedSockets) {
socket.removeAllListeners();
player.detachFromSocket();
private retireGhost(token?: string): CarriedScore | undefined {
if (!token) {
return undefined;
}
for (const [socket, { player }] of this.joinedSockets) {
if (player.reconnectToken === token) {
const carried = { team: player.team, ...player.scoreSnapshot };
this.removeJoined(socket);
return carried;
}
}
return undefined;
}
private removeJoined(socket: Socket) {
const joined = this.joinedSockets.get(socket);
if (!joined) {
return;
}
this.joinedSockets.delete(socket);
this.inboundBudget.delete(socket);
// Only the listeners this join added: socket.io keeps its own internal
// 'error' guard and the connection-scoped PlayerJoining handler here.
joined.release();
joined.player.destroy();
this.players.deletePlayer(joined.player);
}
private releaseJoinedSockets() {
this.joinedSockets.forEach(({ release }) => release());
this.joinedSockets.clear();
this.inboundBudget.clear();
}
@ -255,9 +280,9 @@ export class GameServer extends CommandReceiver {
private saturatedFrames = 0;
private handlePhysics() {
const now = process.hrtime(this.lastPhysicsBase);
const delta = now[0] + now[1] / 1e9;
this.lastPhysicsBase = process.hrtime();
const frameStart = process.hrtime.bigint();
const delta = Number(frameStart - this.lastPhysicsBase) / 1e9;
this.lastPhysicsBase = frameStart;
if (Date.now() - this.statReportMs > 30000) {
this.statReportMs = Date.now();
@ -317,13 +342,9 @@ export class GameServer extends CommandReceiver {
this.players.stepCommunication(delta);
this.objects.resetRemoteCalls();
const elapsed = process.hrtime(now);
const physicsDelta = elapsed[0] + elapsed[1] / 1e9;
const elapsed = Number(process.hrtime.bigint() - frameStart) / 1e9;
setTimeout(
this.handlePhysics.bind(this),
Math.max(0, fixedDelta - physicsDelta) * 1000,
);
setTimeout(this.handlePhysics.bind(this), Math.max(0, fixedDelta - elapsed) * 1000);
}
public get serverInfo(): ServerInformation {

View file

@ -249,7 +249,7 @@ export class CharacterPhysical extends CharacterBase implements DynamicPhysical
}
}
public shootTowards(position: vec2, charge = 0, catchUpSeconds = 0) {
public shootTowards(position: vec2, charge = 0) {
if (
!this.isAlive ||
this.timeSinceLastShot < settings.projectileCreationInterval ||
@ -295,7 +295,6 @@ export class CharacterPhysical extends CharacterBase implements DynamicPhysical
c,
);
this.container.addObject(projectile);
projectile.fastForward(catchUpSeconds);
if (c > 0) {
vec2.scaleAndAdd(

View file

@ -175,24 +175,8 @@ export class PlanetPhysical extends PlanetBase implements StaticPhysical {
}
}
private get flipTeam(): CharacterTeam {
const control = this.ownership - 0.5;
const enter = settings.planetControlThreshold + settings.planetFlipHysteresis;
if (control > enter) {
return CharacterTeam.red;
}
if (control < -enter) {
return CharacterTeam.blue;
}
if (Math.abs(control) < settings.planetControlThreshold) {
return CharacterTeam.neutral;
}
return this.lastTeam;
}
private detectFlip(game: CommandReceiver) {
const currentTeam = this.flipTeam;
const currentTeam = this.team;
if (currentTeam === this.lastTeam) {
return;
}

View file

@ -82,25 +82,6 @@ export class ProjectilePhysical extends ProjectileBase implements DynamicPhysica
wasCollision = hitSurface;
this.object.syncBoundingBox();
}
vec2.add(this.center, this.center, delta);
vec2.add(this.center, this.center, delta);
this.object.syncBoundingBox();
}
/**
* Lag compensation: runs the projectile forward by the time its command spent
* travelling to the server. Capped by settings.maxProjectileCatchUpSeconds so
* a forged timestamp cannot spawn a shot arbitrarily far downrange.
*/
public fastForward(seconds: number) {
const step = settings.targetPhysicsDeltaTimeInSeconds;
let remaining = Math.min(Math.max(seconds, 0), settings.maxProjectileCatchUpSeconds);
while (remaining > 0 && this.isAlive) {
const delta = Math.min(step, remaining);
this.advance(delta);
remaining -= delta;
}
}
// Live view of the circle's box, not a snapshot — the circle keeps it in sync

View file

@ -9,10 +9,10 @@ export class BoundingBoxList {
}
public remove(object: DynamicPhysical) {
this.objects.splice(
this.objects.findIndex((i) => i === object),
1,
);
const index = this.objects.indexOf(object);
if (index >= 0) {
this.objects.splice(index, 1);
}
}
public forEach(func: (object: DynamicPhysical) => unknown) {

View file

@ -8,10 +8,10 @@ import {
settings,
sanitizeName,
boundRadius,
evaluateSdf,
} from 'shared';
import { PhysicalContainer } from '../physics/containers/physical-container';
import { getBoundingBoxOfCircle } from '../physics/functions/get-bounding-box-of-circle';
import { evaluateSdf } from 'shared';
import { CharacterPhysical } from '../objects/character-physical';
import { PlanetPhysical } from '../objects/planet-physical';
import { PlayerContainer } from './player-container';

View file

@ -5,21 +5,18 @@ import { NPC } from './npc';
import { Player } from './player';
import { PlayerBase } from './player-base';
import { ServerFullError } from './server-full-error';
import { randomUUID } from 'node:crypto';
// Score held for a dropped player so a reconnect inside the grace window
// resumes the match instead of starting from zero.
interface ReservedScore {
// Team and score carried over from the connection a reconnecting client is
// replacing, so it resumes the match instead of starting from zero.
export interface CarriedScore {
team: CharacterTeam;
kills: number;
deaths: number;
expiresAtMs: number;
}
export class PlayerContainer {
private _players: Array<Player> = [];
private _npcs: Array<NPC> = [];
private reservedScores = new Map<string, ReservedScore>();
constructor(
private readonly objects: PhysicalContainer,
@ -42,80 +39,34 @@ export class PlayerContainer {
}
}
public createPlayer(playerInfo: PlayerInformation, socket: Socket): Player {
public createPlayer(
playerInfo: PlayerInformation,
socket: Socket,
carried?: CarriedScore,
): Player {
if (this._players.length >= this.playerMaxCount) {
throw new ServerFullError();
}
const reserved = this.claimReservedScore(playerInfo.reconnectToken);
const team = reserved ? reserved.team : this.getTeamOfNextPlayer();
const team = carried ? carried.team : this.getTeamOfNextPlayer();
const player = new Player(playerInfo, this, this.objects, team, socket);
let npcToReplace = this._npcs.find((n) => n.team === team);
if (!npcToReplace) {
npcToReplace = this._npcs.find((n) => n.team !== team);
}
// Retire the bot before the player spawns: its body would otherwise push
// the spawn search away from the position it picked.
const npcToReplace =
this._npcs.find((n) => n.team === team) ?? this._npcs.find((n) => n.team !== team);
npcToReplace?.destroy();
this._npcs = this._npcs.filter((n) => n !== npcToReplace);
const player = new Player(playerInfo, this, this.objects, team, socket);
this._players.push(player);
if (reserved) {
player.restoreScore(reserved.kills, reserved.deaths);
if (carried) {
player.restoreScore(carried.kills, carried.deaths);
}
return player;
}
/**
* A fresh token for a joining player; only redeemable once the player
* actually drops (see reserveScore).
*/
public issueToken(): string {
return randomUUID();
}
/**
* Hold a dropped player's team and score against its token for the grace
* window, so a reconnecting client rejoins as itself.
*/
public reserveScore(
token: string,
team: CharacterTeam,
kills: number,
deaths: number,
nowMs: number,
) {
this.expireReservations(nowMs);
this.reservedScores.set(token, {
team,
kills,
deaths,
expiresAtMs: nowMs + settings.reconnectGraceSeconds * 1000,
});
}
private claimReservedScore(token?: string): ReservedScore | undefined {
if (!token || typeof token !== 'string') {
return undefined;
}
const reserved = this.reservedScores.get(token);
if (!reserved) {
return undefined;
}
this.reservedScores.delete(token);
return reserved;
}
private expireReservations(nowMs: number) {
for (const [token, reserved] of this.reservedScores) {
if (reserved.expiresAtMs <= nowMs) {
this.reservedScores.delete(token);
}
}
}
public get players(): Array<PlayerBase> {
return [...this._players, ...this._npcs];
}

View file

@ -92,11 +92,7 @@ export class Player extends PlayerBase {
return;
}
this.observeClientTime(c.clientTimeMs);
this.character?.shootTowards(
position,
finiteInRange(c.charge, 0, 1, 0),
this.catchUpSeconds,
);
this.character?.shootTowards(position, finiteInRange(c.charge, 0, 1, 0));
},
[LeapActionCommand.type]: (c: LeapActionCommand) => {
if (!isFiniteNumber(c.clientTimeMs)) {
@ -125,12 +121,6 @@ export class Player extends PlayerBase {
}
}
// Derived from the measured RTT, NOT the client's timestamp, so a forged
// stamp cannot buy extra lag compensation. fastForward caps the result.
private get catchUpSeconds(): number {
return Math.max(0, this.rttMs / 2 / 1000);
}
constructor(
playerInfo: PlayerInformation,
playerContainer: PlayerContainer,