BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 70.7 KiB Download Raw
1import { MessageType, GAIT, CHUNK_SIZE, STATIC_CHUNK_RADIUS } 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 { findPathToNearestGoal } from "/shared/navigation/bfs.js";
6import { GameSocket, defaultSocketUrl } from "../net/socket.js";
7import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
8import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
9import { WorldView } from "../render/worldView.js";
10import { initSocial } from "./social.js";
11import { initChat } from "./chat.js";
12import { initInventory } from "./inventory.js";
13import { initSkills } from "./skills.js";
14import { initSpells } from "./spells.js";
15import { initCrafting } from "./crafting.js";
16import { initAlchemy } from "./alchemy.js";
17import { initTipArrows } from "./tipArrows.js";
18import { initStamina } from "./stamina.js";
19import { initHealth } from "./health.js";
20import { initStatusEffects } from "./statusEffects.js";
21import { initContextMenu } from "./contextMenu.js";
22import { initDeath } from "./death.js";
23import { initToasts } from "./toasts.js";
24import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
25import { initQuests } from "./quests.js";
26import { initDialogue } from "./dialogue.js";
27import { initShop } from "./shop.js";
28import { initMarket } from "./market.js";
29import { initBounty } from "./bounty.js";
30import { initBarber } from "./barber.js";
31import { bindHairControls } from "./hairControls.js";
32import { bindCreateClothingControls } from "./createClothingControls.js";
33import { paintCharacterPreview } from "./characterPreview.js";
34import { initGraphicsSettings } from "./graphicsSettings.js";
35import { CraftingStationId } from "/shared/definitions/craftingStations.js";
36import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
37import { formatQuantity } from "/shared/items/formatQuantity.js";
38import { ItemId, itemDefinition } from "/shared/definitions/items.js";
39import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
40import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
41import { countCoinsInSlots } from "/shared/items/inventory.js";
42
43const game = new Game();
44const hud = document.getElementById("hud");
45const overlay = document.getElementById("overlay");
46const statusEl = document.getElementById("status");
47const characterList = document.getElementById("character-list");
48const errorEl = document.getElementById("error");
49const assetLoadEl = document.getElementById("asset-load");
50const assetLoadBar = document.getElementById("asset-load-bar");
51const assetLoadLabel = document.getElementById("asset-load-label");
52const createCharacterOpen = document.getElementById("create-character-open");
53const worldTooltip = document.getElementById("world-tooltip");
54
55let socket;
56let session = null;
57let playing = false;
58let view = null;
59let graphicsSettingsUi = null;
60let scene = null;
61let gait = GAIT.walk;
62let catalog = { grounds: {}, blocks: {} };
63let social;
64let chat;
65let inventory;
66let skills;
67let spells;
68let crafting;
69let alchemy;
70let staminaUi;
71let healthUi;
72let statusEffectsUi;
73let contextMenu;
74let death;
75let toasts;
76let questsUi;
77let dialogueUi;
78let shop;
79let playZoomRaf = 0;
80let playZoomDelta = 0;
81let market;
82let bounty;
83let barber;
84let createHairControls;
85let createClothingControls;
86let createActiveTab = "appearance";
87let pendingPickup = null;
88/** @type {{ kind: "bank" | "doorway" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | { kind: "market" | "bounty" | "barber", tileX: number, tileY: number } | null } */
89let pendingInteract = null;
90/**
91 * Block/NPC the player currently has a station UI open for.
92 * Closed automatically when Chebyshev distance exceeds 1.
93 * @type {null | { kind: "bank" | "station" | "cauldron" | "market" | "bounty" | "barber", tileX: number, tileY: number } | { kind: "shop" | "dialogue", entityId: number }}
94 */
95let uiFocus = null;
96/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
97let approachMove = null;
98/** Client-tracked follow target; server follow owns gait while this is set. */
99let followTargetId = null;
100/** Destination of the active click/approach moveTo for autorun distance checks. */
101let moveDest = null;
102/** Entity / tile focus for server-driven approach (attack, cast) — no client moveTo. */
103let autorunFocusEntityId = null;
104let autorunFocusTile = null;
105/** After stamina hits 0 while autorunning, wait until ≥50% before running again. */
106let autorunWaitingStamina = false;
107/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
108let leftClickConsumed = false;
109
110const AUTORUN_DISTANCE_TILES = 3;
111const AUTORUN_STAMINA_RESUME_RATIO = 0.5;
112
113function sendPlayerMoveTo (tileX, tileY)
114{
115 followTargetId = null;
116 clearAutorunFocus();
117 moveDest = { tileX: tileX | 0, tileY: tileY | 0 };
118 socket.send({ type: MessageType.moveTo, tileX: moveDest.tileX, tileY: moveDest.tileY });
119 syncAutorun();
120}
121
122function sendPlayerFollow (targetEntityId)
123{
124 followTargetId = targetEntityId | 0;
125 moveDest = null;
126 clearAutorunFocus();
127 autorunWaitingStamina = false;
128 socket.send({ type: MessageType.follow, targetEntityId: followTargetId });
129}
130
131function clearAutorunFocus ()
132{
133 autorunFocusEntityId = null;
134 autorunFocusTile = null;
135}
136
137function setAutorunFocusEntity (entityId)
138{
139 moveDest = null;
140 autorunFocusTile = null;
141 autorunFocusEntityId = entityId | 0;
142 syncAutorun();
143}
144
145function setAutorunFocusTile (tileX, tileY)
146{
147 moveDest = null;
148 autorunFocusEntityId = null;
149 autorunFocusTile = { tileX: tileX | 0, tileY: tileY | 0 };
150 syncAutorun();
151}
152
153function resolveAutorunDest ()
154{
155 if (moveDest)
156 { return moveDest; }
157 if (autorunFocusEntityId != null)
158 {
159 const target = view?.entities?.get(autorunFocusEntityId);
160 if (!target)
161 { return null; }
162 return { tileX: target.tileX | 0, tileY: target.tileY | 0 };
163 }
164 return autorunFocusTile;
165}
166
167function localEntityIsMoving (local)
168{
169 if (!local)
170 { return false; }
171 if (local.lerpStarted != null)
172 { return true; }
173 const dx = (local.visualX ?? 0) - (local.targetX ?? local.visualX ?? 0);
174 const dy = (local.visualY ?? 0) - (local.targetY ?? local.visualY ?? 0);
175 return (dx * dx + dy * dy) > 0.25;
176}
177
178function requestGaitIfNeeded (next)
179{
180 if (next !== GAIT.walk && next !== GAIT.run)
181 { return; }
182 if (next === gait)
183 { return; }
184 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 0) <= 0)
185 { return; }
186 socket.send({ type: MessageType.setGait, gait: next });
187 if (next === GAIT.walk)
188 {
189 gait = next;
190 const el = document.getElementById("gait");
191 if (el)
192 { el.textContent = gait; }
193 }
194}
195
196function syncAutorun ()
197{
198 if (!playing || followTargetId != null)
199 { return; }
200 const settings = graphicsSettingsUi?.getSettings?.() ?? {};
201 if (settings.autorun !== "on")
202 { return; }
203 const local = view?.entities?.get(view.localEntityId);
204 const dest = resolveAutorunDest();
205 if (!local || !dest)
206 { return; }
207 if (moveDest && local.tileX === moveDest.tileX && local.tileY === moveDest.tileY)
208 {
209 moveDest = null;
210 autorunWaitingStamina = false;
211 requestGaitIfNeeded(GAIT.walk);
212 return;
213 }
214 // Attack / cast approach is server-pathed — only run while tiles are changing.
215 if (!moveDest && !localEntityIsMoving(local))
216 {
217 requestGaitIfNeeded(GAIT.walk);
218 return;
219 }
220 const dist = chebyshev(local.tileX, local.tileY, dest.tileX, dest.tileY);
221 const wantRun = dist > AUTORUN_DISTANCE_TILES;
222 const current = staminaUi?.getCurrent?.() ?? 0;
223 const max = Math.max(1, staminaUi?.getMax?.() ?? 1);
224 if (gait === GAIT.run && current <= 0)
225 { autorunWaitingStamina = true; }
226 if (autorunWaitingStamina)
227 {
228 if (wantRun && current / max >= AUTORUN_STAMINA_RESUME_RATIO)
229 {
230 autorunWaitingStamina = false;
231 requestGaitIfNeeded(GAIT.run);
232 }
233 else
234 { requestGaitIfNeeded(GAIT.walk); }
235 return;
236 }
237 if (wantRun)
238 {
239 if (current <= 0)
240 {
241 autorunWaitingStamina = true;
242 requestGaitIfNeeded(GAIT.walk);
243 }
244 else
245 { requestGaitIfNeeded(GAIT.run); }
246 }
247 else
248 { requestGaitIfNeeded(GAIT.walk); }
249}
250
251function consumeWorldClick ()
252{
253 leftClickConsumed = true;
254}
255
256function showError (message)
257{
258 errorEl.textContent = message ?? "";
259}
260
261function setAssetLoading (active, { loaded = 0, total = 0, phase = "" } = {})
262{
263 if (assetLoadEl)
264 { assetLoadEl.hidden = !active; }
265 if (characterList)
266 { characterList.hidden = active; }
267 if (createCharacterOpen)
268 { createCharacterOpen.hidden = active; }
269 if (!active)
270 { return; }
271 if (assetLoadBar && total > 0)
272 { assetLoadBar.value = Math.round((loaded / total) * 100); }
273 if (assetLoadLabel)
274 {
275 assetLoadLabel.textContent = phase
276 || (total > 0 ? `Loading assets… ${loaded}/${total}` : "Loading assets…");
277 }
278}
279
280function renderCharacters (characters)
281{
282 characterList.innerHTML = "";
283 for (const character of characters)
284 {
285 const row = document.createElement("div");
286 row.className = "character-row";
287 const pending = character.deletionScheduledAt
288 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
289 : "";
290 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
291 const play = document.createElement("button");
292 play.textContent = "Play";
293 play.disabled = !!character.deletionScheduledAt;
294 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
295 const del = document.createElement("button");
296 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
297 del.addEventListener("click", () =>
298 {
299 socket.send({
300 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
301 characterId: character.characterId
302 });
303 });
304 row.append(play, del);
305 characterList.append(row);
306 }
307}
308
309function uiBlocked ()
310{
311 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
312 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
313 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
314 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
315 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
316 || graphicsSettingsUi?.isBlocking?.()
317 || pointerOverSpellUi());
318}
319
320function pointerOverSpellUi ()
321{
322 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
323 if (!el)
324 { return false; }
325 return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
326}
327
328function applyGraphicsSettings (settings)
329{
330 view?.setGraphicsPrefs(settings);
331 if (socket && playing)
332 {
333 socket.send({
334 type: MessageType.setGraphicsSettings,
335 viewDistance: settings.viewDistance
336 });
337 }
338 syncAutorun();
339}
340
341function clearPendingPickup ()
342{
343 pendingPickup = null;
344}
345
346function clearPendingInteract ()
347{
348 pendingInteract = null;
349 approachMove = null;
350}
351
352function clearAllPendingActions ()
353{
354 clearPendingPickup();
355 clearPendingInteract();
356}
357
358function approachAdjacentTile (tileX, tileY)
359{
360 const local = view.entities.get(view.localEntityId);
361 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
362 {
363 approachMove = null;
364 return true;
365 }
366 if (!local)
367 { return false; }
368
369 const radius = Math.max(1, STATIC_CHUNK_RADIUS | 0) * CHUNK_SIZE;
370 const path = findPathToNearestGoal(
371 local.tileX,
372 local.tileY,
373 (x, y) => chebyshev(x, y, tileX, tileY) === 1 && isClientApproachable(x, y),
374 (x, y) => isClientApproachable(x, y),
375 local.tileX - radius,
376 local.tileY - radius,
377 local.tileX + radius,
378 local.tileY + radius
379 );
380 let best = path.length ? path[path.length - 1] : null;
381 if (!best)
382 {
383 // Fallback if BFS finds nothing (incomplete client map): nearest adjacent guess.
384 let bestAny = null;
385 let bestAnyDist = Infinity;
386 for (let dy = -1; dy <= 1; dy++)
387 {
388 for (let dx = -1; dx <= 1; dx++)
389 {
390 if (dx === 0 && dy === 0)
391 { continue; }
392 const destX = tileX + dx;
393 const destY = tileY + dy;
394 const dist = chebyshev(local.tileX, local.tileY, destX, destY);
395 if (dist < bestAnyDist)
396 {
397 bestAnyDist = dist;
398 bestAny = { tileX: destX, tileY: destY };
399 }
400 }
401 }
402 best = bestAny ? { x: bestAny.tileX, y: bestAny.tileY } : null;
403 }
404 if (!best)
405 { return false; }
406 const destX = best.x ?? best.tileX;
407 const destY = best.y ?? best.tileY;
408 if (
409 approachMove
410 && approachMove.focusX === tileX
411 && approachMove.focusY === tileY
412 && approachMove.destX === destX
413 && approachMove.destY === destY
414 )
415 { return false; }
416 approachMove = {
417 focusX: tileX,
418 focusY: tileY,
419 destX,
420 destY
421 };
422 sendPlayerMoveTo(destX, destY);
423 return false;
424}
425
426function requestOpenBank (tileX, tileY, { getCheques = false } = {})
427{
428 clearAllPendingActions();
429 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
430 const local = view?.entities.get(view.localEntityId);
431 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
432 { flushPendingInteract(); }
433 else
434 { approachAdjacentTile(tileX, tileY); }
435}
436
437function requestEnterDoorway (tileX, tileY)
438{
439 clearAllPendingActions();
440 pendingInteract = { kind: "doorway", tileX, tileY };
441 const local = view?.entities.get(view.localEntityId);
442 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
443 { flushPendingInteract(); }
444 else
445 { approachAdjacentTile(tileX, tileY); }
446}
447
448function requestOpenMarket (tileX, tileY)
449{
450 clearAllPendingActions();
451 pendingInteract = { kind: "market", tileX, tileY };
452 const local = view?.entities.get(view.localEntityId);
453 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
454 { flushPendingInteract(); }
455 else
456 { approachAdjacentTile(tileX, tileY); }
457}
458
459function requestOpenBounty (tileX, tileY)
460{
461 clearAllPendingActions();
462 pendingInteract = { kind: "bounty", tileX, tileY };
463 const local = view?.entities.get(view.localEntityId);
464 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
465 { flushPendingInteract(); }
466 else
467 { approachAdjacentTile(tileX, tileY); }
468}
469
470function requestOpenBarber (tileX, tileY)
471{
472 clearAllPendingActions();
473 pendingInteract = { kind: "barber", tileX, tileY };
474 const local = view?.entities.get(view.localEntityId);
475 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
476 { flushPendingInteract(); }
477 else
478 { approachAdjacentTile(tileX, tileY); }
479}
480
481function requestOpenCauldron (tileX, tileY)
482{
483 clearAllPendingActions();
484 pendingInteract = { kind: "cauldron", tileX, tileY };
485 const local = view?.entities.get(view.localEntityId);
486 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
487 { flushPendingInteract(); }
488 else
489 { approachAdjacentTile(tileX, tileY); }
490}
491
492function requestOpenFurnace (tileX, tileY)
493{
494 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
495}
496
497function requestOpenCraftStation (stationId, tileX, tileY)
498{
499 clearAllPendingActions();
500 pendingInteract = { kind: "station", stationId, tileX, tileY };
501 const local = view?.entities.get(view.localEntityId);
502 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
503 { flushPendingInteract(); }
504 else
505 { approachAdjacentTile(tileX, tileY); }
506}
507
508function requestStartFire (ground)
509{
510 if (!ground)
511 { return; }
512 clearAllPendingActions();
513 pendingInteract = {
514 kind: "start-fire",
515 groundItemId: ground.groundItemId,
516 tileX: ground.tileX,
517 tileY: ground.tileY
518 };
519 const local = view?.entities.get(view.localEntityId);
520 if (local && chebyshev(local.tileX, local.tileY, ground.tileX, ground.tileY) <= 1)
521 { flushPendingInteract(); }
522 else
523 { approachAdjacentTile(ground.tileX, ground.tileY); }
524}
525
526function requestFish (tileX, tileY)
527{
528 clearAllPendingActions();
529 pendingInteract = { kind: "fish", tileX, tileY };
530 const local = view?.entities.get(view.localEntityId);
531 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
532 { flushPendingInteract(); }
533 else
534 { approachAdjacentTile(tileX, tileY); }
535}
536
537function requestMine (tileX, tileY)
538{
539 clearAllPendingActions();
540 pendingInteract = { kind: "mine", tileX, tileY };
541 const local = view?.entities.get(view.localEntityId);
542 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
543 { flushPendingInteract(); }
544 else
545 { approachAdjacentTile(tileX, tileY); }
546}
547
548function requestChop (tileX, tileY)
549{
550 clearAllPendingActions();
551 pendingInteract = { kind: "chop", tileX, tileY };
552 const local = view?.entities.get(view.localEntityId);
553 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
554 { flushPendingInteract(); }
555 else
556 { approachAdjacentTile(tileX, tileY); }
557}
558
559function requestPick (tileX, tileY)
560{
561 clearAllPendingActions();
562 pendingInteract = { kind: "pick", tileX, tileY };
563 const local = view?.entities.get(view.localEntityId);
564 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
565 { flushPendingInteract(); }
566 else
567 { approachAdjacentTile(tileX, tileY); }
568}
569
570function requestTalk (targetEntityId, purpose = null)
571{
572 clearAllPendingActions();
573 pendingInteract = { kind: "talk", targetEntityId, purpose };
574 const target = view?.entities.get(targetEntityId);
575 if (!target)
576 {
577 clearPendingInteract();
578 return;
579 }
580 if (approachAdjacentTile(target.tileX, target.tileY))
581 { flushPendingInteract(); }
582}
583
584function setUiFocus (focus)
585{
586 uiFocus = focus;
587}
588
589function clearUiFocus ()
590{
591 uiFocus = null;
592}
593
594/** Close bank / station / NPC UIs when the player walks out of adjacency. */
595function closeOpenUiIfTooFar ()
596{
597 if (!uiFocus || !view)
598 { return; }
599 const local = view.entities.get(view.localEntityId);
600 if (!local)
601 { return; }
602
603 let tooFar = false;
604 if (uiFocus.entityId != null)
605 {
606 const target = view.entities.get(uiFocus.entityId);
607 tooFar = !target
608 || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1;
609 }
610 else if (uiFocus.tileX != null && uiFocus.tileY != null)
611 {
612 tooFar = chebyshev(local.tileX, local.tileY, uiFocus.tileX, uiFocus.tileY) > 1;
613 }
614 if (!tooFar)
615 { return; }
616
617 const kind = uiFocus.kind;
618 clearUiFocus();
619 switch (kind)
620 {
621 case "bank":
622 if (inventory?.isBankOpen?.())
623 { inventory.closeBank(); }
624 break;
625 case "station":
626 if (crafting?.isOpen?.())
627 { crafting.close(); }
628 break;
629 case "cauldron":
630 if (alchemy?.isOpen?.())
631 { alchemy.close(); }
632 break;
633 case "market":
634 if (market?.isOpen?.())
635 { market.close(); }
636 break;
637 case "bounty":
638 if (bounty?.isOpen?.())
639 { bounty.close(); }
640 break;
641 case "barber":
642 if (barber?.isOpen?.())
643 { barber.close(); }
644 break;
645 case "shop":
646 if (shop?.isOpen?.())
647 { shop.close(); }
648 break;
649 case "dialogue":
650 if (dialogueUi?.isOpen?.())
651 { dialogueUi.close(); }
652 break;
653 default:
654 break;
655 }
656}
657
658function flushPendingInteract ()
659{
660 if (!pendingInteract || !view)
661 { return; }
662 const local = view.entities.get(view.localEntityId);
663 if (!local)
664 { return; }
665
666 if (pendingInteract.kind === "bank")
667 {
668 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
669 { return; }
670 setUiFocus({
671 kind: "bank",
672 tileX: pendingInteract.tileX,
673 tileY: pendingInteract.tileY
674 });
675 const getCheques = !!pendingInteract.getCheques;
676 socket.send({ type: MessageType.openBank });
677 if (getCheques)
678 { inventory?.getBlankCheques(); }
679 clearPendingInteract();
680 return;
681 }
682
683 if (pendingInteract.kind === "doorway")
684 {
685 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
686 { return; }
687 socket.send({
688 type: MessageType.enterDoorway,
689 tileX: pendingInteract.tileX,
690 tileY: pendingInteract.tileY
691 });
692 clearPendingInteract();
693 return;
694 }
695
696 if (pendingInteract.kind === "market")
697 {
698 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
699 { return; }
700 setUiFocus({
701 kind: "market",
702 tileX: pendingInteract.tileX,
703 tileY: pendingInteract.tileY
704 });
705 socket.send({ type: MessageType.openMarket });
706 clearPendingInteract();
707 return;
708 }
709
710 if (pendingInteract.kind === "bounty")
711 {
712 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
713 { return; }
714 setUiFocus({
715 kind: "bounty",
716 tileX: pendingInteract.tileX,
717 tileY: pendingInteract.tileY
718 });
719 socket.send({ type: MessageType.openBounty });
720 clearPendingInteract();
721 return;
722 }
723
724 if (pendingInteract.kind === "barber")
725 {
726 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
727 { return; }
728 setUiFocus({
729 kind: "barber",
730 tileX: pendingInteract.tileX,
731 tileY: pendingInteract.tileY
732 });
733 socket.send({ type: MessageType.openBarber });
734 clearPendingInteract();
735 return;
736 }
737
738 if (pendingInteract.kind === "cauldron")
739 {
740 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
741 { return; }
742 setUiFocus({
743 kind: "cauldron",
744 tileX: pendingInteract.tileX,
745 tileY: pendingInteract.tileY
746 });
747 socket.send({ type: MessageType.openCauldron });
748 clearPendingInteract();
749 return;
750 }
751
752 if (pendingInteract.kind === "station")
753 {
754 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
755 { return; }
756 setUiFocus({
757 kind: "station",
758 tileX: pendingInteract.tileX,
759 tileY: pendingInteract.tileY
760 });
761 socket.send({
762 type: MessageType.openStation,
763 stationId: pendingInteract.stationId
764 });
765 clearPendingInteract();
766 return;
767 }
768
769 if (pendingInteract.kind === "mine")
770 {
771 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
772 { return; }
773 socket.send({
774 type: MessageType.mine,
775 tileX: pendingInteract.tileX,
776 tileY: pendingInteract.tileY
777 });
778 clearPendingInteract();
779 return;
780 }
781
782 if (pendingInteract.kind === "start-fire")
783 {
784 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
785 { return; }
786 socket.send({
787 type: MessageType.startFire,
788 groundItemId: pendingInteract.groundItemId
789 });
790 clearPendingInteract();
791 return;
792 }
793
794 if (pendingInteract.kind === "fish")
795 {
796 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
797 { return; }
798 socket.send({
799 type: MessageType.startFish,
800 tileX: pendingInteract.tileX,
801 tileY: pendingInteract.tileY
802 });
803 clearPendingInteract();
804 return;
805 }
806
807 if (pendingInteract.kind === "chop")
808 {
809 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
810 { return; }
811 socket.send({
812 type: MessageType.chop,
813 tileX: pendingInteract.tileX,
814 tileY: pendingInteract.tileY
815 });
816 clearPendingInteract();
817 return;
818 }
819
820 if (pendingInteract.kind === "pick")
821 {
822 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
823 { return; }
824 socket.send({
825 type: MessageType.pick,
826 tileX: pendingInteract.tileX,
827 tileY: pendingInteract.tileY
828 });
829 clearPendingInteract();
830 return;
831 }
832
833 if (pendingInteract.kind === "talk")
834 {
835 const target = view.entities.get(pendingInteract.targetEntityId);
836 if (!target)
837 {
838 clearPendingInteract();
839 return;
840 }
841 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
842 {
843 // Target may have moved — keep chasing.
844 approachAdjacentTile(target.tileX, target.tileY);
845 return;
846 }
847 socket.send({
848 type: MessageType.interact,
849 targetEntityId: pendingInteract.targetEntityId,
850 purpose: pendingInteract.purpose || undefined
851 });
852 // Shop vs dialogue is decided server-side; both use NPC adjacency.
853 setUiFocus({
854 kind: pendingInteract.purpose === "shop" ? "shop" : "dialogue",
855 entityId: pendingInteract.targetEntityId
856 });
857 clearPendingInteract();
858 }
859}
860
861function requestPickup (ground)
862{
863 if (!ground)
864 { return; }
865 clearPendingInteract();
866 pendingPickup = {
867 groundItemId: ground.groundItemId,
868 tileX: ground.tileX,
869 tileY: ground.tileY
870 };
871 const local = view.entities.get(view.localEntityId);
872 if (local && local.tileX === ground.tileX && local.tileY === ground.tileY)
873 {
874 flushPendingPickup();
875 return;
876 }
877 sendPlayerMoveTo(ground.tileX, ground.tileY);
878}
879
880function flushPendingPickup ()
881{
882 if (!pendingPickup || !view)
883 { return; }
884 const item = view.groundItems.get(pendingPickup.groundItemId);
885 if (!item)
886 {
887 clearPendingPickup();
888 return;
889 }
890 const local = view.entities.get(view.localEntityId);
891 if (!local)
892 { return; }
893 if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY)
894 { return; }
895 socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId });
896 clearPendingPickup();
897}
898
899function requestAttack (targetEntityId)
900{
901 clearAllPendingActions();
902 setAutorunFocusEntity(targetEntityId);
903 socket.send({ type: MessageType.attack, targetEntityId });
904}
905
906function isAttackableEntity (entity)
907{
908 if (!entity || entity.untargetable)
909 { return false; }
910 if (entity.canFight)
911 { return true; }
912 // Snapshots can omit canFight; mobs are still attackable via LMB.
913 return !!entity.mobTypeId && !entity.talkable;
914}
915
916function canTalkToEntity (entity)
917{
918 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
919}
920
921function isApproachingCombatOrCast ()
922{
923 return autorunFocusEntityId != null || autorunFocusTile != null;
924}
925
926function handleLeftClick (mouseX, mouseY)
927{
928 const tile = view.screenToTile(mouseX, mouseY);
929 const armed = spells?.getArmedSpell?.();
930 const approaching = isApproachingCombatOrCast();
931
932 // Entity-armed: cast only when a valid target is under the cursor. Empty ground
933 // must fall through so walk cancels cast/attack approach (server moveTo clears it).
934 if (armed?.target === "entity" && armed.canCast)
935 {
936 const snap = nearestSpellEntityAtCursor(mouseX, mouseY);
937 if (snap && spells.tryCastAtEntity(snap.entityId))
938 {
939 setAutorunFocusEntity(snap.entityId);
940 return;
941 }
942 }
943 // Tile-armed while approaching: prefer walk-cancel over re-targeting the cast.
944 else if (
945 !approaching
946 && armed?.target === "tile"
947 && armed.canCast
948 && spells.tryCastAtTile(tile.tileX, tile.tileY)
949 )
950 {
951 setAutorunFocusTile(tile.tileX, tile.tileY);
952 return;
953 }
954
955 const entity = view.entityAtScreen(mouseX, mouseY);
956 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
957 {
958 clearPendingPickup();
959 if (entity.characterId)
960 {
961 clearPendingInteract();
962 social.inspect(entity);
963 return;
964 }
965 // Dialogue (or shop/talkable) wins over attack as the default click.
966 if (canTalkToEntity(entity))
967 {
968 // Same intent as context-menu Talk / Shop so dialogue pin matches.
969 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
970 ? "talk"
971 : (entity.hasShop ? "shop" : "talk");
972 requestTalk(entity.entityId, purpose);
973 return;
974 }
975 if (isAttackableEntity(entity))
976 {
977 requestAttack(entity.entityId);
978 return;
979 }
980 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
981 return;
982 }
983
984 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
985 if (ground)
986 { requestPickup(ground); }
987 else if (isBankTile(view, tile.tileX, tile.tileY))
988 { requestOpenBank(tile.tileX, tile.tileY); }
989 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
990 { requestEnterDoorway(tile.tileX, tile.tileY); }
991 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
992 { requestOpenMarket(tile.tileX, tile.tileY); }
993 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
994 { requestOpenBounty(tile.tileX, tile.tileY); }
995 else if (isBarberTile(view, tile.tileX, tile.tileY))
996 { requestOpenBarber(tile.tileX, tile.tileY); }
997 else if (isCauldronTile(view, tile.tileX, tile.tileY))
998 { requestOpenCauldron(tile.tileX, tile.tileY); }
999 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
1000 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
1001 else if (isOvenTile(view, tile.tileX, tile.tileY))
1002 { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); }
1003 else if (isCampfireTile(view, tile.tileX, tile.tileY))
1004 { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); }
1005 else if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1006 { requestFish(tile.tileX, tile.tileY); }
1007 else if (isAnvilTile(view, tile.tileX, tile.tileY))
1008 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
1009 else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1010 { requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }
1011 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1012 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
1013 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1014 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
1015 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1016 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
1017 else if (isLoomTile(view, tile.tileX, tile.tileY))
1018 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
1019 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1020 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
1021 else if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1022 { requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY); }
1023 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1024 { requestMine(tile.tileX, tile.tileY); }
1025 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1026 { requestChop(tile.tileX, tile.tileY); }
1027 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1028 { requestPick(tile.tileX, tile.tileY); }
1029 else
1030 {
1031 clearAllPendingActions();
1032 sendPlayerMoveTo(tile.tileX, tile.tileY);
1033 }
1034}
1035
1036function handleRightClick (event, mouseX, mouseY)
1037{
1038 event.preventDefault();
1039 if (spells?.isTargeting?.())
1040 {
1041 spells.cancelTargeting();
1042 view?.clearSpellTargetHighlight();
1043 return;
1044 }
1045 const tile = view.screenToTile(mouseX, mouseY);
1046 const items = [];
1047 const walkTileX = tile.tileX;
1048 const walkTileY = tile.tileY;
1049
1050 items.push({
1051 label: "Walk here",
1052 onSelect: () =>
1053 {
1054 clearAllPendingActions();
1055 sendPlayerMoveTo(walkTileX, walkTileY);
1056 }
1057 });
1058
1059 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY))
1060 {
1061 if (entity.entityId === view.localEntityId)
1062 { continue; }
1063 const targetName = entityLabel(entity);
1064 items.push({
1065 label: `Follow ${targetName}`,
1066 onSelect: () =>
1067 {
1068 clearAllPendingActions();
1069 sendPlayerFollow(entity.entityId);
1070 }
1071 });
1072 if (entity.untargetable)
1073 { continue; }
1074 if (entity.hasShop)
1075 {
1076 items.push({
1077 label: `Shop ${targetName}`,
1078 onSelect: () => requestTalk(entity.entityId, "shop")
1079 });
1080 }
1081 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
1082 {
1083 items.push({
1084 label: `Talk to ${targetName}`,
1085 onSelect: () => requestTalk(entity.entityId, "talk")
1086 });
1087 }
1088 if (entity.characterId)
1089 {
1090 items.push({
1091 label: `${targetName} info`,
1092 onSelect: () =>
1093 {
1094 clearAllPendingActions();
1095 social.inspect(entity);
1096 }
1097 });
1098 }
1099 items.push({
1100 label: `Attack ${targetName}`,
1101 onSelect: () => requestAttack(entity.entityId)
1102 });
1103 }
1104
1105 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1106 {
1107 const name = groundLabel(ground);
1108 items.push({
1109 label: `Pick up ${name}`,
1110 onSelect: () => requestPickup(ground)
1111 });
1112 if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
1113 {
1114 items.push({
1115 label: `Start Fire`,
1116 onSelect: () => requestStartFire(ground)
1117 });
1118 }
1119 }
1120
1121 if (isBankTile(view, tile.tileX, tile.tileY))
1122 {
1123 items.push({
1124 label: "Bank",
1125 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
1126 });
1127 items.push({
1128 label: "Get Blank Cheques",
1129 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
1130 });
1131 }
1132
1133 if (isDoorwayTile(view, tile.tileX, tile.tileY))
1134 {
1135 items.push({
1136 label: "Enter",
1137 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
1138 });
1139 }
1140
1141 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1142 {
1143 items.push({
1144 label: "Central Exchange",
1145 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
1146 });
1147 }
1148
1149 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1150 {
1151 items.push({
1152 label: "Bounty Office",
1153 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
1154 });
1155 }
1156
1157 if (isBarberTile(view, tile.tileX, tile.tileY))
1158 {
1159 items.push({
1160 label: "Barber",
1161 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
1162 });
1163 }
1164
1165 if (isCauldronTile(view, tile.tileX, tile.tileY))
1166 {
1167 items.push({
1168 label: "Alchemy",
1169 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
1170 });
1171 }
1172
1173 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1174 {
1175 items.push({
1176 label: "Smelt",
1177 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
1178 });
1179 }
1180
1181 if (isOvenTile(view, tile.tileX, tile.tileY))
1182 {
1183 items.push({
1184 label: "Cook",
1185 onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
1186 });
1187 }
1188
1189 if (isCampfireTile(view, tile.tileX, tile.tileY))
1190 {
1191 items.push({
1192 label: "Cook",
1193 onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
1194 });
1195 }
1196
1197 if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1198 {
1199 items.push({
1200 label: "Fish",
1201 onSelect: () => requestFish(tile.tileX, tile.tileY)
1202 });
1203 }
1204
1205 if (isAnvilTile(view, tile.tileX, tile.tileY))
1206 {
1207 items.push({
1208 label: "Smith",
1209 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
1210 });
1211 }
1212
1213 if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1214 {
1215 items.push({
1216 label: "Jewel",
1217 onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1218 });
1219 }
1220
1221 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1222 {
1223 items.push({
1224 label: "Woodwork",
1225 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
1226 });
1227 }
1228
1229 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1230 {
1231 items.push({
1232 label: "Craft",
1233 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
1234 });
1235 }
1236
1237 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1238 {
1239 items.push({
1240 label: "Spin",
1241 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
1242 });
1243 }
1244
1245 if (isLoomTile(view, tile.tileX, tile.tileY))
1246 {
1247 items.push({
1248 label: "Weave",
1249 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
1250 });
1251 }
1252
1253 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1254 {
1255 items.push({
1256 label: "Tailor",
1257 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
1258 });
1259 }
1260
1261 if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1262 {
1263 items.push({
1264 label: "Leatherwork",
1265 onSelect: () => requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY)
1266 });
1267 }
1268
1269 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1270 {
1271 items.push({
1272 label: "Mine",
1273 onSelect: () => requestMine(tile.tileX, tile.tileY)
1274 });
1275 }
1276
1277 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1278 {
1279 items.push({
1280 label: "Chop",
1281 onSelect: () => requestChop(tile.tileX, tile.tileY)
1282 });
1283 }
1284
1285 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1286 {
1287 items.push({
1288 label: "Pick",
1289 onSelect: () => requestPick(tile.tileX, tile.tileY)
1290 });
1291 }
1292
1293 contextMenu.show(event.clientX, event.clientY, items);
1294}
1295
1296function entityLabel (entity)
1297{
1298 const first = (entity?.firstName ?? "").trim();
1299 const last = (entity?.lastName ?? "").trim();
1300 const name = first && last ? `${first} ${last}` : (first || "target");
1301 const level = entity?.level | 0;
1302 if (entity?.mobTypeId && level > 0)
1303 { return `Lv.${level} ${name}`; }
1304 return name;
1305}
1306
1307function groundLabel (ground)
1308{
1309 const name = (ground?.displayName ?? "").trim() || "item";
1310 const qty = ground?.quantity ?? 1;
1311 if (qty <= 1)
1312 { return name; }
1313 return `${name} (${formatQuantity(qty)})`;
1314}
1315
1316function startPlay (payload)
1317{
1318 playing = true;
1319 overlay.hidden = true;
1320 hud.hidden = false;
1321 const settingsToggle = document.getElementById("settings-toggle");
1322 if (settingsToggle)
1323 { settingsToggle.hidden = false; }
1324 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
1325 gait = payload.gait ?? GAIT.walk;
1326 document.getElementById("gait").textContent = gait;
1327 staminaUi?.show();
1328 healthUi?.show();
1329 statusEffectsUi?.show();
1330 if (payload.stamina != null)
1331 { staminaUi?.apply(payload.stamina); }
1332 if (payload.health != null || payload.maxHealth != null)
1333 {
1334 healthUi?.apply({
1335 current: payload.health ?? healthUi.getCurrent?.(),
1336 max: payload.maxHealth ?? healthUi.getMax?.()
1337 });
1338 }
1339 if (!scene)
1340 {
1341 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1342 game.loadScene(scene);
1343 useNearestNeighbour(scene, game.images);
1344 }
1345 if (!view)
1346 {
1347 view = new WorldView(game, scene, catalog);
1348 graphicsSettingsUi?.apply();
1349 const ticker = new GameObject(0, 0, null, 10);
1350 ticker.update = (dt) =>
1351 {
1352 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
1353 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
1354 if (!leftPressed && !leftHeld)
1355 { leftClickConsumed = false; }
1356 else if (!leftClickConsumed && playing && !uiBlocked())
1357 {
1358 leftClickConsumed = true;
1359 const canvas = scene.canvas;
1360 const rect = canvas.getBoundingClientRect();
1361 const mouseX = GameInput.mousePosition.x - rect.left;
1362 const mouseY = GameInput.mousePosition.y - rect.top;
1363 handleLeftClick(mouseX, mouseY);
1364 }
1365 if (GameInput.isPressed(82) && !uiBlocked())
1366 {
1367 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
1368 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
1369 { return; }
1370 socket.send({ type: MessageType.setGait, gait: next });
1371 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
1372 if (next === GAIT.walk)
1373 {
1374 gait = next;
1375 document.getElementById("gait").textContent = gait;
1376 }
1377 }
1378 if (playing && !death?.isBlocking())
1379 {
1380 flushPendingPickup();
1381 flushPendingInteract();
1382 syncAutorun();
1383 social?.updateNametag(view, scene, view.localEntityId);
1384 chat?.update(view, scene);
1385 updateSpellTargetHighlight();
1386 updateWorldTooltip();
1387 }
1388 else
1389 {
1390 hideWorldTooltip();
1391 view?.clearSpellTargetHighlight();
1392 }
1393 view.update(dt);
1394 };
1395 scene.addObject(ticker);
1396 window.addEventListener("resize", () =>
1397 {
1398 scene.size.x = window.innerWidth;
1399 scene.size.y = window.innerHeight;
1400 scene.g_fixSize();
1401 useNearestNeighbour(scene, game.images);
1402 });
1403 window.addEventListener("wheel", (event) =>
1404 {
1405 if (!playing || uiBlocked())
1406 { return; }
1407 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
1408 if (playZoomRaf)
1409 { return; }
1410 playZoomRaf = requestAnimationFrame(() =>
1411 {
1412 playZoomRaf = 0;
1413 if (!view || !playZoomDelta)
1414 { return; }
1415 view.setZoom(view.zoom + playZoomDelta);
1416 playZoomDelta = 0;
1417 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
1418 });
1419 }, { passive: true });
1420 scene.canvas.addEventListener("contextmenu", (event) =>
1421 {
1422 if (!playing || uiBlocked())
1423 { return; }
1424 const rect = scene.canvas.getBoundingClientRect();
1425 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
1426 });
1427 }
1428 view.setSettings(payload.settings ?? view.settings);
1429 chat?.syncSettings();
1430 view.worldHour = payload.worldTime?.hour ?? 12;
1431 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
1432 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
1433 view.setWorldSeason(payload.worldTime?.season);
1434 view.setLocalEntity(
1435 payload.entityId,
1436 payload.tileX,
1437 payload.tileY,
1438 payload.gait,
1439 payload.sex,
1440 payload.firstName,
1441 payload.lastName,
1442 payload.characterId,
1443 payload.layers,
1444 payload.health,
1445 payload.maxHealth,
1446 payload.skullValue
1447 );
1448 social?.setLocalIdentity?.({
1449 accountId: payload.accountId,
1450 characterId: payload.characterId
1451 });
1452 graphicsSettingsUi?.apply();
1453}
1454
1455async function main ()
1456{
1457 const authStatus = await fetchAuthStatus();
1458 updateAuthUi(authStatus);
1459 if (!authStatus.authenticated)
1460 {
1461 statusEl.textContent = "Sign in to play Questward.";
1462 showError("");
1463 return;
1464 }
1465
1466 setAssetLoading(true, { phase: "Loading catalog…" });
1467 catalog = await loadSpriteCatalog();
1468 const assetTotal = playImagesFromCatalog(catalog).length;
1469 setAssetLoading(true, { loaded: 0, total: assetTotal, phase: "Loading assets…" });
1470 await preloadCatalogImages(game, catalog, {
1471 onProgress ({ loaded, total })
1472 {
1473 setAssetLoading(true, { loaded, total });
1474 }
1475 });
1476 applySpriteSheets(game.images, catalog);
1477 if (!scene)
1478 {
1479 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1480 game.loadScene(scene);
1481 }
1482 setAssetLoading(false);
1483 statusEl.textContent = "Connecting…";
1484 createHairControls = bindHairControls({
1485 root: document.getElementById("create-hair"),
1486 resolveSpriteUrl (name)
1487 {
1488 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1489 },
1490 getSex: () => document.getElementById("sex")?.value ?? "male",
1491 getBag: () => null,
1492 hideHeadgear: true,
1493 onChange ()
1494 {
1495 if (createActiveTab === "clothing")
1496 { void refreshCreateClothingPreview(); }
1497 }
1498 });
1499 createClothingControls = bindCreateClothingControls({
1500 root: document.getElementById("create-clothing"),
1501 onChange ()
1502 {
1503 if (createActiveTab === "clothing")
1504 { void refreshCreateClothingPreview(); }
1505 }
1506 });
1507 initCreateTabs();
1508 document.getElementById("sex")?.addEventListener("change", () =>
1509 {
1510 createHairControls?.fillStyles();
1511 void createHairControls?.refreshPreview();
1512 if (createActiveTab === "clothing")
1513 { void refreshCreateClothingPreview(); }
1514 });
1515 void createHairControls?.refreshPreview();
1516 void refreshCreateClothingPreview();
1517 graphicsSettingsUi = initGraphicsSettings({
1518 onChange: applyGraphicsSettings,
1519 onSuppressWorldClick: consumeWorldClick
1520 });
1521 social = initSocial({
1522 socket: { send (payload) { socket.send(payload); } },
1523 MessageType,
1524 resolveSpriteUrl (name)
1525 {
1526 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1527 }
1528 });
1529 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1530 const tipArrows = initTipArrows({
1531 socket: { send (payload) { socket.send(payload); } },
1532 MessageType,
1533 getInventoryBag ()
1534 {
1535 return inventory?.getBag?.() ?? null;
1536 }
1537 });
1538 inventory = initInventory({
1539 socket: { send (payload) { socket.send(payload); } },
1540 MessageType,
1541 contextMenu,
1542 tipArrows,
1543 resolveSpriteUrl (name)
1544 {
1545 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1546 },
1547 getFriends ()
1548 {
1549 return social?.getFriends?.() ?? [];
1550 },
1551 getLocalName ()
1552 {
1553 const you = document.getElementById("you")?.textContent ?? "";
1554 return you.split("(")[0].trim() || "Unknown";
1555 }
1556 });
1557 skills = initSkills({
1558 getEquipmentSlots ()
1559 {
1560 return inventory?.getEquipment?.() ?? {};
1561 },
1562 getSettings ()
1563 {
1564 return view?.settings ?? null;
1565 }
1566 });
1567 spells = initSpells({
1568 socket: { send (payload) { socket.send(payload); } },
1569 MessageType,
1570 getSkillLevel (skillId)
1571 {
1572 return skills?.skillLevel?.(skillId) ?? 1;
1573 }
1574 });
1575 crafting = initCrafting({
1576 socket: { send (payload) { socket.send(payload); } },
1577 MessageType,
1578 getInventorySlots ()
1579 {
1580 return inventory?.getInventorySlots?.() ?? [];
1581 },
1582 getSkillLevel (skillId)
1583 {
1584 return skills?.skillLevel?.(skillId) ?? 1;
1585 }
1586 });
1587 alchemy = initAlchemy({
1588 socket: { send (payload) { socket.send(payload); } },
1589 MessageType,
1590 getInventorySlots ()
1591 {
1592 return inventory?.getInventorySlots?.() ?? [];
1593 }
1594 });
1595 staminaUi = initStamina();
1596 healthUi = initHealth();
1597 statusEffectsUi = initStatusEffects();
1598 toasts = initToasts();
1599 questsUi = initQuests({
1600 socket: { send (payload) { socket.send(payload); } },
1601 MessageType,
1602 toasts
1603 });
1604 dialogueUi = initDialogue({
1605 socket: { send (payload) { socket.send(payload); } },
1606 MessageType,
1607 getEntity (id)
1608 {
1609 if (id === "local")
1610 { return view?.entities.get(view.localEntityId) ?? null; }
1611 return view?.entities.get(id) ?? null;
1612 },
1613 captureSpeakerIcon (entityId, size = 64)
1614 {
1615 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1616 }
1617 });
1618 shop = initShop({
1619 socket: { send (payload) { socket.send(payload); } },
1620 MessageType,
1621 onSuppressWorldClick: consumeWorldClick,
1622 getCoinCount ()
1623 {
1624 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1625 },
1626 getInventorySlots ()
1627 {
1628 return inventory?.getInventorySlots?.() ?? [];
1629 }
1630 });
1631 market = initMarket({
1632 socket: { send (payload) { socket.send(payload); } },
1633 MessageType,
1634 onSuppressWorldClick: consumeWorldClick,
1635 getCoinCount ()
1636 {
1637 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1638 },
1639 getInventorySlots ()
1640 {
1641 return inventory?.getInventorySlots?.() ?? [];
1642 },
1643 getLocalCharacterId ()
1644 {
1645 return inventory?.getLocalCharacterId?.() ?? null;
1646 }
1647 });
1648 bounty = initBounty({
1649 socket: { send (payload) { socket.send(payload); } },
1650 MessageType,
1651 onSuppressWorldClick: consumeWorldClick,
1652 resolveSpriteUrl (name)
1653 {
1654 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1655 }
1656 });
1657 barber = initBarber({
1658 socket: { send (payload) { socket.send(payload); } },
1659 MessageType,
1660 onSuppressWorldClick: consumeWorldClick,
1661 resolveSpriteUrl (name)
1662 {
1663 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1664 },
1665 getInventoryBag ()
1666 {
1667 return {
1668 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1669 inventory: inventory?.getInventorySlots?.() ?? []
1670 };
1671 }
1672 });
1673 chat = initChat({
1674 socket: { send (payload) { socket.send(payload); } },
1675 MessageType,
1676 getSettings: () => view?.settings
1677 });
1678 death = initDeath({
1679 socket: { send (payload) { socket.send(payload); } },
1680 MessageType
1681 });
1682 game.startGame();
1683 useNearestNeighbour(scene, game.images);
1684
1685 socket = new GameSocket(defaultSocketUrl(), (message) =>
1686 {
1687 switch (message.type)
1688 {
1689 case MessageType.session:
1690 session = message;
1691 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1692 renderCharacters(message.characters);
1693 break;
1694 case MessageType.characterList:
1695 renderCharacters(message.characters);
1696 if (!playing)
1697 { overlay.hidden = false; }
1698 break;
1699 case MessageType.enterWorld:
1700 closeCreateModal();
1701 startPlay(message);
1702 inventory?.setLocalCharacterId(message.characterId);
1703 toasts?.applyRestartStatus?.(message.restartStatus);
1704 socket.send({ type: MessageType.requestQuests });
1705 break;
1706 case MessageType.chunkSnapshot:
1707 view?.applySnapshot(message);
1708 break;
1709 case MessageType.dimensionChanged:
1710 if (view)
1711 {
1712 view.setDimensionId(message.dimensionId);
1713 view.setDimensionModes(message.lightingMode, message.seasonMode);
1714 view.clearAllChunks();
1715 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1716 {
1717 view.moveEntity({
1718 entityId: view.localEntityId,
1719 tileX: message.tileX,
1720 tileY: message.tileY
1721 });
1722 }
1723 }
1724 closeOpenUiIfTooFar();
1725 break;
1726 case MessageType.chunkDelta:
1727 for (const tile of message.tiles ?? [])
1728 {
1729 view?.updateAuthoredTile(
1730 message.chunkX,
1731 message.chunkY,
1732 tile.localX,
1733 tile.localY,
1734 { ground: tile.ground, block: tile.block, light: tile.light }
1735 );
1736 }
1737 break;
1738 case MessageType.unsubscribeChunk:
1739 view?.removeChunk(message.chunkX, message.chunkY);
1740 break;
1741 case MessageType.entitySpawn:
1742 view?.spawnEntity(message);
1743 break;
1744 case MessageType.entityMove:
1745 view?.moveEntity(message);
1746 if (message.entityId === view?.localEntityId)
1747 {
1748 if (message.gait)
1749 {
1750 gait = message.gait;
1751 document.getElementById("gait").textContent = gait;
1752 }
1753 closeOpenUiIfTooFar();
1754 }
1755 else if (
1756 uiFocus?.entityId != null
1757 && message.entityId === uiFocus.entityId
1758 )
1759 { closeOpenUiIfTooFar(); }
1760 break;
1761 case MessageType.entityDespawn:
1762 if (message.entityId === autorunFocusEntityId)
1763 { clearAutorunFocus(); }
1764 view?.despawnEntity(message.entityId);
1765 break;
1766 case MessageType.entityAppearance:
1767 view?.setAppearance(message);
1768 break;
1769 case MessageType.entitySkull:
1770 view?.updateEntitySkull(message.entityId, message.skullValue);
1771 break;
1772 case MessageType.groundItemAppear:
1773 view?.upsertGroundItem(message);
1774 break;
1775 case MessageType.groundItemDespawn:
1776 view?.despawnGroundItem(message.groundItemId);
1777 break;
1778 case MessageType.inventory:
1779 inventory?.handleInventory(message);
1780 skills?.refresh?.();
1781 crafting?.refresh();
1782 alchemy?.refresh();
1783 shop?.refresh();
1784 market?.refresh();
1785 break;
1786 case MessageType.skills:
1787 skills?.render(message.skills);
1788 crafting?.refresh();
1789 spells?.refreshCastGates?.();
1790 break;
1791 case MessageType.spells:
1792 case MessageType.spellsUpdated:
1793 spells?.render(message);
1794 break;
1795 case MessageType.spellArmed:
1796 spells?.handleSpellArmed(message);
1797 break;
1798 case MessageType.spellDisarmed:
1799 spells?.handleSpellDisarmed();
1800 break;
1801 case MessageType.spellProjectile:
1802 view?.spawnSpellProjectileFx(message);
1803 if (message.casterId === view?.localEntityId)
1804 { clearAutorunFocus(); }
1805 break;
1806 case MessageType.spellFizzle:
1807 view?.spawnSpellFizzleFx(message);
1808 if (message.casterId === view?.localEntityId)
1809 {
1810 clearAutorunFocus();
1811 toasts?.show("Failed to cast spell");
1812 }
1813 break;
1814 case MessageType.spellCastFlash:
1815 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
1816 if (message.casterId === view?.localEntityId)
1817 { clearAutorunFocus(); }
1818 break;
1819 case MessageType.spellLightAppear:
1820 case MessageType.spellLightUpdate:
1821 view?.setSpellLight(message);
1822 break;
1823 case MessageType.spellLightRemove:
1824 view?.removeSpellLight(message);
1825 break;
1826 case MessageType.spellDarkAppear:
1827 case MessageType.spellDarkUpdate:
1828 view?.setSpellDark(message);
1829 break;
1830 case MessageType.spellDarkRemove:
1831 view?.removeSpellDark(message);
1832 break;
1833 case MessageType.stamina:
1834 staminaUi?.apply(message);
1835 if (message.gait)
1836 {
1837 gait = message.gait;
1838 document.getElementById("gait").textContent = gait;
1839 if (gait === GAIT.walk && (staminaUi?.getCurrent?.() ?? 0) <= 0)
1840 { autorunWaitingStamina = true; }
1841 }
1842 syncAutorun();
1843 break;
1844 case MessageType.statusEffects:
1845 view?.setLocalBlind(!!message.blind);
1846 statusEffectsUi?.apply(message);
1847 break;
1848 case MessageType.bankSnapshot:
1849 inventory?.handleBank(message);
1850 break;
1851 case MessageType.cauldronSnapshot:
1852 if (message.open === false && uiFocus?.kind === "cauldron")
1853 { clearUiFocus(); }
1854 alchemy?.handleSnapshot(message);
1855 break;
1856 case MessageType.pigeonDispatched:
1857 inventory?.handlePigeonDispatched(message);
1858 break;
1859 case MessageType.pigeonDelivered:
1860 inventory?.handlePigeonDelivered(message);
1861 break;
1862 case MessageType.characterSearchResult:
1863 inventory?.handleCharacterSearch(message);
1864 break;
1865 case MessageType.craftResult:
1866 crafting?.handleCraftResult(message);
1867 break;
1868 case MessageType.worldStatus:
1869 if (view)
1870 {
1871 view.setSettings(message.settings ?? view.settings);
1872 view.worldHour = message.worldTime?.hour ?? view.worldHour;
1873 view.setWorldSeason(message.worldTime?.season);
1874 chat?.syncSettings();
1875 }
1876 skills?.refresh?.();
1877 toasts?.applyRestartStatus?.(message.restartStatus);
1878 break;
1879 case MessageType.restartStatus:
1880 toasts?.applyRestartStatus?.(message.restartStatus);
1881 break;
1882 case MessageType.chatBubble:
1883 chat?.showBubble(message);
1884 break;
1885 case MessageType.friends:
1886 social?.handleFriends(message);
1887 break;
1888 case MessageType.combatSwing:
1889 view?.spawnCombatSwing(message);
1890 break;
1891 case MessageType.combatProjectile:
1892 view?.spawnPhysicalProjectileFx({
1893 ...message,
1894 sprite: "fx:projectile:arrow"
1895 });
1896 break;
1897 case MessageType.combatNoArrows:
1898 toasts?.show("Out of arrows!");
1899 break;
1900 case MessageType.gatherSwing:
1901 case MessageType.tileShove:
1902 view?.spawnGatherSwing(message);
1903 break;
1904 case MessageType.stationOpen:
1905 if (message.stationId)
1906 { crafting?.openStation(message.stationId); }
1907 break;
1908 case MessageType.shopOpen:
1909 if (message.npcEntityId != null)
1910 { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); }
1911 shop?.handleShopOpen(message);
1912 break;
1913 case MessageType.shopClosed:
1914 if (uiFocus?.kind === "shop")
1915 { clearUiFocus(); }
1916 shop?.handleShopClosed(message);
1917 break;
1918 case MessageType.marketOpen:
1919 market?.handleOpen(message);
1920 break;
1921 case MessageType.marketClosed:
1922 if (uiFocus?.kind === "market")
1923 { clearUiFocus(); }
1924 market?.handleClosed(message);
1925 break;
1926 case MessageType.marketTrade:
1927 market?.handleTrade(message);
1928 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
1929 break;
1930 case MessageType.bountySnapshot:
1931 bounty?.handleSnapshot(message);
1932 break;
1933 case MessageType.closeBounty:
1934 if (uiFocus?.kind === "bounty")
1935 { clearUiFocus(); }
1936 bounty?.handleClosed(message);
1937 break;
1938 case MessageType.characterBounty:
1939 bounty?.handleCharacterBounty(message);
1940 social?.handleCharacterBounty(message);
1941 break;
1942 case MessageType.barberSnapshot:
1943 barber?.handleSnapshot(message);
1944 break;
1945 case MessageType.closeBarber:
1946 if (uiFocus?.kind === "barber")
1947 { clearUiFocus(); }
1948 barber?.handleClosed(message);
1949 break;
1950 case MessageType.itemBubble:
1951 chat?.showItemBubble(message);
1952 break;
1953 case MessageType.gatherComplete:
1954 crafting?.refresh();
1955 break;
1956 case MessageType.combatHit:
1957 {
1958 const applyHit = () =>
1959 {
1960 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1961 view?.flashDamage(message.targetId);
1962 view?.spawnCombatKnockback?.(message);
1963 view?.spawnDamageNumber(message.targetId, message.damage);
1964 if (message.targetId === view?.localEntityId)
1965 {
1966 healthUi?.apply({
1967 current: message.health,
1968 max: message.maxHealth
1969 });
1970 }
1971 };
1972 if (!view?.deferCombatHit?.(message, applyHit))
1973 { applyHit(); }
1974 break;
1975 }
1976 case MessageType.combatMiss:
1977 view?.spawnCombatDodge?.(message);
1978 view?.markProjectileMiss?.(message);
1979 break;
1980 case MessageType.combatBlock:
1981 {
1982 const applyBlock = () =>
1983 {
1984 view?.flashBlock?.(message.targetId);
1985 if (message.health != null)
1986 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
1987 };
1988 if (!view?.deferCombatHit?.(message, applyBlock))
1989 { applyBlock(); }
1990 break;
1991 }
1992 case MessageType.entityHealth:
1993 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1994 if (message.entityId === view?.localEntityId)
1995 {
1996 healthUi?.apply({
1997 current: message.health,
1998 max: message.maxHealth
1999 });
2000 }
2001 break;
2002 case MessageType.skillLevelUp:
2003 view?.spawnSkillLevelUp(message.entityId, message);
2004 if (message.entityId === view?.localEntityId)
2005 {
2006 const level = message.level | 0;
2007 const previousLevel = message.previousLevel == null
2008 ? Math.max(0, level - 1)
2009 : message.previousLevel | 0;
2010 const unlockCount = skillUnlockMessages(message.skillId, previousLevel, level).length;
2011 toasts?.show(skillLevelUpToastText(message.skillId, level, previousLevel), {
2012 durationMs: 3500 + unlockCount * 1600
2013 });
2014 }
2015 break;
2016 case MessageType.playerDied:
2017 clearAllPendingActions();
2018 clearAutorunFocus();
2019 contextMenu?.hide();
2020 spells?.handleSpellDisarmed?.();
2021 death?.show();
2022 if (message.entityId === view?.localEntityId)
2023 {
2024 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
2025 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
2026 }
2027 break;
2028 case MessageType.playerRespawned:
2029 death?.hide();
2030 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2031 if (message.entityId === view?.localEntityId)
2032 {
2033 healthUi?.apply({
2034 current: message.health,
2035 max: message.maxHealth
2036 });
2037 }
2038 if (message.stamina != null || message.maxStamina != null)
2039 {
2040 staminaUi?.apply({
2041 current: message.stamina ?? staminaUi.getCurrent?.(),
2042 max: message.maxStamina ?? staminaUi.getMax?.()
2043 });
2044 }
2045 break;
2046 case MessageType.error:
2047 if (playing)
2048 { toasts?.show(message.message); }
2049 else
2050 {
2051 const createPanel = document.getElementById("create-panel");
2052 const createError = document.getElementById("create-error");
2053 if (createPanel && !createPanel.hidden && createError)
2054 { createError.textContent = message.message ?? ""; }
2055 else
2056 { showError(message.message); }
2057 }
2058 social?.showError(message.message);
2059 break;
2060 case MessageType.toast:
2061 if (playing)
2062 { toasts?.show(message.message); }
2063 break;
2064 case MessageType.questsSnapshot:
2065 questsUi?.applySnapshot(message);
2066 break;
2067 case MessageType.questStepComplete:
2068 questsUi?.handleStepComplete(message);
2069 break;
2070 case MessageType.dialogueStep:
2071 if (message.npcEntityId != null)
2072 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2073 dialogueUi?.handleStep(message);
2074 break;
2075 case MessageType.dialogueChoices:
2076 if (message.npcEntityId != null)
2077 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2078 dialogueUi?.handleChoices(message);
2079 break;
2080 case MessageType.dialogueClose:
2081 if (uiFocus?.kind === "dialogue")
2082 { clearUiFocus(); }
2083 dialogueUi?.handleClose(message);
2084 break;
2085 case MessageType.forceLogout:
2086 returnToMenu(message.reason);
2087 break;
2088 }
2089 }, {
2090 onClose (event)
2091 {
2092 if (playing)
2093 { returnToMenu(event.reason || "Disconnected from server."); }
2094 }
2095 });
2096 await socket.connect();
2097 if (typeof window !== "undefined")
2098 {
2099 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
2100 {
2101 crafting?.openStation(stationId);
2102 };
2103 }
2104}
2105
2106function returnToMenu (reason = "")
2107{
2108 playing = false;
2109 followTargetId = null;
2110 moveDest = null;
2111 clearAutorunFocus();
2112 autorunWaitingStamina = false;
2113 clearAllPendingActions();
2114 clearUiFocus();
2115 social?.reset();
2116 chat?.reset();
2117 inventory?.reset();
2118 crafting?.reset();
2119 alchemy?.reset();
2120 staminaUi?.hide();
2121 healthUi?.hide();
2122 statusEffectsUi?.hide();
2123 skills?.hide();
2124 spells?.hide();
2125 contextMenu?.hide();
2126 death?.reset();
2127 shop?.close({ notifyServer: false });
2128 bounty?.close();
2129 barber?.close();
2130 questsUi?.reset();
2131 dialogueUi?.reset();
2132 hideWorldTooltip();
2133 if (view)
2134 { view.clearPlaySession(); }
2135 overlay.hidden = false;
2136 hud.hidden = true;
2137 const settingsToggle = document.getElementById("settings-toggle");
2138 if (settingsToggle)
2139 { settingsToggle.hidden = true; }
2140 graphicsSettingsUi?.close();
2141 if (reason)
2142 { statusEl.textContent = reason; }
2143}
2144
2145document.getElementById("create-character-open")?.addEventListener("click", () =>
2146{
2147 showError("");
2148 const createError = document.getElementById("create-error");
2149 if (createError)
2150 { createError.textContent = ""; }
2151 document.getElementById("create-backdrop").hidden = false;
2152 document.getElementById("create-panel").hidden = false;
2153 setCreateTab("appearance");
2154 void createHairControls?.refreshPreview();
2155});
2156
2157function closeCreateModal ()
2158{
2159 document.getElementById("create-backdrop").hidden = true;
2160 document.getElementById("create-panel").hidden = true;
2161}
2162
2163document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
2164document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
2165
2166document.getElementById("create-form").addEventListener("submit", (event) =>
2167{
2168 event.preventDefault();
2169 showError("");
2170 const createError = document.getElementById("create-error");
2171 if (createError)
2172 { createError.textContent = ""; }
2173 socket.send({
2174 type: MessageType.createCharacter,
2175 firstName: document.getElementById("first-name").value,
2176 lastName: document.getElementById("last-name").value,
2177 sex: document.getElementById("sex").value,
2178 hair: createHairControls?.currentHair?.() ?? null,
2179 clothing: createClothingControls?.currentClothing?.() ?? null
2180 });
2181});
2182
2183function initCreateTabs ()
2184{
2185 const tabs = document.querySelectorAll(".create-tab");
2186 for (const tab of tabs)
2187 {
2188 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
2189 }
2190 setCreateTab("appearance");
2191}
2192
2193function setCreateTab (name)
2194{
2195 createActiveTab = name === "clothing" ? "clothing" : "appearance";
2196 for (const tab of document.querySelectorAll(".create-tab"))
2197 {
2198 const on = tab.dataset.createTab === createActiveTab;
2199 tab.classList.toggle("active", on);
2200 tab.setAttribute("aria-selected", on ? "true" : "false");
2201 }
2202 for (const pane of document.querySelectorAll("[data-create-pane]"))
2203 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
2204 if (createActiveTab === "clothing")
2205 { void refreshCreateClothingPreview(); }
2206 else
2207 { void createHairControls?.refreshPreview(); }
2208}
2209
2210async function refreshCreateClothingPreview ()
2211{
2212 const canvas = document.getElementById("create-clothing-preview");
2213 if (!canvas || !createClothingControls)
2214 { return; }
2215 try
2216 {
2217 await paintCharacterPreview(canvas, {
2218 sex: document.getElementById("sex")?.value ?? "male",
2219 bag: createClothingControls.previewBag(),
2220 hair: createHairControls?.currentHair?.() ?? null,
2221 hideHeadgear: true,
2222 resolveSpriteUrl (name)
2223 {
2224 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2225 },
2226 scale: 4
2227 });
2228 }
2229 catch (error)
2230 { console.warn(error); }
2231}
2232
2233document.getElementById("leave").addEventListener("click", () =>
2234{
2235 socket.send({ type: MessageType.leaveWorld });
2236 returnToMenu();
2237});
2238
2239main().catch((error) =>
2240{
2241 showError(error.message);
2242 console.error(error);
2243});
2244
2245function isBankTile (view, tileX, tileY)
2246{
2247 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
2248}
2249
2250function isDoorwayTile (view, tileX, tileY)
2251{
2252 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
2253}
2254
2255function isMarketplaceTile (view, tileX, tileY)
2256{
2257 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
2258}
2259
2260function isBountyOfficeTile (view, tileX, tileY)
2261{
2262 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
2263}
2264
2265function isBarberTile (view, tileX, tileY)
2266{
2267 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
2268}
2269
2270function isCauldronTile (view, tileX, tileY)
2271{
2272 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2273}
2274
2275function isFurnaceTile (view, tileX, tileY)
2276{
2277 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2278}
2279
2280function isOvenTile (view, tileX, tileY)
2281{
2282 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2283}
2284
2285function isCampfireTile (view, tileX, tileY)
2286{
2287 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2288}
2289
2290function isFishingSpotTile (view, tileX, tileY)
2291{
2292 const block = blockAt(view, tileX, tileY);
2293 if (!block || block.typeId !== BlockType.fishingSpot)
2294 { return false; }
2295 return block.state !== "exhausted";
2296}
2297
2298function isAnvilTile (view, tileX, tileY)
2299{
2300 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2301}
2302
2303function isJeweleringStationTile (view, tileX, tileY)
2304{
2305 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2306}
2307
2308function isGroundWoodLog (ground)
2309{
2310 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2311 return def?.familyId === ItemFamilyId.log;
2312}
2313
2314function playerHasUsableTinderbox ()
2315{
2316 const slots = inventory?.getInventorySlots?.() ?? [];
2317 for (const slot of slots)
2318 {
2319 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2320 { continue; }
2321 const charges = slot.instance?.kind === "tinderbox"
2322 ? (slot.instance.charges | 0)
2323 : TINDERBOX_MAX_CHARGES;
2324 if (charges > 0)
2325 { return true; }
2326 }
2327 return false;
2328}
2329
2330function isWoodworkingBenchTile (view, tileX, tileY)
2331{
2332 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2333}
2334
2335function isCraftingBenchTile (view, tileX, tileY)
2336{
2337 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
2338}
2339
2340function isSpinningWheelTile (view, tileX, tileY)
2341{
2342 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
2343}
2344
2345function isLoomTile (view, tileX, tileY)
2346{
2347 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
2348}
2349
2350function isTailorBenchTile (view, tileX, tileY)
2351{
2352 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
2353}
2354
2355function isLeatherworkingTableTile (view, tileX, tileY)
2356{
2357 return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable;
2358}
2359
2360function isOreBoulderTile (view, tileX, tileY)
2361{
2362 const block = blockAt(view, tileX, tileY);
2363 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
2364}
2365
2366function isChopableTreeTile (view, tileX, tileY)
2367{
2368 return isChopableTreeBlock(blockAt(view, tileX, tileY));
2369}
2370
2371function isPickablePlantTile (view, tileX, tileY)
2372{
2373 return isPickablePlantBlock(blockAt(view, tileX, tileY));
2374}
2375
2376const SPELL_ENTITY_SNAP_TILES = 2;
2377
2378function updateSpellTargetHighlight ()
2379{
2380 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
2381 {
2382 view?.clearSpellTargetHighlight();
2383 return;
2384 }
2385 const canvas = scene?.canvas;
2386 if (!canvas)
2387 { return; }
2388 const rect = canvas.getBoundingClientRect();
2389 const mouseX = GameInput.mousePosition.x - rect.left;
2390 const mouseY = GameInput.mousePosition.y - rect.top;
2391 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2392 {
2393 view.clearSpellTargetHighlight();
2394 return;
2395 }
2396 const armed = spells.getArmedSpell?.();
2397 const local = view.entities.get(view.localEntityId);
2398 if (armed?.target === "entity")
2399 {
2400 const target = nearestSpellEntityAtCursor(mouseX, mouseY);
2401 if (!target)
2402 {
2403 view.clearSpellTargetHighlight();
2404 return;
2405 }
2406 const inRange = !local
2407 || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) <= COMBAT_RANGE_TILES;
2408 view.setSpellEntityTargetHighlight(target.entityId, inRange);
2409 return;
2410 }
2411 const tile = view.screenToTile(mouseX, mouseY);
2412 const inRange = !local
2413 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
2414 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
2415}
2416
2417/**
2418 * Nearest spell-targetable entity within {@link SPELL_ENTITY_SNAP_TILES} of the
2419 * cursor tile (uses both authoritative and visual tile for moving mobs).
2420 */
2421function nearestSpellEntityAtCursor (mouseX, mouseY)
2422{
2423 if (!view)
2424 { return null; }
2425 const cursor = view.screenToTile(mouseX, mouseY);
2426 const tileSize = view.tileSize();
2427 let best = null;
2428 let bestDist = Infinity;
2429 let bestScreen = Infinity;
2430 for (const entity of view.entities.values())
2431 {
2432 if (!isSpellEntityTarget(entity))
2433 { continue; }
2434 const visualTileX = Math.floor((entity.visualX + (entity.stackOffsetX ?? 0)) / tileSize);
2435 const visualTileY = Math.floor((entity.visualY + (entity.stackOffsetY ?? 0)) / tileSize);
2436 const dist = Math.min(
2437 chebyshev(cursor.tileX, cursor.tileY, entity.tileX, entity.tileY),
2438 chebyshev(cursor.tileX, cursor.tileY, visualTileX, visualTileY)
2439 );
2440 if (dist > SPELL_ENTITY_SNAP_TILES)
2441 { continue; }
2442 const box = view.nametagAnchor?.(entity);
2443 const screenDist = box
2444 ? Math.hypot(box.x - mouseX, box.y - mouseY)
2445 : dist;
2446 if (dist < bestDist || (dist === bestDist && screenDist < bestScreen))
2447 {
2448 best = entity;
2449 bestDist = dist;
2450 bestScreen = screenDist;
2451 }
2452 }
2453 return best;
2454}
2455
2456function isSpellEntityTarget (entity)
2457{
2458 if (!entity || entity.entityId === view?.localEntityId)
2459 { return false; }
2460 if (entity.untargetable || entity.freeFlight)
2461 { return false; }
2462 return isAttackableEntity(entity);
2463}
2464
2465function hideWorldTooltip ()
2466{
2467 if (worldTooltip)
2468 {
2469 worldTooltip.hidden = true;
2470 worldTooltip.classList.remove("friend-name");
2471 worldTooltip.style.color = "";
2472 }
2473}
2474
2475/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
2476function updateWorldTooltip ()
2477{
2478 if (!worldTooltip || !view || !scene || uiBlocked())
2479 {
2480 hideWorldTooltip();
2481 return;
2482 }
2483 const canvas = scene.canvas;
2484 const rect = canvas.getBoundingClientRect();
2485 const mouseX = GameInput.mousePosition.x - rect.left;
2486 const mouseY = GameInput.mousePosition.y - rect.top;
2487 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2488 {
2489 hideWorldTooltip();
2490 return;
2491 }
2492 const entity = view.entityAtScreen(mouseX, mouseY);
2493 if (entity && entity.entityId !== view.localEntityId)
2494 {
2495 const label = entityLabel(entity);
2496 worldTooltip.hidden = false;
2497 worldTooltip.textContent = label;
2498 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2499 worldTooltip.classList.toggle("friend-name", !!friend);
2500 worldTooltip.style.color = friend ? "#e8c84a" : "";
2501 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2502 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2503 return;
2504 }
2505 const tile = view.screenToTile(mouseX, mouseY);
2506 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
2507 if (!label)
2508 {
2509 hideWorldTooltip();
2510 return;
2511 }
2512 worldTooltip.hidden = false;
2513 worldTooltip.textContent = label;
2514 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2515 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2516}
2517
2518function blockTypeAt (view, tileX, tileY)
2519{
2520 return blockAt(view, tileX, tileY)?.typeId ?? null;
2521}
2522
2523function blockAt (view, tileX, tileY)
2524{
2525 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2526 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2527 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2528 if (!snapshot)
2529 { return null; }
2530 const localX = tileX - chunkX * CHUNK_SIZE;
2531 const localY = tileY - chunkY * CHUNK_SIZE;
2532 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
2533}
2534
2535function groundTypeAt (view, tileX, tileY)
2536{
2537 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2538 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2539 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2540 if (!snapshot)
2541 { return null; }
2542 const localX = tileX - chunkX * CHUNK_SIZE;
2543 const localY = tileY - chunkY * CHUNK_SIZE;
2544 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
2545}
2546
2547/** Best-effort client filter for approach destinations (server still authorizes paths). */
2548function isClientApproachable (tileX, tileY)
2549{
2550 if (!view)
2551 { return true; }
2552 const groundId = groundTypeAt(view, tileX, tileY);
2553 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
2554 if (groundDef && !groundDef.passable)
2555 { return false; }
2556 const block = blockAt(view, tileX, tileY);
2557 if (block?.typeId != null)
2558 {
2559 const blockDef = BLOCK_DEFINITIONS[block.typeId];
2560 if (blockDef && !blockDef.passable)
2561 { return false; }
2562 }
2563 for (const entity of view.entitiesAtTile(tileX, tileY))
2564 {
2565 if (entity.entityId === view.localEntityId)
2566 { continue; }
2567 if (entity.untargetable || entity.freeFlight)
2568 { continue; }
2569 return false;
2570 }
2571 return true;
2572}
2573
2574function chebyshev (ax, ay, bx, by)
2575{
2576 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
2577}
2578
2579function updateAuthUi (authStatus)
2580{
2581 const signIn = document.getElementById("auth-sign-in");
2582 const signOut = document.getElementById("auth-sign-out");
2583 const exportLink = document.getElementById("auth-export");
2584 if (signIn)
2585 {
2586 signIn.hidden = !!authStatus?.authenticated;
2587 signIn.href = loginUrl("/");
2588 }
2589 if (signOut)
2590 {
2591 signOut.hidden = !authStatus?.authenticated;
2592 signOut.href = logoutUrl("/");
2593 }
2594 if (exportLink)
2595 { exportLink.hidden = !authStatus?.authenticated; }
2596 if (authStatus?.authenticated && !session)
2597 {
2598 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
2599 }
2600}