| 1 | import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js"; |
| 2 | import { tileToChunk, tileToLocal, chunkKey, visibleChunkCoords, tileKey } from "../world/coordinates.js"; |
| 3 | import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js"; |
| 4 | import { EcsWorld } from "../ecs/world.js"; |
| 5 | import { chunkBoundsAround, findPath } from "../navigation/astar.js"; |
| 6 | |
| 7 | export class Simulation |
| 8 | { |
| 9 | constructor (worldDb, stateDb) |
| 10 | { |
| 11 | this.worldDb = worldDb; |
| 12 | this.stateDb = stateDb; |
| 13 | this.ecs = new EcsWorld(); |
| 14 | this.chunks = new Map(); |
| 15 | this.occupancy = new Map(); |
| 16 | this.characterEntities = new Map(); |
| 17 | this.commandQueue = []; |
| 18 | this.movementTickCounter = 0; |
| 19 | this.activeRevisionId = worldDb.getActiveRevisionId(); |
| 20 | this.settings = worldDb.getSettings(this.activeRevisionId); |
| 21 | this.tickIndex = 0; |
| 22 | this.reloadWorld(); |
| 23 | } |
| 24 | |
| 25 | reloadWorld () |
| 26 | { |
| 27 | this.activeRevisionId = this.worldDb.getActiveRevisionId(); |
| 28 | this.settings = this.worldDb.getSettings(this.activeRevisionId); |
| 29 | this.chunks.clear(); |
| 30 | for (const entity of this.ecs.query("position")) |
| 31 | { |
| 32 | const pos = entity.position; |
| 33 | this.#ensureChunk(tileToChunk(pos.tileX), tileToChunk(pos.tileY)); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | enqueue (sessionId, command) |
| 38 | { |
| 39 | this.commandQueue.push({ sessionId, command, receivedAt: Date.now() }); |
| 40 | } |
| 41 | |
| 42 | step (now = Date.now()) |
| 43 | { |
| 44 | this.tickIndex += 1; |
| 45 | const commands = this.commandQueue.splice(0); |
| 46 | const events = []; |
| 47 | for (const item of commands) |
| 48 | { |
| 49 | try |
| 50 | { |
| 51 | const produced = this.#handleCommand(item.sessionId, item.command) ?? []; |
| 52 | events.push(...produced); |
| 53 | } |
| 54 | catch (error) |
| 55 | { |
| 56 | events.push({ |
| 57 | sessionId: item.sessionId, |
| 58 | type: "command-error", |
| 59 | message: error.userFacing ? error.message : "Command failed." |
| 60 | }); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | const movementHz = this.settings.walkTilesPerSecond * 2; |
| 65 | const simHz = this.settings.simulationTickHz; |
| 66 | const movementEvery = Math.max(1, Math.round(simHz / movementHz)); |
| 67 | if (this.tickIndex % movementEvery === 0) |
| 68 | { |
| 69 | this.movementTickCounter += 1; |
| 70 | events.push(...this.#stepMovement()); |
| 71 | } |
| 72 | |
| 73 | return { now, events }; |
| 74 | } |
| 75 | |
| 76 | worldTime (now = Date.now()) |
| 77 | { |
| 78 | const date = new Date(now); |
| 79 | date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET); |
| 80 | return { |
| 81 | unixMs: now, |
| 82 | worldUnixMs: date.getTime(), |
| 83 | iso: date.toISOString(), |
| 84 | hour: date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600 |
| 85 | }; |
| 86 | } |
| 87 | |
| 88 | spawnCharacter (sessionId, character) |
| 89 | { |
| 90 | this.despawnCharacter(character.character_id); |
| 91 | const tileX = character.tile_x; |
| 92 | const tileY = character.tile_y; |
| 93 | if (!this.isEnterable(tileX, tileY)) |
| 94 | { |
| 95 | const spawn = this.findOpenSpawn(); |
| 96 | if (!spawn) |
| 97 | { |
| 98 | const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first."); |
| 99 | error.userFacing = true; |
| 100 | throw error; |
| 101 | } |
| 102 | character.tile_x = spawn.tileX; |
| 103 | character.tile_y = spawn.tileY; |
| 104 | this.stateDb.saveCharacterPosition(character.character_id, spawn.tileX, spawn.tileY, character.gait); |
| 105 | } |
| 106 | |
| 107 | const id = this.ecs.entity(); |
| 108 | this.ecs.add(id, "position", { tileX: character.tile_x, tileY: character.tile_y }); |
| 109 | this.ecs.add(id, "movement", { gait: character.gait || GAIT.walk, path: [], walkCarry: 0 }); |
| 110 | this.ecs.add(id, "appearance", { |
| 111 | sex: character.sex, |
| 112 | firstName: character.first_name, |
| 113 | lastName: character.last_name |
| 114 | }); |
| 115 | this.ecs.add(id, "character", { |
| 116 | characterId: character.character_id, |
| 117 | accountId: character.account_id, |
| 118 | sessionId |
| 119 | }); |
| 120 | this.characterEntities.set(character.character_id, id); |
| 121 | this.#occupy(id, character.tile_x, character.tile_y); |
| 122 | this.#ensureVisibleChunks(character.tile_x, character.tile_y); |
| 123 | return id; |
| 124 | } |
| 125 | |
| 126 | despawnCharacter (characterId) |
| 127 | { |
| 128 | const id = this.characterEntities.get(characterId); |
| 129 | if (!id) |
| 130 | { return; } |
| 131 | |
| 132 | const position = this.ecs.get(id, "position"); |
| 133 | const movement = this.ecs.get(id, "movement"); |
| 134 | if (position) |
| 135 | { |
| 136 | this.#vacate(id, position.tileX, position.tileY); |
| 137 | this.stateDb.saveCharacterPosition(characterId, position.tileX, position.tileY, movement?.gait ?? GAIT.walk); |
| 138 | } |
| 139 | this.ecs.destroy(id); |
| 140 | this.characterEntities.delete(characterId); |
| 141 | } |
| 142 | |
| 143 | entityForCharacter (characterId) |
| 144 | { |
| 145 | return this.characterEntities.get(characterId) ?? null; |
| 146 | } |
| 147 | |
| 148 | snapshotFor (entityId) |
| 149 | { |
| 150 | const position = this.ecs.get(entityId, "position"); |
| 151 | if (!position) |
| 152 | { return []; } |
| 153 | |
| 154 | const coords = visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS); |
| 155 | return coords.map((coord) => this.#chunkSnapshot(coord.chunkX, coord.chunkY)); |
| 156 | } |
| 157 | |
| 158 | findOpenSpawn () |
| 159 | { |
| 160 | const coords = this.worldDb.listChunkCoords(this.activeRevisionId); |
| 161 | for (const coord of coords) |
| 162 | { |
| 163 | const data = this.#ensureChunk(coord.chunk_x, coord.chunk_y); |
| 164 | if (!data.open) |
| 165 | { continue; } |
| 166 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 167 | { |
| 168 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 169 | { |
| 170 | const tileX = coord.chunk_x * CHUNK_SIZE + localX; |
| 171 | const tileY = coord.chunk_y * CHUNK_SIZE + localY; |
| 172 | if (this.isEnterable(tileX, tileY) && !this.#occupied(tileX, tileY)) |
| 173 | { return { tileX, tileY }; } |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | return null; |
| 178 | } |
| 179 | |
| 180 | isEnterable (tileX, tileY) |
| 181 | { |
| 182 | const data = this.#ensureChunk(tileToChunk(tileX), tileToChunk(tileY)); |
| 183 | if (!data.open) |
| 184 | { return false; } |
| 185 | return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); |
| 186 | } |
| 187 | |
| 188 | #handleCommand (sessionId, command) |
| 189 | { |
| 190 | switch (command.type) |
| 191 | { |
| 192 | case "move-to": |
| 193 | return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY); |
| 194 | case "set-gait": |
| 195 | return this.#setGait(sessionId, command.characterId, command.gait); |
| 196 | default: |
| 197 | return []; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | #moveTo (sessionId, characterId, tileX, tileY) |
| 202 | { |
| 203 | const id = this.#requireOwnedEntity(sessionId, characterId); |
| 204 | const position = this.ecs.get(id, "position"); |
| 205 | const movement = this.ecs.get(id, "movement"); |
| 206 | const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); |
| 207 | const path = findPath( |
| 208 | position.tileX, |
| 209 | position.tileY, |
| 210 | tileX, |
| 211 | tileY, |
| 212 | (x, y) => this.#walkableFor(id, x, y), |
| 213 | bounds.minX, |
| 214 | bounds.minY, |
| 215 | bounds.maxX, |
| 216 | bounds.maxY |
| 217 | ); |
| 218 | movement.path = path; |
| 219 | movement.walkCarry = 0; |
| 220 | return []; |
| 221 | } |
| 222 | |
| 223 | #setGait (sessionId, characterId, gait) |
| 224 | { |
| 225 | if (gait !== GAIT.walk && gait !== GAIT.run) |
| 226 | { |
| 227 | const error = new Error("Gait must be walk or run."); |
| 228 | error.userFacing = true; |
| 229 | throw error; |
| 230 | } |
| 231 | const id = this.#requireOwnedEntity(sessionId, characterId); |
| 232 | this.ecs.get(id, "movement").gait = gait; |
| 233 | return []; |
| 234 | } |
| 235 | |
| 236 | #requireOwnedEntity (sessionId, characterId) |
| 237 | { |
| 238 | const id = this.characterEntities.get(characterId); |
| 239 | if (!id) |
| 240 | { |
| 241 | const error = new Error("Character is not in the world."); |
| 242 | error.userFacing = true; |
| 243 | throw error; |
| 244 | } |
| 245 | const character = this.ecs.get(id, "character"); |
| 246 | if (!character || character.sessionId !== sessionId) |
| 247 | { |
| 248 | const error = new Error("Character is not in the world."); |
| 249 | error.userFacing = true; |
| 250 | throw error; |
| 251 | } |
| 252 | return id; |
| 253 | } |
| 254 | |
| 255 | #stepMovement () |
| 256 | { |
| 257 | const events = []; |
| 258 | for (const entity of this.ecs.query("position", "movement")) |
| 259 | { |
| 260 | const { id, position, movement } = entity; |
| 261 | if (!movement.path.length) |
| 262 | { continue; } |
| 263 | |
| 264 | const isWalk = movement.gait !== GAIT.run; |
| 265 | if (isWalk) |
| 266 | { |
| 267 | movement.walkCarry = (movement.walkCarry + 1) % 2; |
| 268 | if (movement.walkCarry !== 0) |
| 269 | { continue; } |
| 270 | } |
| 271 | |
| 272 | const next = movement.path[0]; |
| 273 | if (!this.#walkableFor(id, next.x, next.y)) |
| 274 | { continue; } |
| 275 | |
| 276 | const fromTileX = position.tileX; |
| 277 | const fromTileY = position.tileY; |
| 278 | this.#vacate(id, fromTileX, fromTileY); |
| 279 | position.tileX = next.x; |
| 280 | position.tileY = next.y; |
| 281 | movement.path.shift(); |
| 282 | this.#occupy(id, position.tileX, position.tileY); |
| 283 | this.#ensureVisibleChunks(position.tileX, position.tileY); |
| 284 | const character = this.ecs.get(id, "character"); |
| 285 | events.push({ |
| 286 | type: "entity-move", |
| 287 | entityId: id, |
| 288 | characterId: character?.characterId, |
| 289 | fromTileX, |
| 290 | fromTileY, |
| 291 | tileX: position.tileX, |
| 292 | tileY: position.tileY, |
| 293 | gait: movement.gait |
| 294 | }); |
| 295 | } |
| 296 | return events; |
| 297 | } |
| 298 | |
| 299 | #walkableFor (entityId, tileX, tileY) |
| 300 | { |
| 301 | if (!this.isEnterable(tileX, tileY)) |
| 302 | { return false; } |
| 303 | const occupant = this.#occupied(tileX, tileY); |
| 304 | return !occupant || occupant === entityId; |
| 305 | } |
| 306 | |
| 307 | #ensureVisibleChunks (tileX, tileY) |
| 308 | { |
| 309 | for (const coord of visibleChunkCoords(tileToChunk(tileX), tileToChunk(tileY), VISIBLE_CHUNK_RADIUS)) |
| 310 | { this.#ensureChunk(coord.chunkX, coord.chunkY); } |
| 311 | } |
| 312 | |
| 313 | #ensureChunk (chunkX, chunkY) |
| 314 | { |
| 315 | const key = chunkKey(chunkX, chunkY); |
| 316 | if (this.chunks.has(key)) |
| 317 | { return this.chunks.get(key); } |
| 318 | |
| 319 | const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId); |
| 320 | const data = row |
| 321 | ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId) |
| 322 | : createEmptyChunkData(this.settings.defaultGroundTypeId); |
| 323 | this.chunks.set(key, data); |
| 324 | return data; |
| 325 | } |
| 326 | |
| 327 | #chunkSnapshot (chunkX, chunkY) |
| 328 | { |
| 329 | const data = this.#ensureChunk(chunkX, chunkY); |
| 330 | const entities = []; |
| 331 | for (const entity of this.ecs.query("position", "appearance")) |
| 332 | { |
| 333 | if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY) |
| 334 | { continue; } |
| 335 | const movement = this.ecs.get(entity.id, "movement"); |
| 336 | const character = this.ecs.get(entity.id, "character"); |
| 337 | entities.push({ |
| 338 | entityId: entity.id, |
| 339 | characterId: character?.characterId ?? null, |
| 340 | tileX: entity.position.tileX, |
| 341 | tileY: entity.position.tileY, |
| 342 | gait: movement?.gait ?? GAIT.walk, |
| 343 | sex: entity.appearance.sex, |
| 344 | firstName: entity.appearance.firstName, |
| 345 | lastName: entity.appearance.lastName |
| 346 | }); |
| 347 | } |
| 348 | return { |
| 349 | chunkX, |
| 350 | chunkY, |
| 351 | open: data.open, |
| 352 | grounds: data.grounds, |
| 353 | blocks: data.blocks, |
| 354 | light: data.light, |
| 355 | entities |
| 356 | }; |
| 357 | } |
| 358 | |
| 359 | #occupy (entityId, tileX, tileY) |
| 360 | { |
| 361 | this.occupancy.set(tileKey(tileX, tileY), entityId); |
| 362 | } |
| 363 | |
| 364 | #vacate (entityId, tileX, tileY) |
| 365 | { |
| 366 | const key = tileKey(tileX, tileY); |
| 367 | if (this.occupancy.get(key) === entityId) |
| 368 | { this.occupancy.delete(key); } |
| 369 | } |
| 370 | |
| 371 | #occupied (tileX, tileY) |
| 372 | { |
| 373 | return this.occupancy.get(tileKey(tileX, tileY)) ?? null; |
| 374 | } |
| 375 | } |