BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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