| 1 | import { WebSocketServer } from "ws"; |
| 2 | import { MessageType, GAIT } from "../../../shared/protocol/constants.js"; |
| 3 | import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js"; |
| 4 | import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js"; |
| 5 | |
| 6 | let nextSessionId = 1; |
| 7 | |
| 8 | export function attachGateway ({ httpServer, auth, stateDb, characters, editor, simulation }) |
| 9 | { |
| 10 | const wss = new WebSocketServer({ server: httpServer, path: "/ws" }); |
| 11 | const sessions = new Map(); |
| 12 | |
| 13 | wss.on("connection", (socket) => |
| 14 | { |
| 15 | const identity = auth.claimIdentity(); |
| 16 | const account = stateDb.ensureAccount(identity.authSubject, identity.isAdmin, identity.email); |
| 17 | const session = { |
| 18 | id: nextSessionId++, |
| 19 | socket, |
| 20 | account, |
| 21 | authSubject: identity.authSubject, |
| 22 | characterId: null, |
| 23 | entityId: null, |
| 24 | subscribed: new Set() |
| 25 | }; |
| 26 | auth.register(session); |
| 27 | sessions.set(session.id, session); |
| 28 | send(session, { |
| 29 | type: MessageType.session, |
| 30 | accountId: account.account_id, |
| 31 | authSubject: account.auth_subject, |
| 32 | isAdmin: !!account.is_admin, |
| 33 | characters: characters.list(account.account_id) |
| 34 | }); |
| 35 | |
| 36 | socket.on("message", (raw) => |
| 37 | { |
| 38 | let message; |
| 39 | try |
| 40 | { message = JSON.parse(String(raw)); } |
| 41 | catch |
| 42 | { |
| 43 | send(session, { type: MessageType.error, message: "Invalid JSON." }); |
| 44 | return; |
| 45 | } |
| 46 | try |
| 47 | { handleMessage(session, message); } |
| 48 | catch (error) |
| 49 | { |
| 50 | send(session, { |
| 51 | type: MessageType.error, |
| 52 | message: error.userFacing ? error.message : "Request failed." |
| 53 | }); |
| 54 | } |
| 55 | }); |
| 56 | |
| 57 | socket.on("close", () => |
| 58 | { |
| 59 | leaveWorld(session); |
| 60 | auth.release(session); |
| 61 | sessions.delete(session.id); |
| 62 | }); |
| 63 | }); |
| 64 | |
| 65 | function handleMessage (session, message) |
| 66 | { |
| 67 | switch (message.type) |
| 68 | { |
| 69 | case MessageType.createCharacter: |
| 70 | characters.create(session.account, message.firstName, message.lastName, message.sex); |
| 71 | send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) }); |
| 72 | break; |
| 73 | case MessageType.selectCharacter: |
| 74 | enterWorld(session, message.characterId); |
| 75 | break; |
| 76 | case MessageType.scheduleDeleteCharacter: |
| 77 | characters.scheduleDelete(session.account, message.characterId, simulation.settings.characterDeletionDelayMs); |
| 78 | send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) }); |
| 79 | break; |
| 80 | case MessageType.cancelDeleteCharacter: |
| 81 | characters.cancelDelete(session.account, message.characterId); |
| 82 | send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) }); |
| 83 | break; |
| 84 | case MessageType.leaveWorld: |
| 85 | leaveWorld(session); |
| 86 | send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) }); |
| 87 | break; |
| 88 | case MessageType.moveTo: |
| 89 | requirePlaying(session); |
| 90 | simulation.enqueue(session.id, { |
| 91 | type: "move-to", |
| 92 | characterId: session.characterId, |
| 93 | tileX: message.tileX | 0, |
| 94 | tileY: message.tileY | 0 |
| 95 | }); |
| 96 | break; |
| 97 | case MessageType.setGait: |
| 98 | requirePlaying(session); |
| 99 | simulation.enqueue(session.id, { |
| 100 | type: "set-gait", |
| 101 | characterId: session.characterId, |
| 102 | gait: message.gait === GAIT.run ? GAIT.run : GAIT.walk |
| 103 | }); |
| 104 | break; |
| 105 | case MessageType.editorLoadChunk: |
| 106 | requireAdmin(session); |
| 107 | send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) }); |
| 108 | break; |
| 109 | case MessageType.editorSaveChunk: |
| 110 | requireAdmin(session); |
| 111 | send(session, { |
| 112 | type: MessageType.editorChunk, |
| 113 | ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject) |
| 114 | }); |
| 115 | break; |
| 116 | case MessageType.editorSaveSettings: |
| 117 | requireAdmin(session); |
| 118 | send(session, { |
| 119 | type: MessageType.editorChunk, |
| 120 | settingsSaved: editor.saveSettings(message.settings ?? {}, session.authSubject) |
| 121 | }); |
| 122 | break; |
| 123 | case MessageType.editorApplyRevision: |
| 124 | requireAdmin(session); |
| 125 | editor.applyPendingRevision(); |
| 126 | simulation.reloadWorld(); |
| 127 | for (const other of sessions.values()) |
| 128 | { |
| 129 | if (other.entityId) |
| 130 | { syncSubscriptions(other, true); } |
| 131 | } |
| 132 | broadcastStatus(); |
| 133 | break; |
| 134 | default: |
| 135 | send(session, { type: MessageType.error, message: `Unknown message ${message.type}` }); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | function enterWorld (session, characterId) |
| 140 | { |
| 141 | leaveWorld(session); |
| 142 | const character = characters.getOwned(session.account.account_id, characterId); |
| 143 | if (character.deletion_scheduled_at) |
| 144 | { |
| 145 | const error = new Error("That character is marked for deletion."); |
| 146 | error.userFacing = true; |
| 147 | throw error; |
| 148 | } |
| 149 | for (const other of sessions.values()) |
| 150 | { |
| 151 | if (other !== session && other.account.account_id === session.account.account_id && other.characterId) |
| 152 | { |
| 153 | const error = new Error("This account already has a character in the world."); |
| 154 | error.userFacing = true; |
| 155 | throw error; |
| 156 | } |
| 157 | } |
| 158 | session.characterId = character.character_id; |
| 159 | session.entityId = simulation.spawnCharacter(session.id, character); |
| 160 | const appearance = simulation.ecs.get(session.entityId, "appearance"); |
| 161 | const position = simulation.ecs.get(session.entityId, "position"); |
| 162 | const movement = simulation.ecs.get(session.entityId, "movement"); |
| 163 | send(session, { |
| 164 | type: MessageType.enterWorld, |
| 165 | entityId: session.entityId, |
| 166 | characterId: session.characterId, |
| 167 | tileX: position.tileX, |
| 168 | tileY: position.tileY, |
| 169 | gait: movement.gait, |
| 170 | sex: appearance.sex, |
| 171 | firstName: appearance.firstName, |
| 172 | lastName: appearance.lastName, |
| 173 | settings: simulation.settings, |
| 174 | worldTime: simulation.worldTime() |
| 175 | }); |
| 176 | syncSubscriptions(session, true); |
| 177 | } |
| 178 | |
| 179 | function leaveWorld (session) |
| 180 | { |
| 181 | if (session.characterId) |
| 182 | { simulation.despawnCharacter(session.characterId); } |
| 183 | session.characterId = null; |
| 184 | session.entityId = null; |
| 185 | session.subscribed.clear(); |
| 186 | } |
| 187 | |
| 188 | function syncSubscriptions (session, forceSnapshots) |
| 189 | { |
| 190 | if (!session.entityId) |
| 191 | { return; } |
| 192 | const position = simulation.ecs.get(session.entityId, "position"); |
| 193 | if (!position) |
| 194 | { return; } |
| 195 | |
| 196 | const next = new Set( |
| 197 | visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS) |
| 198 | .map((coord) => chunkKey(coord.chunkX, coord.chunkY)) |
| 199 | ); |
| 200 | for (const key of session.subscribed) |
| 201 | { |
| 202 | if (!next.has(key)) |
| 203 | { |
| 204 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 205 | send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY }); |
| 206 | } |
| 207 | } |
| 208 | const snapshots = simulation.snapshotFor(session.entityId); |
| 209 | for (const snapshot of snapshots) |
| 210 | { |
| 211 | const key = chunkKey(snapshot.chunkX, snapshot.chunkY); |
| 212 | if (forceSnapshots || !session.subscribed.has(key)) |
| 213 | { send(session, { type: MessageType.chunkSnapshot, ...snapshot }); } |
| 214 | } |
| 215 | session.subscribed = next; |
| 216 | } |
| 217 | |
| 218 | function requirePlaying (session) |
| 219 | { |
| 220 | if (!session.characterId) |
| 221 | { |
| 222 | const error = new Error("Select a character first."); |
| 223 | error.userFacing = true; |
| 224 | throw error; |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | function requireAdmin (session) |
| 229 | { |
| 230 | if (!session.account.is_admin) |
| 231 | { |
| 232 | const error = new Error("Admin only."); |
| 233 | error.userFacing = true; |
| 234 | throw error; |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | function broadcastStatus () |
| 239 | { |
| 240 | const worldTime = simulation.worldTime(); |
| 241 | for (const session of sessions.values()) |
| 242 | { |
| 243 | if (session.entityId) |
| 244 | { |
| 245 | send(session, { |
| 246 | type: MessageType.worldStatus, |
| 247 | worldTime, |
| 248 | settings: simulation.settings, |
| 249 | activeRevisionId: simulation.activeRevisionId |
| 250 | }); |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | function onTickResult (result) |
| 256 | { |
| 257 | for (const event of result.events) |
| 258 | { |
| 259 | if (event.type === "command-error") |
| 260 | { |
| 261 | const session = sessions.get(event.sessionId); |
| 262 | if (session) |
| 263 | { send(session, { type: MessageType.error, message: event.message }); } |
| 264 | continue; |
| 265 | } |
| 266 | if (event.type === "entity-move") |
| 267 | { |
| 268 | const fromKey = chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY)); |
| 269 | const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY)); |
| 270 | for (const session of sessions.values()) |
| 271 | { |
| 272 | if (!session.entityId) |
| 273 | { continue; } |
| 274 | const seesFrom = session.subscribed.has(fromKey); |
| 275 | const seesTo = session.subscribed.has(toKey); |
| 276 | if (seesTo) |
| 277 | { |
| 278 | send(session, { |
| 279 | type: MessageType.entityMove, |
| 280 | entityId: event.entityId, |
| 281 | characterId: event.characterId, |
| 282 | tileX: event.tileX, |
| 283 | tileY: event.tileY, |
| 284 | gait: event.gait |
| 285 | }); |
| 286 | } |
| 287 | else if (seesFrom) |
| 288 | { |
| 289 | send(session, { type: MessageType.entityDespawn, entityId: event.entityId }); |
| 290 | } |
| 291 | if (session.entityId === event.entityId) |
| 292 | { syncSubscriptions(session, false); } |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | if (simulation.tickIndex % simulation.settings.simulationTickHz === 0) |
| 297 | { broadcastStatus(); } |
| 298 | } |
| 299 | |
| 300 | return { sessions, onTickResult, wss }; |
| 301 | } |
| 302 | |
| 303 | function send (session, payload) |
| 304 | { |
| 305 | if (session.socket.readyState === 1) |
| 306 | { session.socket.send(JSON.stringify(payload)); } |
| 307 | } |