BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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