| 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, friends, 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.friendRequest: |
| 106 | requirePlaying(session); |
| 107 | friends.request(session.characterId, message.characterId); |
| 108 | pushFriends(session.characterId, message.characterId); |
| 109 | break; |
| 110 | case MessageType.friendAccept: |
| 111 | requirePlaying(session); |
| 112 | friends.accept(session.characterId, message.characterId); |
| 113 | pushFriends(session.characterId, message.characterId); |
| 114 | break; |
| 115 | case MessageType.friendDecline: |
| 116 | requirePlaying(session); |
| 117 | friends.decline(session.characterId, message.characterId); |
| 118 | pushFriends(session.characterId, message.characterId); |
| 119 | break; |
| 120 | case MessageType.friendRemove: |
| 121 | requirePlaying(session); |
| 122 | friends.remove(session.characterId, message.characterId); |
| 123 | pushFriends(session.characterId, message.characterId); |
| 124 | break; |
| 125 | case MessageType.editorLoadChunk: |
| 126 | requireAdmin(session); |
| 127 | send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) }); |
| 128 | break; |
| 129 | case MessageType.editorSaveChunk: |
| 130 | requireAdmin(session); |
| 131 | send(session, { |
| 132 | type: MessageType.editorChunk, |
| 133 | ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject) |
| 134 | }); |
| 135 | break; |
| 136 | case MessageType.editorLoadSettings: |
| 137 | requireAdmin(session); |
| 138 | send(session, { type: MessageType.editorSettings, ...editor.loadSettings() }); |
| 139 | break; |
| 140 | case MessageType.editorSaveSettings: |
| 141 | requireAdmin(session); |
| 142 | { |
| 143 | const saved = editor.saveSettings(message.settings ?? {}, session.authSubject); |
| 144 | simulation.applySettings(saved.settings); |
| 145 | broadcastStatus(); |
| 146 | broadcastSettings(saved); |
| 147 | } |
| 148 | break; |
| 149 | case MessageType.editorApplyRevision: |
| 150 | requireAdmin(session); |
| 151 | editor.applyPendingRevision(); |
| 152 | simulation.reloadWorld(); |
| 153 | for (const other of sessions.values()) |
| 154 | { |
| 155 | if (other.entityId) |
| 156 | { syncSubscriptions(other, true); } |
| 157 | } |
| 158 | broadcastStatus(); |
| 159 | break; |
| 160 | default: |
| 161 | send(session, { type: MessageType.error, message: `Unknown message ${message.type}` }); |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | function enterWorld (session, characterId) |
| 166 | { |
| 167 | leaveWorld(session); |
| 168 | const character = characters.getOwned(session.account.account_id, characterId); |
| 169 | if (character.deletion_scheduled_at) |
| 170 | { |
| 171 | const error = new Error("That character is marked for deletion."); |
| 172 | error.userFacing = true; |
| 173 | throw error; |
| 174 | } |
| 175 | for (const other of sessions.values()) |
| 176 | { |
| 177 | if (other !== session && other.account.account_id === session.account.account_id && other.characterId) |
| 178 | { |
| 179 | const error = new Error("This account already has a character in the world."); |
| 180 | error.userFacing = true; |
| 181 | throw error; |
| 182 | } |
| 183 | } |
| 184 | session.characterId = character.character_id; |
| 185 | session.entityId = simulation.spawnCharacter(session.id, character); |
| 186 | const appearance = simulation.ecs.get(session.entityId, "appearance"); |
| 187 | const position = simulation.ecs.get(session.entityId, "position"); |
| 188 | const movement = simulation.ecs.get(session.entityId, "movement"); |
| 189 | send(session, { |
| 190 | type: MessageType.enterWorld, |
| 191 | entityId: session.entityId, |
| 192 | characterId: session.characterId, |
| 193 | tileX: position.tileX, |
| 194 | tileY: position.tileY, |
| 195 | gait: movement.gait, |
| 196 | sex: appearance.sex, |
| 197 | firstName: appearance.firstName, |
| 198 | lastName: appearance.lastName, |
| 199 | settings: simulation.settings, |
| 200 | worldTime: simulation.worldTime() |
| 201 | }); |
| 202 | syncSubscriptions(session, true); |
| 203 | send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) }); |
| 204 | } |
| 205 | |
| 206 | function leaveWorld (session) |
| 207 | { |
| 208 | if (session.characterId) |
| 209 | { simulation.despawnCharacter(session.characterId); } |
| 210 | session.characterId = null; |
| 211 | session.entityId = null; |
| 212 | session.subscribed.clear(); |
| 213 | } |
| 214 | |
| 215 | function syncSubscriptions (session, forceSnapshots) |
| 216 | { |
| 217 | if (!session.entityId) |
| 218 | { return; } |
| 219 | const position = simulation.ecs.get(session.entityId, "position"); |
| 220 | if (!position) |
| 221 | { return; } |
| 222 | |
| 223 | const next = new Set( |
| 224 | visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS) |
| 225 | .map((coord) => chunkKey(coord.chunkX, coord.chunkY)) |
| 226 | ); |
| 227 | for (const key of session.subscribed) |
| 228 | { |
| 229 | if (!next.has(key)) |
| 230 | { |
| 231 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 232 | send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY }); |
| 233 | } |
| 234 | } |
| 235 | const snapshots = simulation.snapshotFor(session.entityId); |
| 236 | for (const snapshot of snapshots) |
| 237 | { |
| 238 | const key = chunkKey(snapshot.chunkX, snapshot.chunkY); |
| 239 | if (forceSnapshots || !session.subscribed.has(key)) |
| 240 | { send(session, { type: MessageType.chunkSnapshot, ...snapshot }); } |
| 241 | } |
| 242 | session.subscribed = next; |
| 243 | } |
| 244 | |
| 245 | function requirePlaying (session) |
| 246 | { |
| 247 | if (!session.characterId) |
| 248 | { |
| 249 | const error = new Error("Select a character first."); |
| 250 | error.userFacing = true; |
| 251 | throw error; |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | function requireAdmin (session) |
| 256 | { |
| 257 | if (!session.account.is_admin) |
| 258 | { |
| 259 | const error = new Error("Admin only."); |
| 260 | error.userFacing = true; |
| 261 | throw error; |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | function broadcastStatus () |
| 266 | { |
| 267 | const worldTime = simulation.worldTime(); |
| 268 | for (const session of sessions.values()) |
| 269 | { |
| 270 | if (session.entityId) |
| 271 | { |
| 272 | send(session, { |
| 273 | type: MessageType.worldStatus, |
| 274 | worldTime, |
| 275 | settings: simulation.settings, |
| 276 | activeRevisionId: simulation.activeRevisionId |
| 277 | }); |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | function pushFriends (...characterIds) |
| 283 | { |
| 284 | const seen = new Set(); |
| 285 | for (const characterId of characterIds) |
| 286 | { |
| 287 | const id = Number(characterId); |
| 288 | if (!id || seen.has(id)) |
| 289 | { continue; } |
| 290 | seen.add(id); |
| 291 | const payload = { type: MessageType.friends, ...friends.snapshot(id) }; |
| 292 | for (const session of sessions.values()) |
| 293 | { |
| 294 | if (session.characterId === id) |
| 295 | { send(session, payload); } |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | function broadcastSettings (payload) |
| 301 | { |
| 302 | for (const session of sessions.values()) |
| 303 | { |
| 304 | if (session.account.is_admin) |
| 305 | { send(session, { type: MessageType.editorSettings, ...payload }); } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | function onTickResult (result) |
| 310 | { |
| 311 | for (const event of result.events) |
| 312 | { |
| 313 | if (event.type === "command-error") |
| 314 | { |
| 315 | const session = sessions.get(event.sessionId); |
| 316 | if (session) |
| 317 | { send(session, { type: MessageType.error, message: event.message }); } |
| 318 | continue; |
| 319 | } |
| 320 | if (event.type === "entity-move") |
| 321 | { |
| 322 | const fromKey = chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY)); |
| 323 | const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY)); |
| 324 | for (const session of sessions.values()) |
| 325 | { |
| 326 | if (!session.entityId) |
| 327 | { continue; } |
| 328 | const seesFrom = session.subscribed.has(fromKey); |
| 329 | const seesTo = session.subscribed.has(toKey); |
| 330 | if (seesTo) |
| 331 | { |
| 332 | send(session, { |
| 333 | type: MessageType.entityMove, |
| 334 | entityId: event.entityId, |
| 335 | characterId: event.characterId, |
| 336 | tileX: event.tileX, |
| 337 | tileY: event.tileY, |
| 338 | gait: event.gait, |
| 339 | sex: event.sex, |
| 340 | firstName: event.firstName, |
| 341 | lastName: event.lastName |
| 342 | }); |
| 343 | } |
| 344 | else if (seesFrom) |
| 345 | { |
| 346 | send(session, { type: MessageType.entityDespawn, entityId: event.entityId }); |
| 347 | } |
| 348 | if (session.entityId === event.entityId) |
| 349 | { syncSubscriptions(session, false); } |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | if (simulation.tickIndex % simulation.settings.simulationTickHz === 0) |
| 354 | { broadcastStatus(); } |
| 355 | } |
| 356 | |
| 357 | return { sessions, onTickResult, wss }; |
| 358 | } |
| 359 | |
| 360 | function send (session, payload) |
| 361 | { |
| 362 | if (session.socket.readyState === 1) |
| 363 | { session.socket.send(JSON.stringify(payload)); } |
| 364 | } |