vice city online: the bare online core
This commit is contained in:
commit
2f98475c19
256 changed files with 144219 additions and 0 deletions
241
server/main.ts
Normal file
241
server/main.ts
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
// Free-roam game server: relays each player's state to everybody else.
|
||||
// Run: VC_KEY=<access key> bun server/main.ts
|
||||
import config from "./config.json";
|
||||
import { parseState, type PlayerState } from "./protocol";
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
// With VC_KEY set, connecting needs the key; without it the server is open (the address is the secret).
|
||||
const key = process.env.VC_KEY || "";
|
||||
|
||||
interface Client {
|
||||
id: number;
|
||||
name: string;
|
||||
state: PlayerState | null;
|
||||
lastSeen: number;
|
||||
windowStart: number;
|
||||
windowCount: number;
|
||||
owner: string; // private token from the player's browser: says whose cars are whose
|
||||
protectedUntil: number; // nobody can hurt this player until then
|
||||
passive: boolean; // cannot hurt anybody and cannot be hurt
|
||||
passiveChanged: number;
|
||||
away: boolean; // name box or pause menu open: like passive
|
||||
lastShotAt: number; // last hit this player landed: no hiding in a menu right after
|
||||
lastHitBy: number; // for the kill message
|
||||
lastHitAt: number;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
}
|
||||
|
||||
// Cars players spawned: they stay in the world, also over restarts.
|
||||
interface WorldCar {
|
||||
id: number;
|
||||
owner: string;
|
||||
ownerName: string;
|
||||
model: string;
|
||||
pos: [number, number, number];
|
||||
heading: number;
|
||||
c1: number;
|
||||
c2: number;
|
||||
driven: boolean;
|
||||
free?: boolean; // a boat at the dock: anybody can take it
|
||||
session?: boolean; // a boat somebody took: gone when that player leaves, never saved
|
||||
slot?: number;
|
||||
}
|
||||
const carsPath = join(import.meta.dir, config.carsFile);
|
||||
const cars = new Map<number, WorldCar>();
|
||||
let nextCarId = 1;
|
||||
if (existsSync(carsPath)) {
|
||||
try {
|
||||
for (const c of JSON.parse(readFileSync(carsPath, "utf8"))) { c.driven = false; cars.set(c.id, c); nextCarId = Math.max(nextCarId, c.id + 1); }
|
||||
} catch (e) { console.error("cars file unreadable, starting empty", e); }
|
||||
}
|
||||
// Old owners may be over the limit: only the newest ones stay.
|
||||
{
|
||||
const seen = new Map<string, number>();
|
||||
for (const c of [...cars.values()].sort((a, b) => b.id - a.id)) {
|
||||
const n = (seen.get(c.owner) || 0) + 1;
|
||||
seen.set(c.owner, n);
|
||||
if (n > config.carsPerOwner) cars.delete(c.id);
|
||||
}
|
||||
}
|
||||
let saveTimer: any = null;
|
||||
const saveCars = () => {
|
||||
if (saveTimer) return;
|
||||
saveTimer = setTimeout(() => { saveTimer = null; writeFileSync(carsPath, JSON.stringify([...cars.values()].filter((x) => !x.free && !x.session))); }, 2000);
|
||||
};
|
||||
const carFor = (car: WorldCar, c: Client) => {
|
||||
const { owner, ...pub } = car;
|
||||
return { ...pub, mine: !car.free && owner === c.owner };
|
||||
};
|
||||
const sendCar = (car: WorldCar, t: string) => {
|
||||
for (const [id, ws] of sockets) { const o = clients.get(id); if (o) send(ws, { t, car: carFor(car, o) }); }
|
||||
};
|
||||
// The dock: every slot always holds a boat; a taken one is replaced after a moment.
|
||||
const dockBoat = (slot: number) => {
|
||||
const s = config.dock.slots[slot];
|
||||
const car: WorldCar = { id: nextCarId++, owner: "", ownerName: "", model: config.dock.models[slot % config.dock.models.length], pos: s.pos as [number, number, number],
|
||||
heading: s.heading, c1: Math.floor(Math.random() * config.carColours), c2: Math.floor(Math.random() * config.carColours), driven: false, free: true, slot };
|
||||
cars.set(car.id, car);
|
||||
return car;
|
||||
};
|
||||
const removeCar = (car: WorldCar) => { cars.delete(car.id); broadcast({ t: "carRemove", id: car.id }); };
|
||||
const num3 = (v: any) => Array.isArray(v) && v.length === 3 && v.every(Number.isFinite);
|
||||
const validModel = (m: unknown) => typeof m === "string" && /^[a-z0-9_]{1,16}$/.test(m);
|
||||
|
||||
const clients = new Map<number, Client>();
|
||||
const sockets = new Map<number, any>();
|
||||
let nextId = 1;
|
||||
|
||||
const send = (ws: any, msg: object) => ws.send(JSON.stringify(msg));
|
||||
const broadcast = (msg: object, except?: number) => {
|
||||
const text = JSON.stringify(msg);
|
||||
for (const [id, ws] of sockets) if (id !== except) ws.send(text);
|
||||
};
|
||||
const cleanName = (n: unknown) =>
|
||||
(typeof n === "string" ? n : "").replace(/[^\x20-\x7e]/g, "").trim().slice(0, config.maxNameLength) || "Player";
|
||||
|
||||
const server = Bun.serve({
|
||||
port: config.port,
|
||||
hostname: config.host,
|
||||
fetch(req, srv) {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === "/health") return new Response(JSON.stringify({ ok: true, players: clients.size }));
|
||||
// The key comes from the entry link (?key=) or from the cookie the web server sets after it.
|
||||
const cookieKey = /(?:^|;\s*)vcgate=([^;]+)/.exec(req.headers.get("cookie") ?? "")?.[1];
|
||||
const given = url.searchParams.get("key") ?? cookieKey;
|
||||
if (url.pathname !== "/ws" || (key && given !== key)) return new Response("not found", { status: 404 });
|
||||
if (clients.size >= config.maxPlayers) return new Response("full", { status: 503 });
|
||||
return srv.upgrade(req, { data: {} }) ? undefined : new Response("upgrade failed", { status: 400 });
|
||||
},
|
||||
websocket: {
|
||||
maxPayloadLength: config.maxMessageBytes,
|
||||
open(ws) {
|
||||
const id = nextId++;
|
||||
(ws.data as any).id = id;
|
||||
clients.set(id, { id, name: "Player", state: null, lastSeen: Date.now(), windowStart: Date.now(), windowCount: 0,
|
||||
owner: "", protectedUntil: Date.now() + config.spawnProtectionSeconds * 1000, passive: false, passiveChanged: 0, away: false, lastShotAt: 0, lastHitBy: 0, lastHitAt: 0, kills: 0, deaths: 0 });
|
||||
sockets.set(id, ws);
|
||||
send(ws, { t: "welcome", id, tickHz: config.tickHz, max: config.maxPlayers });
|
||||
},
|
||||
message(ws, raw) {
|
||||
const c = clients.get((ws.data as any).id);
|
||||
if (!c || typeof raw !== "string") return;
|
||||
const now = Date.now();
|
||||
if (now - c.windowStart > 1000) { c.windowStart = now; c.windowCount = 0; }
|
||||
if (++c.windowCount > config.maxMessagesPerSecond) return;
|
||||
c.lastSeen = now;
|
||||
let m: any;
|
||||
try { m = JSON.parse(raw); } catch { return; }
|
||||
if (m.t === "hello") {
|
||||
const first = c.name === "Player" && !c.state;
|
||||
c.name = cleanName(m.name);
|
||||
if (typeof m.owner === "string" && /^[a-f0-9]{16,64}$/.test(m.owner)) c.owner = m.owner;
|
||||
for (const car of cars.values()) if (car.owner === c.owner && c.owner) car.ownerName = c.name;
|
||||
send(ws, { t: "cars", cars: [...cars.values()].map((car) => carFor(car, c)) });
|
||||
if (first) broadcast({ t: "join", id: c.id, name: c.name }, c.id);
|
||||
} else if (m.t === "away") {
|
||||
if (m.on && now - c.lastShotAt < config.fightLockSeconds * 1000) { c.away = false; send(ws, { t: "away", on: false, wait: true }); return; }
|
||||
c.away = !!m.on;
|
||||
send(ws, { t: "away", on: c.away });
|
||||
} else if (m.t === "marker" && Number.isFinite(m.x) && Number.isFinite(m.y)) {
|
||||
console.log(`marker ${c.name} x=${m.x} y=${m.y}` + (Number.isFinite(m.z) ? ` z=${m.z} heading=${m.heading}` : ""));
|
||||
} else if (m.t === "ping" && typeof m.n === "number") {
|
||||
send(ws, { t: "pong", n: m.n });
|
||||
} else if (m.t === "s") {
|
||||
const s = parseState(m);
|
||||
if (s) c.state = s;
|
||||
} else if (m.t === "hit" && Number.isFinite(m.target) && Number.isFinite(m.damage) && Number.isFinite(m.weapon)) {
|
||||
const v = clients.get(m.target), vs = sockets.get(m.target);
|
||||
if (!v || !vs || v === c || c.passive || v.passive || c.away || v.away || now < v.protectedUntil) return;
|
||||
c.lastShotAt = now;
|
||||
if (c.state && v.state) {
|
||||
const a: any = c.state, b: any = v.state;
|
||||
if (Array.isArray(a.pos) && Array.isArray(b.pos) && Math.hypot(a.pos[0] - b.pos[0], a.pos[1] - b.pos[1]) > config.maxHitDistance) return;
|
||||
}
|
||||
v.lastHitBy = c.id; v.lastHitAt = now;
|
||||
send(vs, { t: "dmg", amount: Math.min(Math.max(m.damage, 0), config.maxHitDamage), weapon: m.weapon, from: c.id });
|
||||
} else if (m.t === "died") {
|
||||
c.deaths++;
|
||||
const k = now - c.lastHitAt < config.killCreditSeconds * 1000 ? clients.get(c.lastHitBy) : undefined;
|
||||
if (k) k.kills++;
|
||||
broadcast({ t: "kill", victim: c.name, killer: k?.name ?? "", kills: k?.kills ?? 0, killerId: k?.id ?? 0 });
|
||||
} else if (m.t === "spawned") {
|
||||
c.protectedUntil = now + config.spawnProtectionSeconds * 1000;
|
||||
send(ws, { t: "protected", seconds: config.spawnProtectionSeconds });
|
||||
} else if (m.t === "passive") {
|
||||
if (now - c.passiveChanged < config.passiveCooldownSeconds * 1000) { send(ws, { t: "passive", on: c.passive, wait: true }); return; }
|
||||
c.passive = !c.passive; c.passiveChanged = now;
|
||||
send(ws, { t: "passive", on: c.passive });
|
||||
} else if (m.t === "spawncar" && validModel(m.model) && num3(m.pos) && Number.isFinite(m.heading) && c.owner) {
|
||||
const mine = [...cars.values()].filter((x) => x.owner === c.owner && !x.session);
|
||||
while (mine.length >= config.carsPerOwner) {
|
||||
const old = mine.shift()!;
|
||||
if (old.driven) continue;
|
||||
cars.delete(old.id);
|
||||
broadcast({ t: "carRemove", id: old.id });
|
||||
}
|
||||
// The world holds a limited number of cars: the oldest parked one goes first.
|
||||
for (const old of [...cars.values()]) {
|
||||
if (cars.size < config.maxWorldCars) break;
|
||||
if (old.driven || old.free || old.session) continue;
|
||||
cars.delete(old.id);
|
||||
broadcast({ t: "carRemove", id: old.id });
|
||||
}
|
||||
const car: WorldCar = { id: nextCarId++, owner: c.owner, ownerName: c.name, model: m.model, pos: m.pos, heading: m.heading,
|
||||
c1: Math.floor(Math.random() * config.carColours), c2: Math.floor(Math.random() * config.carColours), driven: false };
|
||||
cars.set(car.id, car);
|
||||
sendCar(car, "carAdd");
|
||||
saveCars();
|
||||
} else if (m.t === "park" && Number.isFinite(m.id) && num3(m.pos) && Number.isFinite(m.heading)) {
|
||||
const car = cars.get(m.id);
|
||||
if (!car || car.owner !== c.owner) return;
|
||||
car.pos = m.pos; car.heading = m.heading; car.driven = !!m.driven;
|
||||
sendCar(car, "carAdd");
|
||||
saveCars();
|
||||
} else if (m.t === "take" && Number.isFinite(m.id) && c.owner) {
|
||||
const car = cars.get(m.id);
|
||||
if (!car || !car.free) return;
|
||||
const slot = car.slot!;
|
||||
const held = [...cars.values()].filter((x) => x.session && x.owner === c.owner);
|
||||
while (held.length >= config.dock.boatsPerPlayer) { const old = held.shift()!; if (!old.driven) removeCar(old); }
|
||||
car.free = false; car.session = true; car.owner = c.owner; car.ownerName = c.name; delete car.slot;
|
||||
sendCar(car, "carAdd");
|
||||
setTimeout(() => sendCar(dockBoat(slot), "carAdd"), config.dock.refillSeconds * 1000);
|
||||
} else if (m.t === "chat" && typeof m.text === "string") {
|
||||
const text = m.text.replace(/[^\x20-\x7e]/g, "").trim().slice(0, 120);
|
||||
if (text) broadcast({ t: "chat", id: c.id, name: c.name, text });
|
||||
}
|
||||
},
|
||||
close(ws) {
|
||||
const id = (ws.data as any).id;
|
||||
const gone = clients.get(id);
|
||||
clients.delete(id);
|
||||
sockets.delete(id);
|
||||
// A car its owner was driving when the connection ended stays where it was last parked.
|
||||
if (gone && gone.owner) for (const car of [...cars.values()]) {
|
||||
if (car.owner !== gone.owner) continue;
|
||||
if (car.session) removeCar(car);
|
||||
else if (car.driven) { car.driven = false; sendCar(car, "carAdd"); }
|
||||
}
|
||||
broadcast({ t: "leave", id });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// One snapshot per tick: for every player, everybody else's last known state.
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [id, c] of clients) {
|
||||
if (now - c.lastSeen > config.idleTimeoutSeconds * 1000) sockets.get(id)?.close();
|
||||
}
|
||||
for (const [id, ws] of sockets) {
|
||||
const p = [];
|
||||
for (const [oid, o] of clients) if (oid !== id && o.state) p.push({ id: oid, name: o.name, ...o.state });
|
||||
send(ws, { t: "snap", p });
|
||||
}
|
||||
}, 1000 / config.tickHz);
|
||||
|
||||
config.dock.slots.forEach((_, i) => dockBoat(i));
|
||||
|
||||
console.log(`vc-online server on :${server.port}`);
|
||||
Loading…
Add table
Add a link
Reference in a new issue