BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 53.8 KiB Download Raw
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
3import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
4import { OVERWORLD_ID } from "/shared/world/dimensions.js";
5import { GameSocket, defaultSocketUrl } from "../net/socket.js";
6import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
7import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
8import { WorldView } from "../render/worldView.js";
9import { initSocial } from "./social.js";
10import { initChat } from "./chat.js";
11import { initInventory } from "./inventory.js";
12import { initSkills } from "./skills.js";
13import { initSpells } from "./spells.js";
14import { initCrafting } from "./crafting.js";
15import { initAlchemy } from "./alchemy.js";
16import { initStamina } from "./stamina.js";
17import { initHealth } from "./health.js";
18import { initStatusEffects } from "./statusEffects.js";
19import { initContextMenu } from "./contextMenu.js";
20import { initDeath } from "./death.js";
21import { initToasts } from "./toasts.js";
22import { initQuests } from "./quests.js";
23import { initDialogue } from "./dialogue.js";
24import { initShop } from "./shop.js";
25import { initMarket } from "./market.js";
26import { initBounty } from "./bounty.js";
27import { initBarber } from "./barber.js";
28import { bindHairControls } from "./hairControls.js";
29import { bindCreateClothingControls } from "./createClothingControls.js";
30import { paintCharacterPreview } from "./characterPreview.js";
31import { initGraphicsSettings } from "./graphicsSettings.js";
32import { CraftingStationId } from "/shared/definitions/craftingStations.js";
33import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
34import { formatQuantity } from "/shared/items/formatQuantity.js";
35import { ItemId } from "/shared/definitions/items.js";
36import { countCoinsInSlots } from "/shared/items/inventory.js";
37
38const game = new Game();
39const hud = document.getElementById("hud");
40const overlay = document.getElementById("overlay");
41const statusEl = document.getElementById("status");
42const characterList = document.getElementById("character-list");
43const errorEl = document.getElementById("error");
44const assetLoadEl = document.getElementById("asset-load");
45const assetLoadBar = document.getElementById("asset-load-bar");
46const assetLoadLabel = document.getElementById("asset-load-label");
47const createCharacterOpen = document.getElementById("create-character-open");
48const worldTooltip = document.getElementById("world-tooltip");
49
50let socket;
51let session = null;
52let playing = false;
53let view = null;
54let graphicsSettingsUi = null;
55let scene = null;
56let gait = GAIT.walk;
57let catalog = { grounds: {}, blocks: {} };
58let social;
59let chat;
60let inventory;
61let skills;
62let spells;
63let crafting;
64let alchemy;
65let staminaUi;
66let healthUi;
67let statusEffectsUi;
68let contextMenu;
69let death;
70let toasts;
71let questsUi;
72let dialogueUi;
73let shop;
74let playZoomRaf = 0;
75let playZoomDelta = 0;
76let market;
77let bounty;
78let barber;
79let createHairControls;
80let createClothingControls;
81let createActiveTab = "appearance";
82let pendingPickup = null;
83/** @type {{ kind: "bank" | "doorway" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
84let pendingInteract = null;
85/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
86let approachMove = null;
87/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
88let leftClickConsumed = false;
89
90function consumeWorldClick ()
91{
92 leftClickConsumed = true;
93}
94
95function showError (message)
96{
97 errorEl.textContent = message ?? "";
98}
99
100function setAssetLoading (active, { loaded = 0, total = 0, phase = "" } = {})
101{
102 if (assetLoadEl)
103 { assetLoadEl.hidden = !active; }
104 if (characterList)
105 { characterList.hidden = active; }
106 if (createCharacterOpen)
107 { createCharacterOpen.hidden = active; }
108 if (!active)
109 { return; }
110 if (assetLoadBar && total > 0)
111 { assetLoadBar.value = Math.round((loaded / total) * 100); }
112 if (assetLoadLabel)
113 {
114 assetLoadLabel.textContent = phase
115 || (total > 0 ? `Loading assets… ${loaded}/${total}` : "Loading assets…");
116 }
117}
118
119function renderCharacters (characters)
120{
121 characterList.innerHTML = "";
122 for (const character of characters)
123 {
124 const row = document.createElement("div");
125 row.className = "character-row";
126 const pending = character.deletionScheduledAt
127 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
128 : "";
129 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
130 const play = document.createElement("button");
131 play.textContent = "Play";
132 play.disabled = !!character.deletionScheduledAt;
133 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
134 const del = document.createElement("button");
135 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
136 del.addEventListener("click", () =>
137 {
138 socket.send({
139 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
140 characterId: character.characterId
141 });
142 });
143 row.append(play, del);
144 characterList.append(row);
145 }
146}
147
148function uiBlocked ()
149{
150 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
151 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
152 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
153 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
154 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
155 || graphicsSettingsUi?.isBlocking?.()
156 || pointerOverSpellUi());
157}
158
159function pointerOverSpellUi ()
160{
161 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
162 if (!el)
163 { return false; }
164 return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
165}
166
167function applyGraphicsSettings (settings)
168{
169 view?.setGraphicsPrefs(settings);
170 if (socket && playing)
171 {
172 socket.send({
173 type: MessageType.setGraphicsSettings,
174 viewDistance: settings.viewDistance
175 });
176 }
177}
178
179function clearPendingPickup ()
180{
181 pendingPickup = null;
182}
183
184function clearPendingInteract ()
185{
186 pendingInteract = null;
187 approachMove = null;
188}
189
190function clearAllPendingActions ()
191{
192 clearPendingPickup();
193 clearPendingInteract();
194}
195
196function approachAdjacentTile (tileX, tileY)
197{
198 const local = view.entities.get(view.localEntityId);
199 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
200 {
201 approachMove = null;
202 return true;
203 }
204 let bestWalkable = null;
205 let bestWalkableDist = Infinity;
206 let bestAny = null;
207 let bestAnyDist = Infinity;
208 for (let dy = -1; dy <= 1; dy++)
209 {
210 for (let dx = -1; dx <= 1; dx++)
211 {
212 if (dx === 0 && dy === 0)
213 { continue; }
214 const destX = tileX + dx;
215 const destY = tileY + dy;
216 const dist = local
217 ? chebyshev(local.tileX, local.tileY, destX, destY)
218 : 0;
219 if (dist < bestAnyDist)
220 {
221 bestAnyDist = dist;
222 bestAny = { tileX: destX, tileY: destY };
223 }
224 if (isClientApproachable(destX, destY) && dist < bestWalkableDist)
225 {
226 bestWalkableDist = dist;
227 bestWalkable = { tileX: destX, tileY: destY };
228 }
229 }
230 }
231 const best = bestWalkable ?? bestAny;
232 if (!best)
233 { return false; }
234 if (
235 approachMove
236 && approachMove.focusX === tileX
237 && approachMove.focusY === tileY
238 && approachMove.destX === best.tileX
239 && approachMove.destY === best.tileY
240 )
241 { return false; }
242 approachMove = {
243 focusX: tileX,
244 focusY: tileY,
245 destX: best.tileX,
246 destY: best.tileY
247 };
248 socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY });
249 return false;
250}
251
252function requestOpenBank (tileX, tileY, { getCheques = false } = {})
253{
254 clearAllPendingActions();
255 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
256 const local = view?.entities.get(view.localEntityId);
257 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
258 { flushPendingInteract(); }
259 else
260 { approachAdjacentTile(tileX, tileY); }
261}
262
263function requestEnterDoorway (tileX, tileY)
264{
265 clearAllPendingActions();
266 pendingInteract = { kind: "doorway", tileX, tileY };
267 const local = view?.entities.get(view.localEntityId);
268 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
269 { flushPendingInteract(); }
270 else
271 { approachAdjacentTile(tileX, tileY); }
272}
273
274function requestOpenMarket (tileX, tileY)
275{
276 clearAllPendingActions();
277 pendingInteract = { kind: "market", tileX, tileY };
278 const local = view?.entities.get(view.localEntityId);
279 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
280 { flushPendingInteract(); }
281 else
282 { approachAdjacentTile(tileX, tileY); }
283}
284
285function requestOpenBounty (tileX, tileY)
286{
287 clearAllPendingActions();
288 pendingInteract = { kind: "bounty", tileX, tileY };
289 const local = view?.entities.get(view.localEntityId);
290 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
291 { flushPendingInteract(); }
292 else
293 { approachAdjacentTile(tileX, tileY); }
294}
295
296function requestOpenBarber (tileX, tileY)
297{
298 clearAllPendingActions();
299 pendingInteract = { kind: "barber", tileX, tileY };
300 const local = view?.entities.get(view.localEntityId);
301 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
302 { flushPendingInteract(); }
303 else
304 { approachAdjacentTile(tileX, tileY); }
305}
306
307function requestOpenCauldron (tileX, tileY)
308{
309 clearAllPendingActions();
310 pendingInteract = { kind: "cauldron", tileX, tileY };
311 const local = view?.entities.get(view.localEntityId);
312 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
313 { flushPendingInteract(); }
314 else
315 { approachAdjacentTile(tileX, tileY); }
316}
317
318function requestOpenFurnace (tileX, tileY)
319{
320 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
321}
322
323function requestOpenCraftStation (stationId, tileX, tileY)
324{
325 clearAllPendingActions();
326 pendingInteract = { kind: "station", stationId, tileX, tileY };
327 const local = view?.entities.get(view.localEntityId);
328 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
329 { flushPendingInteract(); }
330 else
331 { approachAdjacentTile(tileX, tileY); }
332}
333
334function requestMine (tileX, tileY)
335{
336 clearAllPendingActions();
337 pendingInteract = { kind: "mine", tileX, tileY };
338 const local = view?.entities.get(view.localEntityId);
339 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
340 { flushPendingInteract(); }
341 else
342 { approachAdjacentTile(tileX, tileY); }
343}
344
345function requestChop (tileX, tileY)
346{
347 clearAllPendingActions();
348 pendingInteract = { kind: "chop", tileX, tileY };
349 const local = view?.entities.get(view.localEntityId);
350 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
351 { flushPendingInteract(); }
352 else
353 { approachAdjacentTile(tileX, tileY); }
354}
355
356function requestPick (tileX, tileY)
357{
358 clearAllPendingActions();
359 pendingInteract = { kind: "pick", tileX, tileY };
360 const local = view?.entities.get(view.localEntityId);
361 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
362 { flushPendingInteract(); }
363 else
364 { approachAdjacentTile(tileX, tileY); }
365}
366
367function requestTalk (targetEntityId, purpose = null)
368{
369 clearAllPendingActions();
370 pendingInteract = { kind: "talk", targetEntityId, purpose };
371 const target = view?.entities.get(targetEntityId);
372 if (!target)
373 {
374 clearPendingInteract();
375 return;
376 }
377 if (approachAdjacentTile(target.tileX, target.tileY))
378 { flushPendingInteract(); }
379}
380
381function flushPendingInteract ()
382{
383 if (!pendingInteract || !view)
384 { return; }
385 const local = view.entities.get(view.localEntityId);
386 if (!local)
387 { return; }
388
389 if (pendingInteract.kind === "bank")
390 {
391 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
392 { return; }
393 const getCheques = !!pendingInteract.getCheques;
394 socket.send({ type: MessageType.openBank });
395 if (getCheques)
396 { inventory?.getBlankCheques(); }
397 clearPendingInteract();
398 return;
399 }
400
401 if (pendingInteract.kind === "doorway")
402 {
403 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
404 { return; }
405 socket.send({
406 type: MessageType.enterDoorway,
407 tileX: pendingInteract.tileX,
408 tileY: pendingInteract.tileY
409 });
410 clearPendingInteract();
411 return;
412 }
413
414 if (pendingInteract.kind === "market")
415 {
416 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
417 { return; }
418 socket.send({ type: MessageType.openMarket });
419 clearPendingInteract();
420 return;
421 }
422
423 if (pendingInteract.kind === "bounty")
424 {
425 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
426 { return; }
427 socket.send({ type: MessageType.openBounty });
428 clearPendingInteract();
429 return;
430 }
431
432 if (pendingInteract.kind === "barber")
433 {
434 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
435 { return; }
436 socket.send({ type: MessageType.openBarber });
437 clearPendingInteract();
438 return;
439 }
440
441 if (pendingInteract.kind === "cauldron")
442 {
443 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
444 { return; }
445 socket.send({ type: MessageType.openCauldron });
446 clearPendingInteract();
447 return;
448 }
449
450 if (pendingInteract.kind === "station")
451 {
452 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
453 { return; }
454 socket.send({
455 type: MessageType.openStation,
456 stationId: pendingInteract.stationId
457 });
458 clearPendingInteract();
459 return;
460 }
461
462 if (pendingInteract.kind === "mine")
463 {
464 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
465 { return; }
466 socket.send({
467 type: MessageType.mine,
468 tileX: pendingInteract.tileX,
469 tileY: pendingInteract.tileY
470 });
471 clearPendingInteract();
472 return;
473 }
474
475 if (pendingInteract.kind === "chop")
476 {
477 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
478 { return; }
479 socket.send({
480 type: MessageType.chop,
481 tileX: pendingInteract.tileX,
482 tileY: pendingInteract.tileY
483 });
484 clearPendingInteract();
485 return;
486 }
487
488 if (pendingInteract.kind === "pick")
489 {
490 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
491 { return; }
492 socket.send({
493 type: MessageType.pick,
494 tileX: pendingInteract.tileX,
495 tileY: pendingInteract.tileY
496 });
497 clearPendingInteract();
498 return;
499 }
500
501 if (pendingInteract.kind === "talk")
502 {
503 const target = view.entities.get(pendingInteract.targetEntityId);
504 if (!target)
505 {
506 clearPendingInteract();
507 return;
508 }
509 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
510 {
511 // Target may have moved — keep chasing.
512 approachAdjacentTile(target.tileX, target.tileY);
513 return;
514 }
515 socket.send({
516 type: MessageType.interact,
517 targetEntityId: pendingInteract.targetEntityId,
518 purpose: pendingInteract.purpose || undefined
519 });
520 clearPendingInteract();
521 }
522}
523
524function requestPickup (ground)
525{
526 if (!ground)
527 { return; }
528 clearPendingInteract();
529 pendingPickup = {
530 groundItemId: ground.groundItemId,
531 tileX: ground.tileX,
532 tileY: ground.tileY
533 };
534 const local = view.entities.get(view.localEntityId);
535 if (local && local.tileX === ground.tileX && local.tileY === ground.tileY)
536 {
537 flushPendingPickup();
538 return;
539 }
540 socket.send({ type: MessageType.moveTo, tileX: ground.tileX, tileY: ground.tileY });
541}
542
543function flushPendingPickup ()
544{
545 if (!pendingPickup || !view)
546 { return; }
547 const item = view.groundItems.get(pendingPickup.groundItemId);
548 if (!item)
549 {
550 clearPendingPickup();
551 return;
552 }
553 const local = view.entities.get(view.localEntityId);
554 if (!local)
555 { return; }
556 if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY)
557 { return; }
558 socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId });
559 clearPendingPickup();
560}
561
562function requestAttack (targetEntityId)
563{
564 clearAllPendingActions();
565 socket.send({ type: MessageType.attack, targetEntityId });
566}
567
568function isAttackableEntity (entity)
569{
570 if (!entity || entity.untargetable)
571 { return false; }
572 if (entity.canFight)
573 { return true; }
574 // Snapshots can omit canFight; mobs are still attackable via LMB.
575 return !!entity.mobTypeId && !entity.talkable;
576}
577
578function canTalkToEntity (entity)
579{
580 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
581}
582
583function handleLeftClick (mouseX, mouseY)
584{
585 const tile = view.screenToTile(mouseX, mouseY);
586 const armed = spells?.getArmedSpell?.();
587 if (armed?.target === "tile" && armed.canCast && spells.tryCastAtTile(tile.tileX, tile.tileY))
588 { return; }
589
590 const entity = view.entityAtScreen(mouseX, mouseY);
591 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
592 {
593 clearPendingPickup();
594 if (entity.characterId)
595 {
596 clearPendingInteract();
597 social.inspect(entity);
598 return;
599 }
600 // Dialogue (or shop/talkable) wins over attack as the default click.
601 if (canTalkToEntity(entity))
602 {
603 // Same intent as context-menu Talk / Shop so dialogue pin matches.
604 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
605 ? "talk"
606 : (entity.hasShop ? "shop" : "talk");
607 requestTalk(entity.entityId, purpose);
608 return;
609 }
610 if (isAttackableEntity(entity))
611 {
612 if (spells?.tryCastAtEntity?.(entity.entityId))
613 { return; }
614 requestAttack(entity.entityId);
615 return;
616 }
617 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
618 return;
619 }
620
621 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
622 if (ground)
623 { requestPickup(ground); }
624 else if (isBankTile(view, tile.tileX, tile.tileY))
625 { requestOpenBank(tile.tileX, tile.tileY); }
626 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
627 { requestEnterDoorway(tile.tileX, tile.tileY); }
628 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
629 { requestOpenMarket(tile.tileX, tile.tileY); }
630 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
631 { requestOpenBounty(tile.tileX, tile.tileY); }
632 else if (isBarberTile(view, tile.tileX, tile.tileY))
633 { requestOpenBarber(tile.tileX, tile.tileY); }
634 else if (isCauldronTile(view, tile.tileX, tile.tileY))
635 { requestOpenCauldron(tile.tileX, tile.tileY); }
636 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
637 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
638 else if (isAnvilTile(view, tile.tileX, tile.tileY))
639 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
640 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
641 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
642 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
643 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
644 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
645 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
646 else if (isLoomTile(view, tile.tileX, tile.tileY))
647 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
648 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
649 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
650 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
651 { requestMine(tile.tileX, tile.tileY); }
652 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
653 { requestChop(tile.tileX, tile.tileY); }
654 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
655 { requestPick(tile.tileX, tile.tileY); }
656 else
657 {
658 clearAllPendingActions();
659 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
660 }
661}
662
663function handleRightClick (event, mouseX, mouseY)
664{
665 event.preventDefault();
666 if (spells?.isTargeting?.())
667 {
668 spells.cancelTargeting();
669 view?.clearSpellTargetHighlight();
670 return;
671 }
672 const tile = view.screenToTile(mouseX, mouseY);
673 const items = [];
674 const walkTileX = tile.tileX;
675 const walkTileY = tile.tileY;
676
677 items.push({
678 label: "Walk here",
679 onSelect: () =>
680 {
681 clearAllPendingActions();
682 socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY });
683 }
684 });
685
686 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY))
687 {
688 if (entity.entityId === view.localEntityId)
689 { continue; }
690 const targetName = entityLabel(entity);
691 items.push({
692 label: `Follow ${targetName}`,
693 onSelect: () =>
694 {
695 clearAllPendingActions();
696 socket.send({ type: MessageType.follow, targetEntityId: entity.entityId });
697 }
698 });
699 if (entity.untargetable)
700 { continue; }
701 if (entity.hasShop)
702 {
703 items.push({
704 label: `Shop ${targetName}`,
705 onSelect: () => requestTalk(entity.entityId, "shop")
706 });
707 }
708 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
709 {
710 items.push({
711 label: `Talk to ${targetName}`,
712 onSelect: () => requestTalk(entity.entityId, "talk")
713 });
714 }
715 if (entity.characterId)
716 {
717 items.push({
718 label: `${targetName} info`,
719 onSelect: () =>
720 {
721 clearAllPendingActions();
722 social.inspect(entity);
723 }
724 });
725 }
726 items.push({
727 label: `Attack ${targetName}`,
728 onSelect: () => requestAttack(entity.entityId)
729 });
730 }
731
732 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
733 {
734 const name = groundLabel(ground);
735 items.push({
736 label: `Pick up ${name}`,
737 onSelect: () => requestPickup(ground)
738 });
739 }
740
741 if (isBankTile(view, tile.tileX, tile.tileY))
742 {
743 items.push({
744 label: "Bank",
745 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
746 });
747 items.push({
748 label: "Get Blank Cheques",
749 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
750 });
751 }
752
753 if (isDoorwayTile(view, tile.tileX, tile.tileY))
754 {
755 items.push({
756 label: "Enter",
757 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
758 });
759 }
760
761 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
762 {
763 items.push({
764 label: "Central Exchange",
765 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
766 });
767 }
768
769 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
770 {
771 items.push({
772 label: "Bounty Office",
773 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
774 });
775 }
776
777 if (isBarberTile(view, tile.tileX, tile.tileY))
778 {
779 items.push({
780 label: "Barber",
781 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
782 });
783 }
784
785 if (isCauldronTile(view, tile.tileX, tile.tileY))
786 {
787 items.push({
788 label: "Alchemy",
789 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
790 });
791 }
792
793 if (isFurnaceTile(view, tile.tileX, tile.tileY))
794 {
795 items.push({
796 label: "Smelt",
797 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
798 });
799 }
800
801 if (isAnvilTile(view, tile.tileX, tile.tileY))
802 {
803 items.push({
804 label: "Smith",
805 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
806 });
807 }
808
809 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
810 {
811 items.push({
812 label: "Woodwork",
813 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
814 });
815 }
816
817 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
818 {
819 items.push({
820 label: "Craft",
821 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
822 });
823 }
824
825 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
826 {
827 items.push({
828 label: "Spin",
829 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
830 });
831 }
832
833 if (isLoomTile(view, tile.tileX, tile.tileY))
834 {
835 items.push({
836 label: "Weave",
837 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
838 });
839 }
840
841 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
842 {
843 items.push({
844 label: "Tailor",
845 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
846 });
847 }
848
849 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
850 {
851 items.push({
852 label: "Mine",
853 onSelect: () => requestMine(tile.tileX, tile.tileY)
854 });
855 }
856
857 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
858 {
859 items.push({
860 label: "Chop",
861 onSelect: () => requestChop(tile.tileX, tile.tileY)
862 });
863 }
864
865 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
866 {
867 items.push({
868 label: "Pick",
869 onSelect: () => requestPick(tile.tileX, tile.tileY)
870 });
871 }
872
873 contextMenu.show(event.clientX, event.clientY, items);
874}
875
876function entityLabel (entity)
877{
878 const first = (entity?.firstName ?? "").trim();
879 const last = (entity?.lastName ?? "").trim();
880 const name = first && last ? `${first} ${last}` : (first || "target");
881 const level = entity?.level | 0;
882 if (entity?.mobTypeId && level > 0)
883 { return `Lv.${level} ${name}`; }
884 return name;
885}
886
887function groundLabel (ground)
888{
889 const name = (ground?.displayName ?? "").trim() || "item";
890 const qty = ground?.quantity ?? 1;
891 if (qty <= 1)
892 { return name; }
893 return `${name} (${formatQuantity(qty)})`;
894}
895
896function startPlay (payload)
897{
898 playing = true;
899 overlay.hidden = true;
900 hud.hidden = false;
901 const settingsToggle = document.getElementById("settings-toggle");
902 if (settingsToggle)
903 { settingsToggle.hidden = false; }
904 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
905 gait = payload.gait ?? GAIT.walk;
906 document.getElementById("gait").textContent = gait;
907 staminaUi?.show();
908 healthUi?.show();
909 statusEffectsUi?.show();
910 if (payload.stamina != null)
911 { staminaUi?.apply(payload.stamina); }
912 if (payload.health != null || payload.maxHealth != null)
913 {
914 healthUi?.apply({
915 current: payload.health ?? healthUi.getCurrent?.(),
916 max: payload.maxHealth ?? healthUi.getMax?.()
917 });
918 }
919 if (!scene)
920 {
921 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
922 game.loadScene(scene);
923 useNearestNeighbour(scene, game.images);
924 }
925 if (!view)
926 {
927 view = new WorldView(game, scene, catalog);
928 graphicsSettingsUi?.apply();
929 const ticker = new GameObject(0, 0, null, 10);
930 ticker.update = (dt) =>
931 {
932 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
933 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
934 if (!leftPressed && !leftHeld)
935 { leftClickConsumed = false; }
936 else if (!leftClickConsumed && playing && !uiBlocked())
937 {
938 leftClickConsumed = true;
939 const canvas = scene.canvas;
940 const rect = canvas.getBoundingClientRect();
941 const mouseX = GameInput.mousePosition.x - rect.left;
942 const mouseY = GameInput.mousePosition.y - rect.top;
943 handleLeftClick(mouseX, mouseY);
944 }
945 if (GameInput.isPressed(82) && !uiBlocked())
946 {
947 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
948 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
949 { return; }
950 socket.send({ type: MessageType.setGait, gait: next });
951 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
952 if (next === GAIT.walk)
953 {
954 gait = next;
955 document.getElementById("gait").textContent = gait;
956 }
957 }
958 if (playing && !death?.isBlocking())
959 {
960 flushPendingPickup();
961 flushPendingInteract();
962 social?.updateNametag(view, scene, view.localEntityId);
963 chat?.update(view, scene);
964 updateSpellTargetHighlight();
965 updateWorldTooltip();
966 }
967 else
968 {
969 hideWorldTooltip();
970 view?.clearSpellTargetHighlight();
971 }
972 view.update(dt);
973 };
974 scene.addObject(ticker);
975 window.addEventListener("resize", () =>
976 {
977 scene.size.x = window.innerWidth;
978 scene.size.y = window.innerHeight;
979 scene.g_fixSize();
980 useNearestNeighbour(scene, game.images);
981 });
982 window.addEventListener("wheel", (event) =>
983 {
984 if (!playing || uiBlocked())
985 { return; }
986 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
987 if (playZoomRaf)
988 { return; }
989 playZoomRaf = requestAnimationFrame(() =>
990 {
991 playZoomRaf = 0;
992 if (!view || !playZoomDelta)
993 { return; }
994 view.setZoom(view.zoom + playZoomDelta);
995 playZoomDelta = 0;
996 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
997 });
998 }, { passive: true });
999 scene.canvas.addEventListener("contextmenu", (event) =>
1000 {
1001 if (!playing || uiBlocked())
1002 { return; }
1003 const rect = scene.canvas.getBoundingClientRect();
1004 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
1005 });
1006 }
1007 view.setSettings(payload.settings ?? view.settings);
1008 chat?.syncSettings();
1009 view.worldHour = payload.worldTime?.hour ?? 12;
1010 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
1011 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
1012 view.setWorldSeason(payload.worldTime?.season);
1013 view.setLocalEntity(
1014 payload.entityId,
1015 payload.tileX,
1016 payload.tileY,
1017 payload.gait,
1018 payload.sex,
1019 payload.firstName,
1020 payload.lastName,
1021 payload.characterId,
1022 payload.layers,
1023 payload.health,
1024 payload.maxHealth
1025 );
1026 graphicsSettingsUi?.apply();
1027}
1028
1029async function main ()
1030{
1031 const authStatus = await fetchAuthStatus();
1032 updateAuthUi(authStatus);
1033 if (!authStatus.authenticated)
1034 {
1035 statusEl.textContent = "Sign in to play Questward.";
1036 showError("");
1037 return;
1038 }
1039
1040 setAssetLoading(true, { phase: "Loading catalog…" });
1041 catalog = await loadSpriteCatalog();
1042 const assetTotal = playImagesFromCatalog(catalog).length;
1043 setAssetLoading(true, { loaded: 0, total: assetTotal, phase: "Loading assets…" });
1044 await preloadCatalogImages(game, catalog, {
1045 onProgress ({ loaded, total })
1046 {
1047 setAssetLoading(true, { loaded, total });
1048 }
1049 });
1050 applySpriteSheets(game.images, catalog);
1051 if (!scene)
1052 {
1053 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1054 game.loadScene(scene);
1055 }
1056 setAssetLoading(false);
1057 statusEl.textContent = "Connecting…";
1058 createHairControls = bindHairControls({
1059 root: document.getElementById("create-hair"),
1060 resolveSpriteUrl (name)
1061 {
1062 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1063 },
1064 getSex: () => document.getElementById("sex")?.value ?? "male",
1065 getBag: () => null,
1066 hideHeadgear: true,
1067 onChange ()
1068 {
1069 if (createActiveTab === "clothing")
1070 { void refreshCreateClothingPreview(); }
1071 }
1072 });
1073 createClothingControls = bindCreateClothingControls({
1074 root: document.getElementById("create-clothing"),
1075 onChange ()
1076 {
1077 if (createActiveTab === "clothing")
1078 { void refreshCreateClothingPreview(); }
1079 }
1080 });
1081 initCreateTabs();
1082 document.getElementById("sex")?.addEventListener("change", () =>
1083 {
1084 createHairControls?.fillStyles();
1085 void createHairControls?.refreshPreview();
1086 if (createActiveTab === "clothing")
1087 { void refreshCreateClothingPreview(); }
1088 });
1089 void createHairControls?.refreshPreview();
1090 void refreshCreateClothingPreview();
1091 graphicsSettingsUi = initGraphicsSettings({
1092 onChange: applyGraphicsSettings,
1093 onSuppressWorldClick: consumeWorldClick
1094 });
1095 social = initSocial({
1096 socket: { send (payload) { socket.send(payload); } },
1097 MessageType
1098 });
1099 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1100 inventory = initInventory({
1101 socket: { send (payload) { socket.send(payload); } },
1102 MessageType,
1103 contextMenu,
1104 resolveSpriteUrl (name)
1105 {
1106 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1107 },
1108 getFriends ()
1109 {
1110 return social?.getFriends?.() ?? [];
1111 },
1112 getLocalName ()
1113 {
1114 const you = document.getElementById("you")?.textContent ?? "";
1115 return you.split("(")[0].trim() || "Unknown";
1116 }
1117 });
1118 skills = initSkills();
1119 spells = initSpells({
1120 socket: { send (payload) { socket.send(payload); } },
1121 MessageType
1122 });
1123 crafting = initCrafting({
1124 socket: { send (payload) { socket.send(payload); } },
1125 MessageType,
1126 getInventorySlots ()
1127 {
1128 return inventory?.getInventorySlots?.() ?? [];
1129 },
1130 getSkillLevel (skillId)
1131 {
1132 return skills?.skillLevel?.(skillId) ?? 1;
1133 }
1134 });
1135 alchemy = initAlchemy({
1136 socket: { send (payload) { socket.send(payload); } },
1137 MessageType,
1138 getInventorySlots ()
1139 {
1140 return inventory?.getInventorySlots?.() ?? [];
1141 }
1142 });
1143 staminaUi = initStamina();
1144 healthUi = initHealth();
1145 statusEffectsUi = initStatusEffects();
1146 toasts = initToasts();
1147 questsUi = initQuests({
1148 socket: { send (payload) { socket.send(payload); } },
1149 MessageType,
1150 toasts
1151 });
1152 dialogueUi = initDialogue({
1153 socket: { send (payload) { socket.send(payload); } },
1154 MessageType,
1155 getEntity (id)
1156 {
1157 if (id === "local")
1158 { return view?.entities.get(view.localEntityId) ?? null; }
1159 return view?.entities.get(id) ?? null;
1160 },
1161 captureSpeakerIcon (entityId, size = 64)
1162 {
1163 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1164 }
1165 });
1166 shop = initShop({
1167 socket: { send (payload) { socket.send(payload); } },
1168 MessageType,
1169 onSuppressWorldClick: consumeWorldClick,
1170 getCoinCount ()
1171 {
1172 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1173 },
1174 getInventorySlots ()
1175 {
1176 return inventory?.getInventorySlots?.() ?? [];
1177 }
1178 });
1179 market = initMarket({
1180 socket: { send (payload) { socket.send(payload); } },
1181 MessageType,
1182 onSuppressWorldClick: consumeWorldClick,
1183 getCoinCount ()
1184 {
1185 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1186 },
1187 getInventorySlots ()
1188 {
1189 return inventory?.getInventorySlots?.() ?? [];
1190 },
1191 getLocalCharacterId ()
1192 {
1193 return inventory?.getLocalCharacterId?.() ?? null;
1194 }
1195 });
1196 bounty = initBounty({
1197 socket: { send (payload) { socket.send(payload); } },
1198 MessageType,
1199 onSuppressWorldClick: consumeWorldClick,
1200 resolveSpriteUrl (name)
1201 {
1202 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1203 }
1204 });
1205 barber = initBarber({
1206 socket: { send (payload) { socket.send(payload); } },
1207 MessageType,
1208 onSuppressWorldClick: consumeWorldClick,
1209 resolveSpriteUrl (name)
1210 {
1211 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1212 },
1213 getInventoryBag ()
1214 {
1215 return {
1216 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1217 inventory: inventory?.getInventorySlots?.() ?? []
1218 };
1219 }
1220 });
1221 chat = initChat({
1222 socket: { send (payload) { socket.send(payload); } },
1223 MessageType,
1224 getSettings: () => view?.settings
1225 });
1226 death = initDeath({
1227 socket: { send (payload) { socket.send(payload); } },
1228 MessageType
1229 });
1230 game.startGame();
1231 useNearestNeighbour(scene, game.images);
1232
1233 socket = new GameSocket(defaultSocketUrl(), (message) =>
1234 {
1235 switch (message.type)
1236 {
1237 case MessageType.session:
1238 session = message;
1239 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1240 renderCharacters(message.characters);
1241 break;
1242 case MessageType.characterList:
1243 renderCharacters(message.characters);
1244 if (!playing)
1245 { overlay.hidden = false; }
1246 break;
1247 case MessageType.enterWorld:
1248 closeCreateModal();
1249 startPlay(message);
1250 inventory?.setLocalCharacterId(message.characterId);
1251 toasts?.applyRestartStatus?.(message.restartStatus);
1252 socket.send({ type: MessageType.requestQuests });
1253 break;
1254 case MessageType.chunkSnapshot:
1255 view?.applySnapshot(message);
1256 break;
1257 case MessageType.dimensionChanged:
1258 if (view)
1259 {
1260 view.setDimensionId(message.dimensionId);
1261 view.setDimensionModes(message.lightingMode, message.seasonMode);
1262 view.clearAllChunks();
1263 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1264 {
1265 view.moveEntity({
1266 entityId: view.localEntityId,
1267 tileX: message.tileX,
1268 tileY: message.tileY
1269 });
1270 }
1271 }
1272 break;
1273 case MessageType.chunkDelta:
1274 for (const tile of message.tiles ?? [])
1275 {
1276 view?.updateAuthoredTile(
1277 message.chunkX,
1278 message.chunkY,
1279 tile.localX,
1280 tile.localY,
1281 { ground: tile.ground, block: tile.block, light: tile.light }
1282 );
1283 }
1284 break;
1285 case MessageType.unsubscribeChunk:
1286 view?.removeChunk(message.chunkX, message.chunkY);
1287 break;
1288 case MessageType.entitySpawn:
1289 view?.spawnEntity(message);
1290 break;
1291 case MessageType.entityMove:
1292 view?.moveEntity(message);
1293 if (message.entityId === view?.localEntityId && message.gait)
1294 {
1295 gait = message.gait;
1296 document.getElementById("gait").textContent = gait;
1297 }
1298 break;
1299 case MessageType.entityDespawn:
1300 view?.despawnEntity(message.entityId);
1301 break;
1302 case MessageType.entityAppearance:
1303 view?.setAppearance(message);
1304 break;
1305 case MessageType.groundItemAppear:
1306 view?.upsertGroundItem(message);
1307 break;
1308 case MessageType.groundItemDespawn:
1309 view?.despawnGroundItem(message.groundItemId);
1310 break;
1311 case MessageType.inventory:
1312 inventory?.handleInventory(message);
1313 crafting?.refresh();
1314 alchemy?.refresh();
1315 shop?.refresh();
1316 market?.refresh();
1317 break;
1318 case MessageType.skills:
1319 skills?.render(message.skills);
1320 crafting?.refresh();
1321 break;
1322 case MessageType.spells:
1323 case MessageType.spellsUpdated:
1324 spells?.render(message);
1325 break;
1326 case MessageType.spellArmed:
1327 spells?.handleSpellArmed(message);
1328 break;
1329 case MessageType.spellDisarmed:
1330 spells?.handleSpellDisarmed();
1331 break;
1332 case MessageType.spellProjectile:
1333 view?.spawnSpellProjectileFx(message);
1334 break;
1335 case MessageType.spellFizzle:
1336 view?.spawnSpellFizzleFx(message);
1337 if (message.casterId === view?.localEntityId)
1338 { toasts?.show("Failed to cast spell"); }
1339 break;
1340 case MessageType.spellCastFlash:
1341 view?.spawnSpellCastFlash(message);
1342 break;
1343 case MessageType.spellLightAppear:
1344 case MessageType.spellLightUpdate:
1345 view?.setSpellLight(message);
1346 break;
1347 case MessageType.spellLightRemove:
1348 view?.removeSpellLight(message);
1349 break;
1350 case MessageType.stamina:
1351 staminaUi?.apply(message);
1352 if (message.gait)
1353 {
1354 gait = message.gait;
1355 document.getElementById("gait").textContent = gait;
1356 }
1357 break;
1358 case MessageType.statusEffects:
1359 view?.setLocalBlind(!!message.blind);
1360 statusEffectsUi?.apply(message);
1361 break;
1362 case MessageType.bankSnapshot:
1363 inventory?.handleBank(message);
1364 break;
1365 case MessageType.cauldronSnapshot:
1366 alchemy?.handleSnapshot(message);
1367 break;
1368 case MessageType.pigeonDispatched:
1369 inventory?.handlePigeonDispatched(message);
1370 break;
1371 case MessageType.pigeonDelivered:
1372 inventory?.handlePigeonDelivered(message);
1373 break;
1374 case MessageType.characterSearchResult:
1375 inventory?.handleCharacterSearch(message);
1376 break;
1377 case MessageType.craftResult:
1378 crafting?.handleCraftResult(message);
1379 break;
1380 case MessageType.worldStatus:
1381 if (view)
1382 {
1383 view.setSettings(message.settings ?? view.settings);
1384 view.worldHour = message.worldTime?.hour ?? view.worldHour;
1385 view.setWorldSeason(message.worldTime?.season);
1386 chat?.syncSettings();
1387 }
1388 toasts?.applyRestartStatus?.(message.restartStatus);
1389 break;
1390 case MessageType.restartStatus:
1391 toasts?.applyRestartStatus?.(message.restartStatus);
1392 break;
1393 case MessageType.chatBubble:
1394 chat?.showBubble(message);
1395 break;
1396 case MessageType.friends:
1397 social?.handleFriends(message);
1398 break;
1399 case MessageType.combatSwing:
1400 view?.spawnCombatSwing(message);
1401 break;
1402 case MessageType.combatProjectile:
1403 view?.spawnPhysicalProjectileFx({
1404 ...message,
1405 sprite: "fx:projectile:arrow"
1406 });
1407 break;
1408 case MessageType.combatNoArrows:
1409 toasts?.show("Out of arrows!");
1410 break;
1411 case MessageType.gatherSwing:
1412 case MessageType.tileShove:
1413 view?.spawnGatherSwing(message);
1414 break;
1415 case MessageType.stationOpen:
1416 if (message.stationId)
1417 { crafting?.openStation(message.stationId); }
1418 break;
1419 case MessageType.shopOpen:
1420 shop?.handleShopOpen(message);
1421 break;
1422 case MessageType.shopClosed:
1423 shop?.handleShopClosed(message);
1424 break;
1425 case MessageType.marketOpen:
1426 market?.handleOpen(message);
1427 break;
1428 case MessageType.marketClosed:
1429 market?.handleClosed(message);
1430 break;
1431 case MessageType.marketTrade:
1432 market?.handleTrade(message);
1433 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
1434 break;
1435 case MessageType.bountySnapshot:
1436 bounty?.handleSnapshot(message);
1437 break;
1438 case MessageType.closeBounty:
1439 bounty?.handleClosed(message);
1440 break;
1441 case MessageType.characterBounty:
1442 bounty?.handleCharacterBounty(message);
1443 social?.handleCharacterBounty(message);
1444 break;
1445 case MessageType.barberSnapshot:
1446 barber?.handleSnapshot(message);
1447 break;
1448 case MessageType.closeBarber:
1449 barber?.handleClosed(message);
1450 break;
1451 case MessageType.itemBubble:
1452 chat?.showItemBubble(message);
1453 break;
1454 case MessageType.gatherComplete:
1455 crafting?.refresh();
1456 break;
1457 case MessageType.combatHit:
1458 {
1459 const applyHit = () =>
1460 {
1461 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1462 view?.flashDamage(message.targetId);
1463 view?.spawnDamageNumber(message.targetId, message.damage);
1464 if (message.targetId === view?.localEntityId)
1465 {
1466 healthUi?.apply({
1467 current: message.health,
1468 max: message.maxHealth
1469 });
1470 }
1471 };
1472 if (!view?.deferCombatHit?.(message, applyHit))
1473 { applyHit(); }
1474 break;
1475 }
1476 case MessageType.combatMiss:
1477 view?.markProjectileMiss?.(message);
1478 break;
1479 case MessageType.combatBlock:
1480 {
1481 const applyBlock = () =>
1482 {
1483 view?.flashDamage(message.targetId);
1484 if (message.health != null)
1485 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
1486 };
1487 if (!view?.deferCombatHit?.(message, applyBlock))
1488 { applyBlock(); }
1489 break;
1490 }
1491 case MessageType.entityHealth:
1492 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1493 if (message.entityId === view?.localEntityId)
1494 {
1495 healthUi?.apply({
1496 current: message.health,
1497 max: message.maxHealth
1498 });
1499 }
1500 break;
1501 case MessageType.skillLevelUp:
1502 view?.spawnSkillLevelUp(message.entityId, message);
1503 if (message.entityId === view?.localEntityId)
1504 {
1505 const name = message.displayName ?? message.skillId ?? "Skill";
1506 toasts?.show(`${name} level ${message.level}!`);
1507 }
1508 break;
1509 case MessageType.playerDied:
1510 clearAllPendingActions();
1511 contextMenu?.hide();
1512 death?.show();
1513 if (message.entityId === view?.localEntityId)
1514 {
1515 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
1516 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
1517 }
1518 break;
1519 case MessageType.playerRespawned:
1520 death?.hide();
1521 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1522 if (message.entityId === view?.localEntityId)
1523 {
1524 healthUi?.apply({
1525 current: message.health,
1526 max: message.maxHealth
1527 });
1528 }
1529 if (message.stamina != null || message.maxStamina != null)
1530 {
1531 staminaUi?.apply({
1532 current: message.stamina ?? staminaUi.getCurrent?.(),
1533 max: message.maxStamina ?? staminaUi.getMax?.()
1534 });
1535 }
1536 break;
1537 case MessageType.error:
1538 if (playing)
1539 { toasts?.show(message.message); }
1540 else
1541 {
1542 const createPanel = document.getElementById("create-panel");
1543 const createError = document.getElementById("create-error");
1544 if (createPanel && !createPanel.hidden && createError)
1545 { createError.textContent = message.message ?? ""; }
1546 else
1547 { showError(message.message); }
1548 }
1549 social?.showError(message.message);
1550 break;
1551 case MessageType.toast:
1552 if (playing)
1553 { toasts?.show(message.message); }
1554 break;
1555 case MessageType.questsSnapshot:
1556 questsUi?.applySnapshot(message);
1557 break;
1558 case MessageType.questStepComplete:
1559 questsUi?.handleStepComplete(message);
1560 break;
1561 case MessageType.dialogueStep:
1562 dialogueUi?.handleStep(message);
1563 break;
1564 case MessageType.dialogueChoices:
1565 dialogueUi?.handleChoices(message);
1566 break;
1567 case MessageType.dialogueClose:
1568 dialogueUi?.handleClose(message);
1569 break;
1570 case MessageType.forceLogout:
1571 returnToMenu(message.reason);
1572 break;
1573 }
1574 }, {
1575 onClose (event)
1576 {
1577 if (playing)
1578 { returnToMenu(event.reason || "Disconnected from server."); }
1579 }
1580 });
1581 await socket.connect();
1582 if (typeof window !== "undefined")
1583 {
1584 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
1585 {
1586 crafting?.openStation(stationId);
1587 };
1588 }
1589}
1590
1591function returnToMenu (reason = "")
1592{
1593 playing = false;
1594 clearAllPendingActions();
1595 social?.reset();
1596 chat?.reset();
1597 inventory?.reset();
1598 crafting?.reset();
1599 alchemy?.reset();
1600 staminaUi?.hide();
1601 healthUi?.hide();
1602 statusEffectsUi?.hide();
1603 skills?.hide();
1604 spells?.hide();
1605 contextMenu?.hide();
1606 death?.reset();
1607 shop?.close({ notifyServer: false });
1608 bounty?.close();
1609 barber?.close();
1610 questsUi?.reset();
1611 dialogueUi?.reset();
1612 hideWorldTooltip();
1613 if (view)
1614 { view.clearPlaySession(); }
1615 overlay.hidden = false;
1616 hud.hidden = true;
1617 const settingsToggle = document.getElementById("settings-toggle");
1618 if (settingsToggle)
1619 { settingsToggle.hidden = true; }
1620 graphicsSettingsUi?.close();
1621 if (reason)
1622 { statusEl.textContent = reason; }
1623}
1624
1625document.getElementById("create-character-open")?.addEventListener("click", () =>
1626{
1627 showError("");
1628 const createError = document.getElementById("create-error");
1629 if (createError)
1630 { createError.textContent = ""; }
1631 document.getElementById("create-backdrop").hidden = false;
1632 document.getElementById("create-panel").hidden = false;
1633 setCreateTab("appearance");
1634 void createHairControls?.refreshPreview();
1635});
1636
1637function closeCreateModal ()
1638{
1639 document.getElementById("create-backdrop").hidden = true;
1640 document.getElementById("create-panel").hidden = true;
1641}
1642
1643document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
1644document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
1645
1646document.getElementById("create-form").addEventListener("submit", (event) =>
1647{
1648 event.preventDefault();
1649 showError("");
1650 const createError = document.getElementById("create-error");
1651 if (createError)
1652 { createError.textContent = ""; }
1653 socket.send({
1654 type: MessageType.createCharacter,
1655 firstName: document.getElementById("first-name").value,
1656 lastName: document.getElementById("last-name").value,
1657 sex: document.getElementById("sex").value,
1658 hair: createHairControls?.currentHair?.() ?? null,
1659 clothing: createClothingControls?.currentClothing?.() ?? null
1660 });
1661});
1662
1663function initCreateTabs ()
1664{
1665 const tabs = document.querySelectorAll(".create-tab");
1666 for (const tab of tabs)
1667 {
1668 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
1669 }
1670 setCreateTab("appearance");
1671}
1672
1673function setCreateTab (name)
1674{
1675 createActiveTab = name === "clothing" ? "clothing" : "appearance";
1676 for (const tab of document.querySelectorAll(".create-tab"))
1677 {
1678 const on = tab.dataset.createTab === createActiveTab;
1679 tab.classList.toggle("active", on);
1680 tab.setAttribute("aria-selected", on ? "true" : "false");
1681 }
1682 for (const pane of document.querySelectorAll("[data-create-pane]"))
1683 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
1684 if (createActiveTab === "clothing")
1685 { void refreshCreateClothingPreview(); }
1686 else
1687 { void createHairControls?.refreshPreview(); }
1688}
1689
1690async function refreshCreateClothingPreview ()
1691{
1692 const canvas = document.getElementById("create-clothing-preview");
1693 if (!canvas || !createClothingControls)
1694 { return; }
1695 try
1696 {
1697 await paintCharacterPreview(canvas, {
1698 sex: document.getElementById("sex")?.value ?? "male",
1699 bag: createClothingControls.previewBag(),
1700 hair: createHairControls?.currentHair?.() ?? null,
1701 hideHeadgear: true,
1702 resolveSpriteUrl (name)
1703 {
1704 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1705 },
1706 scale: 4
1707 });
1708 }
1709 catch (error)
1710 { console.warn(error); }
1711}
1712
1713document.getElementById("leave").addEventListener("click", () =>
1714{
1715 socket.send({ type: MessageType.leaveWorld });
1716 returnToMenu();
1717});
1718
1719main().catch((error) =>
1720{
1721 showError(error.message);
1722 console.error(error);
1723});
1724
1725function isBankTile (view, tileX, tileY)
1726{
1727 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
1728}
1729
1730function isDoorwayTile (view, tileX, tileY)
1731{
1732 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
1733}
1734
1735function isMarketplaceTile (view, tileX, tileY)
1736{
1737 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1738}
1739
1740function isBountyOfficeTile (view, tileX, tileY)
1741{
1742 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
1743}
1744
1745function isBarberTile (view, tileX, tileY)
1746{
1747 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
1748}
1749
1750function isCauldronTile (view, tileX, tileY)
1751{
1752 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
1753}
1754
1755function isFurnaceTile (view, tileX, tileY)
1756{
1757 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
1758}
1759
1760function isAnvilTile (view, tileX, tileY)
1761{
1762 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
1763}
1764
1765function isWoodworkingBenchTile (view, tileX, tileY)
1766{
1767 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
1768}
1769
1770function isCraftingBenchTile (view, tileX, tileY)
1771{
1772 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1773}
1774
1775function isSpinningWheelTile (view, tileX, tileY)
1776{
1777 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
1778}
1779
1780function isLoomTile (view, tileX, tileY)
1781{
1782 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
1783}
1784
1785function isTailorBenchTile (view, tileX, tileY)
1786{
1787 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
1788}
1789
1790function isOreBoulderTile (view, tileX, tileY)
1791{
1792 const block = blockAt(view, tileX, tileY);
1793 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
1794}
1795
1796function isChopableTreeTile (view, tileX, tileY)
1797{
1798 return isChopableTreeBlock(blockAt(view, tileX, tileY));
1799}
1800
1801function isPickablePlantTile (view, tileX, tileY)
1802{
1803 return isPickablePlantBlock(blockAt(view, tileX, tileY));
1804}
1805
1806function updateSpellTargetHighlight ()
1807{
1808 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
1809 {
1810 view?.clearSpellTargetHighlight();
1811 return;
1812 }
1813 const canvas = scene?.canvas;
1814 if (!canvas)
1815 { return; }
1816 const rect = canvas.getBoundingClientRect();
1817 const mouseX = GameInput.mousePosition.x - rect.left;
1818 const mouseY = GameInput.mousePosition.y - rect.top;
1819 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1820 {
1821 view.clearSpellTargetHighlight();
1822 return;
1823 }
1824 const tile = view.screenToTile(mouseX, mouseY);
1825 const local = view.entities.get(view.localEntityId);
1826 const inRange = !local
1827 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
1828 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
1829}
1830
1831function hideWorldTooltip ()
1832{
1833 if (worldTooltip)
1834 { worldTooltip.hidden = true; }
1835}
1836
1837/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
1838function updateWorldTooltip ()
1839{
1840 if (!worldTooltip || !view || !scene || uiBlocked())
1841 {
1842 hideWorldTooltip();
1843 return;
1844 }
1845 const canvas = scene.canvas;
1846 const rect = canvas.getBoundingClientRect();
1847 const mouseX = GameInput.mousePosition.x - rect.left;
1848 const mouseY = GameInput.mousePosition.y - rect.top;
1849 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1850 {
1851 hideWorldTooltip();
1852 return;
1853 }
1854 const entity = view.entityAtScreen(mouseX, mouseY);
1855 if (entity && entity.entityId !== view.localEntityId)
1856 {
1857 const label = entityLabel(entity);
1858 worldTooltip.hidden = false;
1859 worldTooltip.textContent = label;
1860 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
1861 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
1862 return;
1863 }
1864 const tile = view.screenToTile(mouseX, mouseY);
1865 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
1866 if (!label)
1867 {
1868 hideWorldTooltip();
1869 return;
1870 }
1871 worldTooltip.hidden = false;
1872 worldTooltip.textContent = label;
1873 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
1874 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
1875}
1876
1877function blockTypeAt (view, tileX, tileY)
1878{
1879 return blockAt(view, tileX, tileY)?.typeId ?? null;
1880}
1881
1882function blockAt (view, tileX, tileY)
1883{
1884 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1885 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1886 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1887 if (!snapshot)
1888 { return null; }
1889 const localX = tileX - chunkX * CHUNK_SIZE;
1890 const localY = tileY - chunkY * CHUNK_SIZE;
1891 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
1892}
1893
1894function groundTypeAt (view, tileX, tileY)
1895{
1896 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1897 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1898 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1899 if (!snapshot)
1900 { return null; }
1901 const localX = tileX - chunkX * CHUNK_SIZE;
1902 const localY = tileY - chunkY * CHUNK_SIZE;
1903 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
1904}
1905
1906/** Best-effort client filter for approach destinations (server still authorizes paths). */
1907function isClientApproachable (tileX, tileY)
1908{
1909 if (!view)
1910 { return true; }
1911 const groundId = groundTypeAt(view, tileX, tileY);
1912 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
1913 if (groundDef && !groundDef.passable)
1914 { return false; }
1915 const block = blockAt(view, tileX, tileY);
1916 if (block?.typeId != null)
1917 {
1918 const blockDef = BLOCK_DEFINITIONS[block.typeId];
1919 if (blockDef && !blockDef.passable)
1920 { return false; }
1921 }
1922 for (const entity of view.entitiesAtTile(tileX, tileY))
1923 {
1924 if (entity.entityId === view.localEntityId)
1925 { continue; }
1926 if (entity.untargetable || entity.freeFlight)
1927 { continue; }
1928 return false;
1929 }
1930 return true;
1931}
1932
1933function chebyshev (ax, ay, bx, by)
1934{
1935 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
1936}
1937
1938function updateAuthUi (authStatus)
1939{
1940 const signIn = document.getElementById("auth-sign-in");
1941 const signOut = document.getElementById("auth-sign-out");
1942 const exportLink = document.getElementById("auth-export");
1943 if (signIn)
1944 {
1945 signIn.hidden = !!authStatus?.authenticated;
1946 signIn.href = loginUrl("/");
1947 }
1948 if (signOut)
1949 {
1950 signOut.hidden = !authStatus?.authenticated;
1951 signOut.href = logoutUrl("/");
1952 }
1953 if (exportLink)
1954 { exportLink.hidden = !authStatus?.authenticated; }
1955 if (authStatus?.authenticated && !session)
1956 {
1957 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
1958 }
1959}