BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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