| 1 | import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js"; |
| 2 | import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName } from "/shared/definitions/tiles.js"; |
| 3 | import { GameSocket, defaultSocketUrl } from "../net/socket.js"; |
| 4 | import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js"; |
| 5 | import { WorldView } from "../render/worldView.js"; |
| 6 | import { initSocial } from "./social.js"; |
| 7 | import { initChat } from "./chat.js"; |
| 8 | import { initInventory } from "./inventory.js"; |
| 9 | import { initSkills } from "./skills.js"; |
| 10 | import { initCrafting } from "./crafting.js"; |
| 11 | import { initAlchemy } from "./alchemy.js"; |
| 12 | import { initStamina } from "./stamina.js"; |
| 13 | import { initContextMenu } from "./contextMenu.js"; |
| 14 | import { initDeath } from "./death.js"; |
| 15 | import { initToasts } from "./toasts.js"; |
| 16 | import { initShop } from "./shop.js"; |
| 17 | import { CraftingStationId } from "/shared/definitions/craftingStations.js"; |
| 18 | import { isOreBoulderState } from "/shared/definitions/materialTiers.js"; |
| 19 | import { formatQuantity } from "/shared/items/formatQuantity.js"; |
| 20 | import { ItemId } from "/shared/definitions/items.js"; |
| 21 | import { countCoinsInSlots } from "/shared/items/inventory.js"; |
| 22 | |
| 23 | const game = new Game(); |
| 24 | const hud = document.getElementById("hud"); |
| 25 | const overlay = document.getElementById("overlay"); |
| 26 | const statusEl = document.getElementById("status"); |
| 27 | const characterList = document.getElementById("character-list"); |
| 28 | const errorEl = document.getElementById("error"); |
| 29 | const worldTooltip = document.getElementById("world-tooltip"); |
| 30 | |
| 31 | let socket; |
| 32 | let session = null; |
| 33 | let playing = false; |
| 34 | let view = null; |
| 35 | let scene = null; |
| 36 | let gait = GAIT.walk; |
| 37 | let catalog = { grounds: {}, blocks: {} }; |
| 38 | let social; |
| 39 | let chat; |
| 40 | let inventory; |
| 41 | let skills; |
| 42 | let crafting; |
| 43 | let alchemy; |
| 44 | let staminaUi; |
| 45 | let contextMenu; |
| 46 | let death; |
| 47 | let toasts; |
| 48 | let shop; |
| 49 | let pendingPickup = null; |
| 50 | /** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */ |
| 51 | let pendingInteract = null; |
| 52 | /** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */ |
| 53 | let approachMove = null; |
| 54 | /** Framework can report mousePressed for two frames; latch so one physical click is one command. */ |
| 55 | let leftClickConsumed = false; |
| 56 | |
| 57 | function consumeWorldClick () |
| 58 | { |
| 59 | leftClickConsumed = true; |
| 60 | } |
| 61 | |
| 62 | function showError (message) |
| 63 | { |
| 64 | errorEl.textContent = message ?? ""; |
| 65 | } |
| 66 | |
| 67 | function renderCharacters (characters) |
| 68 | { |
| 69 | characterList.innerHTML = ""; |
| 70 | for (const character of characters) |
| 71 | { |
| 72 | const row = document.createElement("div"); |
| 73 | row.className = "character-row"; |
| 74 | const pending = character.deletionScheduledAt |
| 75 | ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})` |
| 76 | : ""; |
| 77 | row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`; |
| 78 | const play = document.createElement("button"); |
| 79 | play.textContent = "Play"; |
| 80 | play.disabled = !!character.deletionScheduledAt; |
| 81 | play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId })); |
| 82 | const del = document.createElement("button"); |
| 83 | del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete"; |
| 84 | del.addEventListener("click", () => |
| 85 | { |
| 86 | socket.send({ |
| 87 | type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter, |
| 88 | characterId: character.characterId |
| 89 | }); |
| 90 | }); |
| 91 | row.append(play, del); |
| 92 | characterList.append(row); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | function uiBlocked () |
| 97 | { |
| 98 | return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() |
| 99 | || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking() |
| 100 | || contextMenu?.isOpen() || death?.isBlocking()); |
| 101 | } |
| 102 | |
| 103 | function clearPendingPickup () |
| 104 | { |
| 105 | pendingPickup = null; |
| 106 | } |
| 107 | |
| 108 | function clearPendingInteract () |
| 109 | { |
| 110 | pendingInteract = null; |
| 111 | approachMove = null; |
| 112 | } |
| 113 | |
| 114 | function clearAllPendingActions () |
| 115 | { |
| 116 | clearPendingPickup(); |
| 117 | clearPendingInteract(); |
| 118 | } |
| 119 | |
| 120 | function approachAdjacentTile (tileX, tileY) |
| 121 | { |
| 122 | const local = view.entities.get(view.localEntityId); |
| 123 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 124 | { |
| 125 | approachMove = null; |
| 126 | return true; |
| 127 | } |
| 128 | let bestWalkable = null; |
| 129 | let bestWalkableDist = Infinity; |
| 130 | let bestAny = null; |
| 131 | let bestAnyDist = Infinity; |
| 132 | for (let dy = -1; dy <= 1; dy++) |
| 133 | { |
| 134 | for (let dx = -1; dx <= 1; dx++) |
| 135 | { |
| 136 | if (dx === 0 && dy === 0) |
| 137 | { continue; } |
| 138 | const destX = tileX + dx; |
| 139 | const destY = tileY + dy; |
| 140 | const dist = local |
| 141 | ? chebyshev(local.tileX, local.tileY, destX, destY) |
| 142 | : 0; |
| 143 | if (dist < bestAnyDist) |
| 144 | { |
| 145 | bestAnyDist = dist; |
| 146 | bestAny = { tileX: destX, tileY: destY }; |
| 147 | } |
| 148 | if (isClientApproachable(destX, destY) && dist < bestWalkableDist) |
| 149 | { |
| 150 | bestWalkableDist = dist; |
| 151 | bestWalkable = { tileX: destX, tileY: destY }; |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | const best = bestWalkable ?? bestAny; |
| 156 | if (!best) |
| 157 | { return false; } |
| 158 | if ( |
| 159 | approachMove |
| 160 | && approachMove.focusX === tileX |
| 161 | && approachMove.focusY === tileY |
| 162 | && approachMove.destX === best.tileX |
| 163 | && approachMove.destY === best.tileY |
| 164 | ) |
| 165 | { return false; } |
| 166 | approachMove = { |
| 167 | focusX: tileX, |
| 168 | focusY: tileY, |
| 169 | destX: best.tileX, |
| 170 | destY: best.tileY |
| 171 | }; |
| 172 | socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); |
| 173 | return false; |
| 174 | } |
| 175 | |
| 176 | function requestOpenBank (tileX, tileY, { getCheques = false } = {}) |
| 177 | { |
| 178 | clearAllPendingActions(); |
| 179 | pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques }; |
| 180 | const local = view?.entities.get(view.localEntityId); |
| 181 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 182 | { flushPendingInteract(); } |
| 183 | else |
| 184 | { approachAdjacentTile(tileX, tileY); } |
| 185 | } |
| 186 | |
| 187 | function requestOpenCauldron (tileX, tileY) |
| 188 | { |
| 189 | clearAllPendingActions(); |
| 190 | pendingInteract = { kind: "cauldron", tileX, tileY }; |
| 191 | const local = view?.entities.get(view.localEntityId); |
| 192 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 193 | { flushPendingInteract(); } |
| 194 | else |
| 195 | { approachAdjacentTile(tileX, tileY); } |
| 196 | } |
| 197 | |
| 198 | function requestOpenFurnace (tileX, tileY) |
| 199 | { |
| 200 | requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY); |
| 201 | } |
| 202 | |
| 203 | function requestOpenCraftStation (stationId, tileX, tileY) |
| 204 | { |
| 205 | clearAllPendingActions(); |
| 206 | pendingInteract = { kind: "station", stationId, tileX, tileY }; |
| 207 | const local = view?.entities.get(view.localEntityId); |
| 208 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 209 | { flushPendingInteract(); } |
| 210 | else |
| 211 | { approachAdjacentTile(tileX, tileY); } |
| 212 | } |
| 213 | |
| 214 | function requestMine (tileX, tileY) |
| 215 | { |
| 216 | clearAllPendingActions(); |
| 217 | pendingInteract = { kind: "mine", tileX, tileY }; |
| 218 | const local = view?.entities.get(view.localEntityId); |
| 219 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 220 | { flushPendingInteract(); } |
| 221 | else |
| 222 | { approachAdjacentTile(tileX, tileY); } |
| 223 | } |
| 224 | |
| 225 | function requestTalk (targetEntityId) |
| 226 | { |
| 227 | clearAllPendingActions(); |
| 228 | pendingInteract = { kind: "talk", targetEntityId }; |
| 229 | const target = view?.entities.get(targetEntityId); |
| 230 | if (!target) |
| 231 | { |
| 232 | clearPendingInteract(); |
| 233 | return; |
| 234 | } |
| 235 | if (approachAdjacentTile(target.tileX, target.tileY)) |
| 236 | { flushPendingInteract(); } |
| 237 | } |
| 238 | |
| 239 | function flushPendingInteract () |
| 240 | { |
| 241 | if (!pendingInteract || !view) |
| 242 | { return; } |
| 243 | const local = view.entities.get(view.localEntityId); |
| 244 | if (!local) |
| 245 | { return; } |
| 246 | |
| 247 | if (pendingInteract.kind === "bank") |
| 248 | { |
| 249 | if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) |
| 250 | { return; } |
| 251 | const getCheques = !!pendingInteract.getCheques; |
| 252 | socket.send({ type: MessageType.openBank }); |
| 253 | if (getCheques) |
| 254 | { inventory?.getBlankCheques(); } |
| 255 | clearPendingInteract(); |
| 256 | return; |
| 257 | } |
| 258 | |
| 259 | if (pendingInteract.kind === "cauldron") |
| 260 | { |
| 261 | if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) |
| 262 | { return; } |
| 263 | socket.send({ type: MessageType.openCauldron }); |
| 264 | clearPendingInteract(); |
| 265 | return; |
| 266 | } |
| 267 | |
| 268 | if (pendingInteract.kind === "station") |
| 269 | { |
| 270 | if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) |
| 271 | { return; } |
| 272 | socket.send({ |
| 273 | type: MessageType.openStation, |
| 274 | stationId: pendingInteract.stationId |
| 275 | }); |
| 276 | clearPendingInteract(); |
| 277 | return; |
| 278 | } |
| 279 | |
| 280 | if (pendingInteract.kind === "mine") |
| 281 | { |
| 282 | if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) |
| 283 | { return; } |
| 284 | socket.send({ |
| 285 | type: MessageType.mine, |
| 286 | tileX: pendingInteract.tileX, |
| 287 | tileY: pendingInteract.tileY |
| 288 | }); |
| 289 | clearPendingInteract(); |
| 290 | return; |
| 291 | } |
| 292 | |
| 293 | if (pendingInteract.kind === "talk") |
| 294 | { |
| 295 | const target = view.entities.get(pendingInteract.targetEntityId); |
| 296 | if (!target) |
| 297 | { |
| 298 | clearPendingInteract(); |
| 299 | return; |
| 300 | } |
| 301 | if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1) |
| 302 | { |
| 303 | // Target may have moved — keep chasing. |
| 304 | approachAdjacentTile(target.tileX, target.tileY); |
| 305 | return; |
| 306 | } |
| 307 | socket.send({ type: MessageType.interact, targetEntityId: pendingInteract.targetEntityId }); |
| 308 | clearPendingInteract(); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | function requestPickup (ground) |
| 313 | { |
| 314 | if (!ground) |
| 315 | { return; } |
| 316 | clearPendingInteract(); |
| 317 | pendingPickup = { |
| 318 | groundItemId: ground.groundItemId, |
| 319 | tileX: ground.tileX, |
| 320 | tileY: ground.tileY |
| 321 | }; |
| 322 | const local = view.entities.get(view.localEntityId); |
| 323 | if (local && local.tileX === ground.tileX && local.tileY === ground.tileY) |
| 324 | { |
| 325 | flushPendingPickup(); |
| 326 | return; |
| 327 | } |
| 328 | socket.send({ type: MessageType.moveTo, tileX: ground.tileX, tileY: ground.tileY }); |
| 329 | } |
| 330 | |
| 331 | function flushPendingPickup () |
| 332 | { |
| 333 | if (!pendingPickup || !view) |
| 334 | { return; } |
| 335 | const item = view.groundItems.get(pendingPickup.groundItemId); |
| 336 | if (!item) |
| 337 | { |
| 338 | clearPendingPickup(); |
| 339 | return; |
| 340 | } |
| 341 | const local = view.entities.get(view.localEntityId); |
| 342 | if (!local) |
| 343 | { return; } |
| 344 | if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY) |
| 345 | { return; } |
| 346 | socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId }); |
| 347 | clearPendingPickup(); |
| 348 | } |
| 349 | |
| 350 | function requestAttack (targetEntityId) |
| 351 | { |
| 352 | clearAllPendingActions(); |
| 353 | socket.send({ type: MessageType.attack, targetEntityId }); |
| 354 | } |
| 355 | |
| 356 | function isAttackableEntity (entity) |
| 357 | { |
| 358 | if (!entity || entity.untargetable) |
| 359 | { return false; } |
| 360 | if (entity.canFight) |
| 361 | { return true; } |
| 362 | // Snapshots can omit canFight; mobs are still attackable via LMB. |
| 363 | return !!entity.mobTypeId && !entity.talkable; |
| 364 | } |
| 365 | |
| 366 | function handleLeftClick (mouseX, mouseY) |
| 367 | { |
| 368 | const entity = view.entityAtScreen(mouseX, mouseY); |
| 369 | if (entity && entity.entityId !== view.localEntityId && !entity.untargetable) |
| 370 | { |
| 371 | clearPendingPickup(); |
| 372 | if (entity.characterId) |
| 373 | { |
| 374 | clearPendingInteract(); |
| 375 | social.inspect(entity); |
| 376 | return; |
| 377 | } |
| 378 | if (entity.talkable) |
| 379 | { |
| 380 | requestTalk(entity.entityId); |
| 381 | return; |
| 382 | } |
| 383 | if (isAttackableEntity(entity)) |
| 384 | { |
| 385 | requestAttack(entity.entityId); |
| 386 | return; |
| 387 | } |
| 388 | // Clicked an entity we don't act on — do not fall through to walk (that cancels combat). |
| 389 | return; |
| 390 | } |
| 391 | |
| 392 | const tile = view.screenToTile(mouseX, mouseY); |
| 393 | const ground = view.groundItemAtTile(tile.tileX, tile.tileY); |
| 394 | if (ground) |
| 395 | { requestPickup(ground); } |
| 396 | else if (isBankTile(view, tile.tileX, tile.tileY)) |
| 397 | { requestOpenBank(tile.tileX, tile.tileY); } |
| 398 | else if (isCauldronTile(view, tile.tileX, tile.tileY)) |
| 399 | { requestOpenCauldron(tile.tileX, tile.tileY); } |
| 400 | else if (isFurnaceTile(view, tile.tileX, tile.tileY)) |
| 401 | { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); } |
| 402 | else if (isAnvilTile(view, tile.tileX, tile.tileY)) |
| 403 | { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); } |
| 404 | else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY)) |
| 405 | { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); } |
| 406 | else if (isCraftingBenchTile(view, tile.tileX, tile.tileY)) |
| 407 | { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); } |
| 408 | else if (isOreBoulderTile(view, tile.tileX, tile.tileY)) |
| 409 | { requestMine(tile.tileX, tile.tileY); } |
| 410 | else |
| 411 | { |
| 412 | clearAllPendingActions(); |
| 413 | socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | function handleRightClick (event, mouseX, mouseY) |
| 418 | { |
| 419 | event.preventDefault(); |
| 420 | const tile = view.screenToTile(mouseX, mouseY); |
| 421 | const items = []; |
| 422 | const walkTileX = tile.tileX; |
| 423 | const walkTileY = tile.tileY; |
| 424 | |
| 425 | items.push({ |
| 426 | label: "Walk here", |
| 427 | onSelect: () => |
| 428 | { |
| 429 | clearAllPendingActions(); |
| 430 | socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY }); |
| 431 | } |
| 432 | }); |
| 433 | |
| 434 | for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY)) |
| 435 | { |
| 436 | if (entity.entityId === view.localEntityId) |
| 437 | { continue; } |
| 438 | const targetName = entityLabel(entity); |
| 439 | items.push({ |
| 440 | label: `Follow ${targetName}`, |
| 441 | onSelect: () => |
| 442 | { |
| 443 | clearAllPendingActions(); |
| 444 | socket.send({ type: MessageType.follow, targetEntityId: entity.entityId }); |
| 445 | } |
| 446 | }); |
| 447 | if (entity.untargetable) |
| 448 | { continue; } |
| 449 | if (entity.hasShop) |
| 450 | { |
| 451 | items.push({ |
| 452 | label: `Shop ${targetName}`, |
| 453 | onSelect: () => requestTalk(entity.entityId) |
| 454 | }); |
| 455 | } |
| 456 | else if (entity.talkable) |
| 457 | { |
| 458 | items.push({ |
| 459 | label: `Talk to ${targetName}`, |
| 460 | onSelect: () => requestTalk(entity.entityId) |
| 461 | }); |
| 462 | } |
| 463 | if (entity.characterId) |
| 464 | { |
| 465 | items.push({ |
| 466 | label: `${targetName} info`, |
| 467 | onSelect: () => |
| 468 | { |
| 469 | clearAllPendingActions(); |
| 470 | social.inspect(entity); |
| 471 | } |
| 472 | }); |
| 473 | } |
| 474 | items.push({ |
| 475 | label: `Attack ${targetName}`, |
| 476 | onSelect: () => requestAttack(entity.entityId) |
| 477 | }); |
| 478 | } |
| 479 | |
| 480 | for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY)) |
| 481 | { |
| 482 | const name = groundLabel(ground); |
| 483 | items.push({ |
| 484 | label: `Pick up ${name}`, |
| 485 | onSelect: () => requestPickup(ground) |
| 486 | }); |
| 487 | } |
| 488 | |
| 489 | if (isBankTile(view, tile.tileX, tile.tileY)) |
| 490 | { |
| 491 | items.push({ |
| 492 | label: "Bank", |
| 493 | onSelect: () => requestOpenBank(tile.tileX, tile.tileY) |
| 494 | }); |
| 495 | items.push({ |
| 496 | label: "Get Blank Cheques", |
| 497 | onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true }) |
| 498 | }); |
| 499 | } |
| 500 | |
| 501 | if (isCauldronTile(view, tile.tileX, tile.tileY)) |
| 502 | { |
| 503 | items.push({ |
| 504 | label: "Alchemy", |
| 505 | onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY) |
| 506 | }); |
| 507 | } |
| 508 | |
| 509 | if (isFurnaceTile(view, tile.tileX, tile.tileY)) |
| 510 | { |
| 511 | items.push({ |
| 512 | label: "Smelt", |
| 513 | onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY) |
| 514 | }); |
| 515 | } |
| 516 | |
| 517 | if (isAnvilTile(view, tile.tileX, tile.tileY)) |
| 518 | { |
| 519 | items.push({ |
| 520 | label: "Smith", |
| 521 | onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY) |
| 522 | }); |
| 523 | } |
| 524 | |
| 525 | if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY)) |
| 526 | { |
| 527 | items.push({ |
| 528 | label: "Woodwork", |
| 529 | onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY) |
| 530 | }); |
| 531 | } |
| 532 | |
| 533 | if (isCraftingBenchTile(view, tile.tileX, tile.tileY)) |
| 534 | { |
| 535 | items.push({ |
| 536 | label: "Craft", |
| 537 | onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY) |
| 538 | }); |
| 539 | } |
| 540 | |
| 541 | if (isOreBoulderTile(view, tile.tileX, tile.tileY)) |
| 542 | { |
| 543 | items.push({ |
| 544 | label: "Mine", |
| 545 | onSelect: () => requestMine(tile.tileX, tile.tileY) |
| 546 | }); |
| 547 | } |
| 548 | |
| 549 | contextMenu.show(event.clientX, event.clientY, items); |
| 550 | } |
| 551 | |
| 552 | function entityLabel (entity) |
| 553 | { |
| 554 | const first = (entity?.firstName ?? "").trim(); |
| 555 | const last = (entity?.lastName ?? "").trim(); |
| 556 | if (first && last) |
| 557 | { return `${first} ${last}`; } |
| 558 | return first || "target"; |
| 559 | } |
| 560 | |
| 561 | function groundLabel (ground) |
| 562 | { |
| 563 | const name = (ground?.displayName ?? "").trim() || "item"; |
| 564 | const qty = ground?.quantity ?? 1; |
| 565 | if (qty <= 1) |
| 566 | { return name; } |
| 567 | return `${name} (${formatQuantity(qty)})`; |
| 568 | } |
| 569 | |
| 570 | function startPlay (payload) |
| 571 | { |
| 572 | playing = true; |
| 573 | overlay.hidden = true; |
| 574 | hud.hidden = false; |
| 575 | document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`; |
| 576 | gait = payload.gait ?? GAIT.walk; |
| 577 | document.getElementById("gait").textContent = gait; |
| 578 | staminaUi?.show(); |
| 579 | if (payload.stamina != null) |
| 580 | { staminaUi?.apply(payload.stamina); } |
| 581 | if (!scene) |
| 582 | { |
| 583 | scene = new Scene(0, 0, window.innerWidth, window.innerHeight); |
| 584 | game.loadScene(scene); |
| 585 | useNearestNeighbour(scene, game.images); |
| 586 | view = new WorldView(game, scene, catalog); |
| 587 | const ticker = new GameObject(0, 0, null, 10); |
| 588 | ticker.update = (dt) => |
| 589 | { |
| 590 | const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left); |
| 591 | const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left); |
| 592 | if (!leftPressed && !leftHeld) |
| 593 | { leftClickConsumed = false; } |
| 594 | else if (!leftClickConsumed && playing && !uiBlocked()) |
| 595 | { |
| 596 | leftClickConsumed = true; |
| 597 | const canvas = scene.canvas; |
| 598 | const rect = canvas.getBoundingClientRect(); |
| 599 | const mouseX = GameInput.mousePosition.x - rect.left; |
| 600 | const mouseY = GameInput.mousePosition.y - rect.top; |
| 601 | handleLeftClick(mouseX, mouseY); |
| 602 | } |
| 603 | if (GameInput.isPressed(82) && !uiBlocked()) |
| 604 | { |
| 605 | const next = gait === GAIT.run ? GAIT.walk : GAIT.run; |
| 606 | if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0) |
| 607 | { return; } |
| 608 | socket.send({ type: MessageType.setGait, gait: next }); |
| 609 | // Walk always applies; run waits for authoritative STAMINA (may reject if empty). |
| 610 | if (next === GAIT.walk) |
| 611 | { |
| 612 | gait = next; |
| 613 | document.getElementById("gait").textContent = gait; |
| 614 | } |
| 615 | } |
| 616 | if (playing && !death?.isBlocking()) |
| 617 | { |
| 618 | flushPendingPickup(); |
| 619 | flushPendingInteract(); |
| 620 | social?.updateNametag(view, scene, view.localEntityId); |
| 621 | chat?.update(view, scene); |
| 622 | updateWorldTooltip(); |
| 623 | } |
| 624 | else |
| 625 | { hideWorldTooltip(); } |
| 626 | view.update(dt); |
| 627 | }; |
| 628 | scene.addObject(ticker); |
| 629 | window.addEventListener("resize", () => |
| 630 | { |
| 631 | scene.size.x = window.innerWidth; |
| 632 | scene.size.y = window.innerHeight; |
| 633 | scene.g_fixSize(); |
| 634 | useNearestNeighbour(scene, game.images); |
| 635 | }); |
| 636 | window.addEventListener("wheel", (event) => |
| 637 | { |
| 638 | if (!playing || uiBlocked()) |
| 639 | { return; } |
| 640 | view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25)); |
| 641 | document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`; |
| 642 | }, { passive: true }); |
| 643 | scene.canvas.addEventListener("contextmenu", (event) => |
| 644 | { |
| 645 | if (!playing || uiBlocked()) |
| 646 | { return; } |
| 647 | const rect = scene.canvas.getBoundingClientRect(); |
| 648 | handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top); |
| 649 | }); |
| 650 | } |
| 651 | view.setSettings(payload.settings ?? view.settings); |
| 652 | chat?.syncSettings(); |
| 653 | view.worldHour = payload.worldTime?.hour ?? 12; |
| 654 | view.setLocalEntity( |
| 655 | payload.entityId, |
| 656 | payload.tileX, |
| 657 | payload.tileY, |
| 658 | payload.gait, |
| 659 | payload.sex, |
| 660 | payload.firstName, |
| 661 | payload.lastName, |
| 662 | payload.characterId, |
| 663 | payload.layers |
| 664 | ); |
| 665 | } |
| 666 | |
| 667 | async function main () |
| 668 | { |
| 669 | catalog = await loadSpriteCatalog(); |
| 670 | await preloadCatalogImages(game, catalog); |
| 671 | applySpriteSheets(game.images, catalog); |
| 672 | social = initSocial({ |
| 673 | socket: { send (payload) { socket.send(payload); } }, |
| 674 | MessageType |
| 675 | }); |
| 676 | contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick }); |
| 677 | inventory = initInventory({ |
| 678 | socket: { send (payload) { socket.send(payload); } }, |
| 679 | MessageType, |
| 680 | contextMenu, |
| 681 | resolveSpriteUrl (name) |
| 682 | { |
| 683 | return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; |
| 684 | }, |
| 685 | getFriends () |
| 686 | { |
| 687 | return social?.getFriends?.() ?? []; |
| 688 | }, |
| 689 | getLocalName () |
| 690 | { |
| 691 | const you = document.getElementById("you")?.textContent ?? ""; |
| 692 | return you.split("(")[0].trim() || "Unknown"; |
| 693 | } |
| 694 | }); |
| 695 | skills = initSkills(); |
| 696 | crafting = initCrafting({ |
| 697 | socket: { send (payload) { socket.send(payload); } }, |
| 698 | MessageType, |
| 699 | getInventorySlots () |
| 700 | { |
| 701 | return inventory?.getInventorySlots?.() ?? []; |
| 702 | }, |
| 703 | getSkillLevel (skillId) |
| 704 | { |
| 705 | return skills?.skillLevel?.(skillId) ?? 1; |
| 706 | } |
| 707 | }); |
| 708 | alchemy = initAlchemy({ |
| 709 | socket: { send (payload) { socket.send(payload); } }, |
| 710 | MessageType, |
| 711 | getInventorySlots () |
| 712 | { |
| 713 | return inventory?.getInventorySlots?.() ?? []; |
| 714 | } |
| 715 | }); |
| 716 | staminaUi = initStamina(); |
| 717 | toasts = initToasts(); |
| 718 | shop = initShop({ |
| 719 | socket: { send (payload) { socket.send(payload); } }, |
| 720 | MessageType, |
| 721 | onSuppressWorldClick: consumeWorldClick, |
| 722 | getCoinCount () |
| 723 | { |
| 724 | return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []); |
| 725 | }, |
| 726 | getInventorySlots () |
| 727 | { |
| 728 | return inventory?.getInventorySlots?.() ?? []; |
| 729 | } |
| 730 | }); |
| 731 | chat = initChat({ |
| 732 | socket: { send (payload) { socket.send(payload); } }, |
| 733 | MessageType, |
| 734 | getSettings: () => view?.settings |
| 735 | }); |
| 736 | death = initDeath({ |
| 737 | socket: { send (payload) { socket.send(payload); } }, |
| 738 | MessageType |
| 739 | }); |
| 740 | game.startGame(); |
| 741 | |
| 742 | socket = new GameSocket(defaultSocketUrl(), (message) => |
| 743 | { |
| 744 | switch (message.type) |
| 745 | { |
| 746 | case MessageType.session: |
| 747 | session = message; |
| 748 | statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`; |
| 749 | renderCharacters(message.characters); |
| 750 | break; |
| 751 | case MessageType.characterList: |
| 752 | renderCharacters(message.characters); |
| 753 | if (!playing) |
| 754 | { overlay.hidden = false; } |
| 755 | break; |
| 756 | case MessageType.enterWorld: |
| 757 | startPlay(message); |
| 758 | inventory?.setLocalCharacterId(message.characterId); |
| 759 | break; |
| 760 | case MessageType.chunkSnapshot: |
| 761 | view?.applySnapshot(message); |
| 762 | break; |
| 763 | case MessageType.chunkDelta: |
| 764 | for (const tile of message.tiles ?? []) |
| 765 | { |
| 766 | view?.updateAuthoredTile( |
| 767 | message.chunkX, |
| 768 | message.chunkY, |
| 769 | tile.localX, |
| 770 | tile.localY, |
| 771 | { ground: tile.ground, block: tile.block, light: tile.light } |
| 772 | ); |
| 773 | } |
| 774 | break; |
| 775 | case MessageType.unsubscribeChunk: |
| 776 | view?.removeChunk(message.chunkX, message.chunkY); |
| 777 | break; |
| 778 | case MessageType.entitySpawn: |
| 779 | view?.spawnEntity(message); |
| 780 | break; |
| 781 | case MessageType.entityMove: |
| 782 | view?.moveEntity(message); |
| 783 | if (message.entityId === view?.localEntityId && message.gait) |
| 784 | { |
| 785 | gait = message.gait; |
| 786 | document.getElementById("gait").textContent = gait; |
| 787 | } |
| 788 | break; |
| 789 | case MessageType.entityDespawn: |
| 790 | view?.despawnEntity(message.entityId); |
| 791 | break; |
| 792 | case MessageType.entityAppearance: |
| 793 | view?.setAppearance(message); |
| 794 | break; |
| 795 | case MessageType.groundItemAppear: |
| 796 | view?.upsertGroundItem(message); |
| 797 | break; |
| 798 | case MessageType.groundItemDespawn: |
| 799 | view?.despawnGroundItem(message.groundItemId); |
| 800 | break; |
| 801 | case MessageType.inventory: |
| 802 | inventory?.handleInventory(message); |
| 803 | crafting?.refresh(); |
| 804 | alchemy?.refresh(); |
| 805 | shop?.refresh(); |
| 806 | break; |
| 807 | case MessageType.skills: |
| 808 | skills?.render(message.skills); |
| 809 | crafting?.refresh(); |
| 810 | break; |
| 811 | case MessageType.stamina: |
| 812 | staminaUi?.apply(message); |
| 813 | if (message.gait) |
| 814 | { |
| 815 | gait = message.gait; |
| 816 | document.getElementById("gait").textContent = gait; |
| 817 | } |
| 818 | break; |
| 819 | case MessageType.bankSnapshot: |
| 820 | inventory?.handleBank(message); |
| 821 | break; |
| 822 | case MessageType.cauldronSnapshot: |
| 823 | alchemy?.handleSnapshot(message); |
| 824 | break; |
| 825 | case MessageType.pigeonDispatched: |
| 826 | inventory?.handlePigeonDispatched(message); |
| 827 | break; |
| 828 | case MessageType.pigeonDelivered: |
| 829 | inventory?.handlePigeonDelivered(message); |
| 830 | break; |
| 831 | case MessageType.characterSearchResult: |
| 832 | inventory?.handleCharacterSearch(message); |
| 833 | break; |
| 834 | case MessageType.craftResult: |
| 835 | crafting?.handleCraftResult(message); |
| 836 | break; |
| 837 | case MessageType.worldStatus: |
| 838 | if (view) |
| 839 | { |
| 840 | view.setSettings(message.settings ?? view.settings); |
| 841 | view.worldHour = message.worldTime?.hour ?? view.worldHour; |
| 842 | chat?.syncSettings(); |
| 843 | } |
| 844 | break; |
| 845 | case MessageType.chatBubble: |
| 846 | chat?.showBubble(message); |
| 847 | break; |
| 848 | case MessageType.friends: |
| 849 | social?.handleFriends(message); |
| 850 | break; |
| 851 | case MessageType.combatSwing: |
| 852 | view?.spawnCombatSwing(message); |
| 853 | break; |
| 854 | case MessageType.gatherSwing: |
| 855 | case MessageType.tileShove: |
| 856 | view?.spawnGatherSwing(message); |
| 857 | break; |
| 858 | case MessageType.stationOpen: |
| 859 | if (message.stationId) |
| 860 | { crafting?.openStation(message.stationId); } |
| 861 | break; |
| 862 | case MessageType.shopOpen: |
| 863 | shop?.handleShopOpen(message); |
| 864 | break; |
| 865 | case MessageType.shopClosed: |
| 866 | shop?.handleShopClosed(message); |
| 867 | break; |
| 868 | case MessageType.itemBubble: |
| 869 | chat?.showItemBubble(message); |
| 870 | break; |
| 871 | case MessageType.gatherComplete: |
| 872 | crafting?.refresh(); |
| 873 | break; |
| 874 | case MessageType.combatHit: |
| 875 | view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); |
| 876 | view?.flashDamage(message.targetId); |
| 877 | view?.spawnDamageNumber(message.targetId, message.damage); |
| 878 | break; |
| 879 | case MessageType.playerDied: |
| 880 | clearAllPendingActions(); |
| 881 | contextMenu?.hide(); |
| 882 | death?.show(); |
| 883 | break; |
| 884 | case MessageType.playerRespawned: |
| 885 | death?.hide(); |
| 886 | view?.updateEntityHealth(message.entityId, message.health, message.maxHealth); |
| 887 | if (message.stamina != null || message.maxStamina != null) |
| 888 | { |
| 889 | staminaUi?.apply({ |
| 890 | current: message.stamina ?? staminaUi.getCurrent?.(), |
| 891 | max: message.maxStamina ?? staminaUi.getMax?.() |
| 892 | }); |
| 893 | } |
| 894 | break; |
| 895 | case MessageType.error: |
| 896 | if (playing) |
| 897 | { toasts?.show(message.message); } |
| 898 | else |
| 899 | { showError(message.message); } |
| 900 | social?.showError(message.message); |
| 901 | break; |
| 902 | case MessageType.forceLogout: |
| 903 | returnToMenu(message.reason); |
| 904 | break; |
| 905 | } |
| 906 | }, { |
| 907 | onClose (event) |
| 908 | { |
| 909 | if (playing) |
| 910 | { returnToMenu(event.reason || "Disconnected from server."); } |
| 911 | } |
| 912 | }); |
| 913 | await socket.connect(); |
| 914 | if (typeof window !== "undefined") |
| 915 | { |
| 916 | window.__craftDev = (stationId = CraftingStationId.craftingBench) => |
| 917 | { |
| 918 | crafting?.openStation(stationId); |
| 919 | }; |
| 920 | } |
| 921 | } |
| 922 | |
| 923 | function returnToMenu (reason = "") |
| 924 | { |
| 925 | playing = false; |
| 926 | clearAllPendingActions(); |
| 927 | social?.reset(); |
| 928 | chat?.reset(); |
| 929 | inventory?.reset(); |
| 930 | crafting?.reset(); |
| 931 | alchemy?.reset(); |
| 932 | staminaUi?.hide(); |
| 933 | skills?.hide(); |
| 934 | contextMenu?.hide(); |
| 935 | death?.reset(); |
| 936 | shop?.close({ notifyServer: false }); |
| 937 | hideWorldTooltip(); |
| 938 | if (view) |
| 939 | { |
| 940 | for (const key of [...(view.chunks?.keys?.() ?? [])]) |
| 941 | { |
| 942 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 943 | view.removeChunk(chunkX, chunkY); |
| 944 | } |
| 945 | } |
| 946 | overlay.hidden = false; |
| 947 | hud.hidden = true; |
| 948 | if (reason) |
| 949 | { statusEl.textContent = reason; } |
| 950 | } |
| 951 | |
| 952 | document.getElementById("create-form").addEventListener("submit", (event) => |
| 953 | { |
| 954 | event.preventDefault(); |
| 955 | showError(""); |
| 956 | socket.send({ |
| 957 | type: MessageType.createCharacter, |
| 958 | firstName: document.getElementById("first-name").value, |
| 959 | lastName: document.getElementById("last-name").value, |
| 960 | sex: document.getElementById("sex").value |
| 961 | }); |
| 962 | }); |
| 963 | |
| 964 | document.getElementById("leave").addEventListener("click", () => |
| 965 | { |
| 966 | socket.send({ type: MessageType.leaveWorld }); |
| 967 | returnToMenu(); |
| 968 | }); |
| 969 | |
| 970 | main().catch((error) => |
| 971 | { |
| 972 | showError(error.message); |
| 973 | console.error(error); |
| 974 | }); |
| 975 | |
| 976 | function isBankTile (view, tileX, tileY) |
| 977 | { |
| 978 | return blockTypeAt(view, tileX, tileY) === BlockType.bank; |
| 979 | } |
| 980 | |
| 981 | function isCauldronTile (view, tileX, tileY) |
| 982 | { |
| 983 | return blockTypeAt(view, tileX, tileY) === BlockType.cauldron; |
| 984 | } |
| 985 | |
| 986 | function isFurnaceTile (view, tileX, tileY) |
| 987 | { |
| 988 | return blockTypeAt(view, tileX, tileY) === BlockType.furnace; |
| 989 | } |
| 990 | |
| 991 | function isAnvilTile (view, tileX, tileY) |
| 992 | { |
| 993 | return blockTypeAt(view, tileX, tileY) === BlockType.anvil; |
| 994 | } |
| 995 | |
| 996 | function isWoodworkingBenchTile (view, tileX, tileY) |
| 997 | { |
| 998 | return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench; |
| 999 | } |
| 1000 | |
| 1001 | function isCraftingBenchTile (view, tileX, tileY) |
| 1002 | { |
| 1003 | return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench; |
| 1004 | } |
| 1005 | |
| 1006 | function isOreBoulderTile (view, tileX, tileY) |
| 1007 | { |
| 1008 | const block = blockAt(view, tileX, tileY); |
| 1009 | return block?.typeId === BlockType.boulder && isOreBoulderState(block.state); |
| 1010 | } |
| 1011 | |
| 1012 | function hideWorldTooltip () |
| 1013 | { |
| 1014 | if (worldTooltip) |
| 1015 | { worldTooltip.hidden = true; } |
| 1016 | } |
| 1017 | |
| 1018 | /** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */ |
| 1019 | function updateWorldTooltip () |
| 1020 | { |
| 1021 | if (!worldTooltip || !view || !scene || uiBlocked()) |
| 1022 | { |
| 1023 | hideWorldTooltip(); |
| 1024 | return; |
| 1025 | } |
| 1026 | const canvas = scene.canvas; |
| 1027 | const rect = canvas.getBoundingClientRect(); |
| 1028 | const mouseX = GameInput.mousePosition.x - rect.left; |
| 1029 | const mouseY = GameInput.mousePosition.y - rect.top; |
| 1030 | if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height) |
| 1031 | { |
| 1032 | hideWorldTooltip(); |
| 1033 | return; |
| 1034 | } |
| 1035 | const entity = view.entityAtScreen(mouseX, mouseY); |
| 1036 | if (entity && entity.entityId !== view.localEntityId) |
| 1037 | { |
| 1038 | hideWorldTooltip(); |
| 1039 | return; |
| 1040 | } |
| 1041 | const tile = view.screenToTile(mouseX, mouseY); |
| 1042 | const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY)); |
| 1043 | if (!label) |
| 1044 | { |
| 1045 | hideWorldTooltip(); |
| 1046 | return; |
| 1047 | } |
| 1048 | worldTooltip.hidden = false; |
| 1049 | worldTooltip.textContent = label; |
| 1050 | worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`; |
| 1051 | worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`; |
| 1052 | } |
| 1053 | |
| 1054 | function blockTypeAt (view, tileX, tileY) |
| 1055 | { |
| 1056 | return blockAt(view, tileX, tileY)?.typeId ?? null; |
| 1057 | } |
| 1058 | |
| 1059 | function blockAt (view, tileX, tileY) |
| 1060 | { |
| 1061 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 1062 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 1063 | const snapshot = view.chunks.get(`${chunkX},${chunkY}`); |
| 1064 | if (!snapshot) |
| 1065 | { return null; } |
| 1066 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 1067 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 1068 | return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null; |
| 1069 | } |
| 1070 | |
| 1071 | function groundTypeAt (view, tileX, tileY) |
| 1072 | { |
| 1073 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 1074 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 1075 | const snapshot = view.chunks.get(`${chunkX},${chunkY}`); |
| 1076 | if (!snapshot) |
| 1077 | { return null; } |
| 1078 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 1079 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 1080 | return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId; |
| 1081 | } |
| 1082 | |
| 1083 | /** Best-effort client filter for approach destinations (server still authorizes paths). */ |
| 1084 | function isClientApproachable (tileX, tileY) |
| 1085 | { |
| 1086 | if (!view) |
| 1087 | { return true; } |
| 1088 | const groundId = groundTypeAt(view, tileX, tileY); |
| 1089 | const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null; |
| 1090 | if (groundDef && !groundDef.passable) |
| 1091 | { return false; } |
| 1092 | const block = blockAt(view, tileX, tileY); |
| 1093 | if (block?.typeId != null) |
| 1094 | { |
| 1095 | const blockDef = BLOCK_DEFINITIONS[block.typeId]; |
| 1096 | if (blockDef && !blockDef.passable) |
| 1097 | { return false; } |
| 1098 | } |
| 1099 | for (const entity of view.entitiesAtTile(tileX, tileY)) |
| 1100 | { |
| 1101 | if (entity.entityId === view.localEntityId) |
| 1102 | { continue; } |
| 1103 | if (entity.untargetable || entity.freeFlight) |
| 1104 | { continue; } |
| 1105 | return false; |
| 1106 | } |
| 1107 | return true; |
| 1108 | } |
| 1109 | |
| 1110 | function chebyshev (ax, ay, bx, by) |
| 1111 | { |
| 1112 | return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); |
| 1113 | } |