BlueGit

timfa questward

Files

questward / server / src / index.js

index.js

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