import { join } from "node:path"; import { WorldDatabase } from "./persistence/worldDb.js"; import { StateDatabase } from "./persistence/stateDb.js"; import { EditorService } from "./editor/service.js"; import { CharacterService } from "./characters/service.js"; import { FriendService } from "./friends/service.js"; import { StubAuth } from "./auth/stub.js"; import { Simulation } from "./simulation/simulation.js"; import { createHttpServer, repoRootFrom } from "./gateway/http.js"; import { attachGateway } from "./gateway/websocket.js"; const rootDir = repoRootFrom(import.meta.url); const dataDir = join(rootDir, "server", "data"); const port = Number(process.env.PORT ?? 8080); const worldDb = new WorldDatabase(join(dataDir, "world.sqlite")); const stateDb = new StateDatabase(join(dataDir, "state.sqlite")); const editor = new EditorService(worldDb); const characters = new CharacterService(stateDb, console); const friends = new FriendService(stateDb); const simulation = new Simulation(worldDb, stateDb); const auth = new StubAuth(); const httpServer = createHttpServer(rootDir); const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation }); let tickTimer = null; let shuttingDown = false; function scheduleTick () { if (shuttingDown) { return; } const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20))); tickTimer = setTimeout(() => { characters.processDueDeletions(Date.now(), (characterId) => simulation.despawnCharacter(characterId)); const result = simulation.step(); gateway.onTickResult(result); scheduleTick(); }, tickMs); } scheduleTick(); httpServer.listen(port, () => { console.log(`Tile MMO listening on http://localhost:${port}`); console.log(`World editor: http://localhost:${port}/editor`); }); async function shutdown (signal) { if (shuttingDown) { return; } shuttingDown = true; console.log(`Shutting down (${signal})…`); clearTimeout(tickTimer); try { await gateway.shutdown(); } catch (error) { console.error("Graceful shutdown error:", error); } worldDb.close(); stateDb.close(); await new Promise((resolve) => httpServer.close(resolve)); process.exit(0); } process.on("SIGINT", () => { void shutdown("SIGINT"); }); process.on("SIGTERM", () => { void shutdown("SIGTERM"); });