BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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