BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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