| 1 | import { join } from "node:path"; |
| 2 | import { WorldDatabase } from "./persistence/worldDb.js"; |
| 3 | import { StateDatabase } from "./persistence/stateDb.js"; |
| 4 | import { EditorService } from "./editor/service.js"; |
| 5 | import { CharacterService } from "./characters/service.js"; |
| 6 | import { StubAuth } from "./auth/stub.js"; |
| 7 | import { Simulation } from "./simulation/simulation.js"; |
| 8 | import { createHttpServer, repoRootFrom } from "./gateway/http.js"; |
| 9 | import { attachGateway } from "./gateway/websocket.js"; |
| 10 | |
| 11 | const rootDir = repoRootFrom(import.meta.url); |
| 12 | const dataDir = join(rootDir, "server", "data"); |
| 13 | const port = Number(process.env.PORT ?? 8080); |
| 14 | |
| 15 | const worldDb = new WorldDatabase(join(dataDir, "world.sqlite")); |
| 16 | const stateDb = new StateDatabase(join(dataDir, "state.sqlite")); |
| 17 | const editor = new EditorService(worldDb); |
| 18 | const characters = new CharacterService(stateDb, console); |
| 19 | const simulation = new Simulation(worldDb, stateDb); |
| 20 | const auth = new StubAuth(); |
| 21 | const httpServer = createHttpServer(rootDir); |
| 22 | const gateway = attachGateway({ httpServer, auth, stateDb, characters, editor, simulation }); |
| 23 | |
| 24 | const tickMs = Math.round(1000 / simulation.settings.simulationTickHz); |
| 25 | const tickTimer = setInterval(() => |
| 26 | { |
| 27 | characters.processDueDeletions(); |
| 28 | const result = simulation.step(); |
| 29 | gateway.onTickResult(result); |
| 30 | }, tickMs); |
| 31 | |
| 32 | httpServer.listen(port, () => |
| 33 | { |
| 34 | console.log(`Tile MMO listening on http://localhost:${port}`); |
| 35 | console.log(`World editor: http://localhost:${port}/editor`); |
| 36 | }); |
| 37 | |
| 38 | function shutdown () |
| 39 | { |
| 40 | clearInterval(tickTimer); |
| 41 | for (const session of gateway.sessions.values()) |
| 42 | { |
| 43 | if (session.characterId) |
| 44 | { simulation.despawnCharacter(session.characterId); } |
| 45 | } |
| 46 | worldDb.close(); |
| 47 | stateDb.close(); |
| 48 | httpServer.close(); |
| 49 | process.exit(0); |
| 50 | } |
| 51 | |
| 52 | process.on("SIGINT", shutdown); |
| 53 | process.on("SIGTERM", shutdown); |