BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 87.6 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 game.loadScene(scene);
1784 useNearestNeighbour(scene, game.images);
1785 }
1786 if (!view)
1787 {
1788 view = new WorldView(game, scene, catalog);
1789 graphicsSettingsUi?.apply();
1790 const ticker = new GameObject(0, 0, null, 10);
1791 ticker.update = (dt) =>
1792 {
1793 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
1794 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
1795 if (!leftPressed && !leftHeld)
1796 { leftClickConsumed = false; }
1797 else if (uiBlocked())
1798 {
1799 // Absorb presses that begin (or continue) over UI so dragging out of a
1800 // panel does not issue a world move/order on the same mouse hold.
1801 leftClickConsumed = true;
1802 }
1803 else if (!leftClickConsumed && playing)
1804 {
1805 leftClickConsumed = true;
1806 const canvas = scene.canvas;
1807 const rect = canvas.getBoundingClientRect();
1808 const mouseX = GameInput.mousePosition.x - rect.left;
1809 const mouseY = GameInput.mousePosition.y - rect.top;
1810 handleLeftClick(mouseX, mouseY);
1811 }
1812 if (GameInput.isPressed(82) && !uiBlocked())
1813 {
1814 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
1815 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
1816 { return; }
1817 socket.send({ type: MessageType.setGait, gait: next });
1818 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
1819 if (next === GAIT.walk)
1820 {
1821 gait = next;
1822 document.getElementById("gait").textContent = gait;
1823 }
1824 }
1825 if (playing && !death?.isBlocking())
1826 {
1827 flushPendingPickup();
1828 flushPendingInteract();
1829 syncAutorun();
1830 social?.updateNametag(view, scene, view.localEntityId);
1831 chat?.update(view, scene);
1832 updateSpellTargetHighlight();
1833 updateWorldTooltip();
1834 }
1835 else
1836 {
1837 hideWorldTooltip();
1838 view?.clearSpellTargetHighlight();
1839 }
1840 view.update(dt);
1841 };
1842 scene.addObject(ticker);
1843 window.addEventListener("resize", () =>
1844 {
1845 scene.size.x = window.innerWidth;
1846 scene.size.y = window.innerHeight;
1847 scene.g_fixSize();
1848 useNearestNeighbour(scene, game.images);
1849 });
1850 window.addEventListener("wheel", (event) =>
1851 {
1852 if (!playing || uiBlocked())
1853 { return; }
1854 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
1855 if (playZoomRaf)
1856 { return; }
1857 playZoomRaf = requestAnimationFrame(() =>
1858 {
1859 playZoomRaf = 0;
1860 if (!view || !playZoomDelta)
1861 { return; }
1862 view.setZoom(view.zoom + playZoomDelta);
1863 playZoomDelta = 0;
1864 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
1865 });
1866 }, { passive: true });
1867 scene.canvas.addEventListener("contextmenu", (event) =>
1868 {
1869 if (!playing || uiBlocked())
1870 { return; }
1871 const rect = scene.canvas.getBoundingClientRect();
1872 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
1873 });
1874 }
1875 view.setSettings(payload.settings ?? view.settings);
1876 chat?.syncSettings();
1877 view.worldHour = payload.worldTime?.hour ?? 12;
1878 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
1879 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
1880 view.setWorldSeason(payload.worldTime?.season);
1881 view.setLocalEntity(
1882 payload.entityId,
1883 payload.tileX,
1884 payload.tileY,
1885 payload.gait,
1886 payload.sex,
1887 payload.firstName,
1888 payload.lastName,
1889 payload.characterId,
1890 payload.layers,
1891 payload.health,
1892 payload.maxHealth,
1893 payload.skullValue
1894 );
1895 social?.setLocalIdentity?.({
1896 accountId: payload.accountId,
1897 characterId: payload.characterId
1898 });
1899 graphicsSettingsUi?.apply();
1900}
1901
1902async function main ()
1903{
1904 const authStatus = await fetchAuthStatus();
1905 updateAuthUi(authStatus);
1906 if (!authStatus.authenticated)
1907 {
1908 statusEl.textContent = "Sign in to play Questward.";
1909 showError("");
1910 return;
1911 }
1912
1913 setAssetLoading(true, { phase: "Loading catalog…" });
1914 catalog = await loadSpriteCatalog();
1915 const assetTotal = playImagesFromCatalog(catalog).length;
1916 setAssetLoading(true, { loaded: 0, total: assetTotal, phase: "Loading assets…" });
1917 await preloadCatalogImages(game, catalog, {
1918 onProgress ({ loaded, total })
1919 {
1920 setAssetLoading(true, { loaded, total });
1921 }
1922 });
1923 applySpriteSheets(game.images, catalog);
1924 if (!scene)
1925 {
1926 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1927 game.loadScene(scene);
1928 }
1929 setAssetLoading(false);
1930 statusEl.textContent = "Connecting…";
1931 createHairControls = bindHairControls({
1932 root: document.getElementById("create-hair"),
1933 resolveSpriteUrl (name)
1934 {
1935 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1936 },
1937 getSex: () => document.getElementById("sex")?.value ?? "male",
1938 getBag: () => null,
1939 hideHeadgear: true,
1940 onChange ()
1941 {
1942 if (createActiveTab === "clothing")
1943 { void refreshCreateClothingPreview(); }
1944 }
1945 });
1946 createClothingControls = bindCreateClothingControls({
1947 root: document.getElementById("create-clothing"),
1948 onChange ()
1949 {
1950 if (createActiveTab === "clothing")
1951 { void refreshCreateClothingPreview(); }
1952 }
1953 });
1954 initCreateTabs();
1955 document.getElementById("sex")?.addEventListener("change", () =>
1956 {
1957 createHairControls?.fillStyles();
1958 void createHairControls?.refreshPreview();
1959 if (createActiveTab === "clothing")
1960 { void refreshCreateClothingPreview(); }
1961 });
1962 void createHairControls?.refreshPreview();
1963 void refreshCreateClothingPreview();
1964 graphicsSettingsUi = initGraphicsSettings({
1965 onChange: applyGraphicsSettings,
1966 onSuppressWorldClick: consumeWorldClick
1967 });
1968 social = initSocial({
1969 socket: { send (payload) { socket.send(payload); } },
1970 MessageType,
1971 resolveSpriteUrl (name)
1972 {
1973 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1974 },
1975 resolveImage (name)
1976 {
1977 return game?.images?.[name] ?? null;
1978 }
1979 });
1980 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1981 const tipArrows = initTipArrows({
1982 socket: { send (payload) { socket.send(payload); } },
1983 MessageType,
1984 getInventoryBag ()
1985 {
1986 return inventory?.getBag?.() ?? null;
1987 }
1988 });
1989 inventory = initInventory({
1990 socket: { send (payload) { socket.send(payload); } },
1991 MessageType,
1992 contextMenu,
1993 tipArrows,
1994 resolveSpriteUrl (name)
1995 {
1996 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1997 },
1998 resolveImage (name)
1999 {
2000 return game?.images?.[name] ?? null;
2001 },
2002 getFriends ()
2003 {
2004 return social?.getFriends?.() ?? [];
2005 },
2006 getLocalName ()
2007 {
2008 const you = document.getElementById("you")?.textContent ?? "";
2009 return you.split("(")[0].trim() || "Unknown";
2010 },
2011 getSoftClaims ()
2012 {
2013 return [
2014 ...(alchemy?.listSoftClaims?.() ?? []),
2015 ...(trade?.listSoftClaims?.() ?? [])
2016 ];
2017 },
2018 onBagSlotActivate (slotIndex, slot)
2019 {
2020 if (!trade?.isOpen?.())
2021 { return false; }
2022 const real = inventory?.getInventorySlots?.()?.[slotIndex] ?? slot;
2023 return trade.offerBagSlot(slotIndex, real);
2024 },
2025 bagClicksLocked ()
2026 {
2027 return !!trade?.inventoryLocked?.();
2028 },
2029 knowsSpell (spellId)
2030 {
2031 return !!spells?.knowsSpell?.(spellId);
2032 },
2033 getSkillLevels ()
2034 {
2035 return skills?.getSkillLevels?.() ?? {};
2036 },
2037 getSettings ()
2038 {
2039 return view?.settings ?? null;
2040 },
2041 getKnownSpellIds ()
2042 {
2043 return spells?.getKnownSpellIds?.() ?? [];
2044 },
2045 onBagChanged ()
2046 {
2047 spells?.refreshMaxHitDisplay?.();
2048 }
2049 });
2050 skills = initSkills({
2051 getEquipmentSlots ()
2052 {
2053 return inventory?.getEquipment?.() ?? {};
2054 },
2055 getSettings ()
2056 {
2057 return view?.settings ?? null;
2058 }
2059 });
2060 spells = initSpells({
2061 socket: { send (payload) { socket.send(payload); } },
2062 MessageType,
2063 getSkillLevel (skillId)
2064 {
2065 return skills?.skillLevel?.(skillId) ?? 1;
2066 },
2067 getSkillLevels ()
2068 {
2069 return skills?.getSkillLevels?.() ?? {};
2070 },
2071 getEquipmentSlots ()
2072 {
2073 return inventory?.getEquipment?.() ?? {};
2074 },
2075 getSettings ()
2076 {
2077 return view?.settings ?? null;
2078 }
2079 });
2080 crafting = initCrafting({
2081 socket: { send (payload) { socket.send(payload); } },
2082 MessageType,
2083 getInventorySlots ()
2084 {
2085 return inventory?.getInventorySlots?.() ?? [];
2086 },
2087 getEquipment ()
2088 {
2089 return inventory?.getEquipment?.() ?? {};
2090 },
2091 getSkillLevel (skillId)
2092 {
2093 return skills?.skillLevel?.(skillId) ?? 1;
2094 }
2095 });
2096 alchemy = initAlchemy({
2097 socket: { send (payload) { socket.send(payload); } },
2098 MessageType,
2099 getInventorySlots ()
2100 {
2101 return inventory?.getInventorySlots?.() ?? [];
2102 }
2103 });
2104 alchemy?.setOnSoftClaimsChanged?.(() => inventory?.refreshBagDisplay?.());
2105 staminaUi = initStamina();
2106 healthUi = initHealth();
2107 statusEffectsUi = initStatusEffects();
2108 toasts = initToasts({ onSuppressWorldClick: consumeWorldClick });
2109 trade = initTrade({
2110 socket: { send (payload) { socket.send(payload); } },
2111 MessageType,
2112 toasts,
2113 getLocalEntity ()
2114 {
2115 return view?.entities.get(view.localEntityId) ?? null;
2116 },
2117 getEntity (id)
2118 {
2119 return view?.entities.get(id) ?? null;
2120 },
2121 approachAdjacentTile,
2122 clearPendingActions: clearAllPendingActions,
2123 setPendingTradeRequest (targetEntityId)
2124 {
2125 pendingInteract = {
2126 kind: "trade-request",
2127 targetEntityId: targetEntityId | 0
2128 };
2129 },
2130 setPendingTradeAccept (invite)
2131 {
2132 pendingInteract = {
2133 kind: "trade-accept",
2134 fromEntityId: invite.fromEntityId | 0,
2135 invite
2136 };
2137 },
2138 onSuppressWorldClick: consumeWorldClick,
2139 resolveSpriteUrl (name)
2140 {
2141 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2142 },
2143 resolveImage (name)
2144 {
2145 return game?.images?.[name] ?? null;
2146 },
2147 ensureBagOpen ()
2148 {
2149 const bagPanel = document.getElementById("bag-panel");
2150 if (bagPanel?.hidden)
2151 { bagPanel.hidden = false; }
2152 inventory?.refreshBagDisplay?.();
2153 },
2154 onTradeOpenChanged ()
2155 {
2156 inventory?.refreshBagDisplay?.();
2157 }
2158 });
2159 questsUi = initQuests({
2160 socket: { send (payload) { socket.send(payload); } },
2161 MessageType,
2162 toasts
2163 });
2164 dialogueUi = initDialogue({
2165 socket: { send (payload) { socket.send(payload); } },
2166 MessageType,
2167 getEntity (id)
2168 {
2169 if (id === "local")
2170 { return view?.entities.get(view.localEntityId) ?? null; }
2171 return view?.entities.get(id) ?? null;
2172 },
2173 captureSpeakerIcon (entityId, size = 64)
2174 {
2175 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
2176 }
2177 });
2178 shop = initShop({
2179 socket: { send (payload) { socket.send(payload); } },
2180 MessageType,
2181 onSuppressWorldClick: consumeWorldClick,
2182 getCoinCount ()
2183 {
2184 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
2185 },
2186 getInventorySlots ()
2187 {
2188 return inventory?.getInventorySlots?.() ?? [];
2189 }
2190 });
2191 market = initMarket({
2192 socket: { send (payload) { socket.send(payload); } },
2193 MessageType,
2194 onSuppressWorldClick: consumeWorldClick,
2195 getCoinCount ()
2196 {
2197 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
2198 },
2199 getInventorySlots ()
2200 {
2201 return inventory?.getInventorySlots?.() ?? [];
2202 },
2203 getLocalCharacterId ()
2204 {
2205 return inventory?.getLocalCharacterId?.() ?? null;
2206 }
2207 });
2208 bounty = initBounty({
2209 socket: { send (payload) { socket.send(payload); } },
2210 MessageType,
2211 onSuppressWorldClick: consumeWorldClick,
2212 resolveSpriteUrl (name)
2213 {
2214 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2215 },
2216 resolveImage (name)
2217 {
2218 return game?.images?.[name] ?? null;
2219 }
2220 });
2221 barber = initBarber({
2222 socket: { send (payload) { socket.send(payload); } },
2223 MessageType,
2224 onSuppressWorldClick: consumeWorldClick,
2225 resolveSpriteUrl (name)
2226 {
2227 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2228 },
2229 getInventoryBag ()
2230 {
2231 return {
2232 equipment: { slots: inventory?.getEquipment?.() ?? {} },
2233 inventory: inventory?.getInventorySlots?.() ?? []
2234 };
2235 }
2236 });
2237 chat = initChat({
2238 socket: { send (payload) { socket.send(payload); } },
2239 MessageType,
2240 getSettings: () => view?.settings
2241 });
2242 death = initDeath({
2243 socket: { send (payload) { socket.send(payload); } },
2244 MessageType
2245 });
2246 game.startGame();
2247 useNearestNeighbour(scene, game.images);
2248
2249 socket = new GameSocket(defaultSocketUrl(), (message) =>
2250 {
2251 switch (message.type)
2252 {
2253 case MessageType.session:
2254 session = message;
2255 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
2256 renderCharacters(message.characters);
2257 break;
2258 case MessageType.characterList:
2259 renderCharacters(message.characters);
2260 if (!playing)
2261 { overlay.hidden = false; }
2262 break;
2263 case MessageType.enterWorld:
2264 closeCreateModal();
2265 startPlay(message);
2266 inventory?.setLocalCharacterId(message.characterId);
2267 questsUi?.setLocalCharacterId?.(message.characterId);
2268 toasts?.applyRestartStatus?.(message.restartStatus);
2269 socket.send({ type: MessageType.requestQuests });
2270 break;
2271 case MessageType.chunkSnapshot:
2272 view?.applySnapshot(message);
2273 break;
2274 case MessageType.dimensionChanged:
2275 if (view)
2276 {
2277 view.setDimensionId(message.dimensionId);
2278 view.setDimensionModes(message.lightingMode, message.seasonMode);
2279 view.clearAllChunks();
2280 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
2281 {
2282 view.moveEntity({
2283 entityId: view.localEntityId,
2284 tileX: message.tileX,
2285 tileY: message.tileY
2286 });
2287 }
2288 }
2289 closeOpenUiIfTooFar();
2290 break;
2291 case MessageType.chunkDelta:
2292 if (isForeignDimensionMessage(message))
2293 { break; }
2294 for (const tile of message.tiles ?? [])
2295 {
2296 view?.updateAuthoredTile(
2297 message.chunkX,
2298 message.chunkY,
2299 tile.localX,
2300 tile.localY,
2301 { ground: tile.ground, block: tile.block, light: tile.light }
2302 );
2303 }
2304 break;
2305 case MessageType.unsubscribeChunk:
2306 view?.removeChunk(message.chunkX, message.chunkY);
2307 break;
2308 case MessageType.entitySpawn:
2309 view?.spawnEntity(message);
2310 break;
2311 case MessageType.entityMove:
2312 view?.moveEntity(message);
2313 if (message.entityId === view?.localEntityId)
2314 {
2315 if (message.gait)
2316 {
2317 gait = message.gait;
2318 document.getElementById("gait").textContent = gait;
2319 }
2320 closeOpenUiIfTooFar();
2321 }
2322 else if (
2323 uiFocus?.entityId != null
2324 && message.entityId === uiFocus.entityId
2325 )
2326 { closeOpenUiIfTooFar(); }
2327 break;
2328 case MessageType.entityDespawn:
2329 if (message.entityId === autorunFocusEntityId)
2330 { clearAutorunFocus(); }
2331 clearCombatWithLocal(message.entityId);
2332 view?.despawnEntity(message.entityId, {
2333 combatDeath: message.cause === "death"
2334 });
2335 break;
2336 case MessageType.entityAppearance:
2337 view?.setAppearance(message);
2338 break;
2339 case MessageType.entitySkull:
2340 view?.updateEntitySkull(message.entityId, message.skullValue);
2341 break;
2342 case MessageType.groundItemAppear:
2343 if (isForeignDimensionMessage(message))
2344 { break; }
2345 view?.upsertGroundItem(message);
2346 break;
2347 case MessageType.groundItemDespawn:
2348 view?.despawnGroundItem(message.groundItemId);
2349 break;
2350 case MessageType.inventory:
2351 inventory?.handleInventory(message);
2352 skills?.refresh?.();
2353 crafting?.refresh();
2354 alchemy?.refresh();
2355 shop?.refresh();
2356 market?.refresh();
2357 break;
2358 case MessageType.skills:
2359 skills?.render(message.skills, message.combatLevel);
2360 inventory?.refreshMaxHit?.();
2361 spells?.refreshMaxHitDisplay?.();
2362 crafting?.refresh();
2363 spells?.refreshCastGates?.();
2364 break;
2365 case MessageType.spells:
2366 case MessageType.spellsUpdated:
2367 spells?.render(message);
2368 inventory?.refreshMaxHit?.();
2369 break;
2370 case MessageType.spellArmed:
2371 spells?.handleSpellArmed(message);
2372 break;
2373 case MessageType.spellDisarmed:
2374 spells?.handleSpellDisarmed();
2375 break;
2376 case MessageType.spellProjectile:
2377 if (isForeignDimensionMessage(message))
2378 { break; }
2379 view?.spawnSpellProjectileFx(message);
2380 if (message.casterId === view?.localEntityId)
2381 { clearAutorunFocus(); }
2382 break;
2383 case MessageType.spellFizzle:
2384 if (isForeignDimensionMessage(message))
2385 { break; }
2386 view?.spawnSpellFizzleFx(message);
2387 if (message.casterId === view?.localEntityId)
2388 {
2389 clearAutorunFocus();
2390 toasts?.show("Failed to cast spell");
2391 }
2392 break;
2393 case MessageType.spellCastFlash:
2394 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
2395 if (isForeignDimensionMessage(message))
2396 { break; }
2397 if (message.casterId === view?.localEntityId)
2398 { clearAutorunFocus(); }
2399 break;
2400 case MessageType.spellLightAppear:
2401 case MessageType.spellLightUpdate:
2402 if (isForeignDimensionMessage(message))
2403 { break; }
2404 view?.setSpellLight(message);
2405 break;
2406 case MessageType.spellLightRemove:
2407 if (isForeignDimensionMessage(message))
2408 { break; }
2409 view?.removeSpellLight(message);
2410 break;
2411 case MessageType.spellDarkAppear:
2412 case MessageType.spellDarkUpdate:
2413 if (isForeignDimensionMessage(message))
2414 { break; }
2415 view?.setSpellDark(message);
2416 break;
2417 case MessageType.spellDarkRemove:
2418 if (isForeignDimensionMessage(message))
2419 { break; }
2420 view?.removeSpellDark(message);
2421 break;
2422 case MessageType.stamina:
2423 staminaUi?.apply(message);
2424 if (message.gait)
2425 {
2426 gait = message.gait;
2427 document.getElementById("gait").textContent = gait;
2428 if (gait === GAIT.walk && (staminaUi?.getCurrent?.() ?? 0) <= 0)
2429 { autorunWaitingStamina = true; }
2430 }
2431 syncAutorun();
2432 break;
2433 case MessageType.statusEffects:
2434 view?.setLocalBlind(!!message.blind);
2435 statusEffectsUi?.apply(message);
2436 break;
2437 case MessageType.bankSnapshot:
2438 inventory?.handleBank(message);
2439 break;
2440 case MessageType.cauldronSnapshot:
2441 if (message.open === false && uiFocus?.kind === "cauldron")
2442 { clearUiFocus(); }
2443 alchemy?.handleSnapshot(message);
2444 break;
2445 case MessageType.pigeonDispatched:
2446 inventory?.handlePigeonDispatched(message);
2447 break;
2448 case MessageType.pigeonDelivered:
2449 inventory?.handlePigeonDelivered(message);
2450 break;
2451 case MessageType.characterSearchResult:
2452 inventory?.handleCharacterSearch(message);
2453 break;
2454 case MessageType.craftResult:
2455 crafting?.handleCraftResult(message);
2456 break;
2457 case MessageType.worldStatus:
2458 if (view)
2459 {
2460 view.setSettings(message.settings ?? view.settings);
2461 view.worldHour = message.worldTime?.hour ?? view.worldHour;
2462 view.setWorldSeason(message.worldTime?.season);
2463 chat?.syncSettings();
2464 }
2465 skills?.refresh?.();
2466 toasts?.applyRestartStatus?.(message.restartStatus);
2467 break;
2468 case MessageType.restartStatus:
2469 toasts?.applyRestartStatus?.(message.restartStatus);
2470 break;
2471 case MessageType.chatBubble:
2472 chat?.showBubble(message);
2473 break;
2474 case MessageType.friends:
2475 social?.handleFriends(message);
2476 break;
2477 case MessageType.combatSwing:
2478 if (isForeignDimensionMessage(message))
2479 { break; }
2480 noteCombatWithLocal(message.attackerId, message.targetId);
2481 view?.spawnCombatSwing(message);
2482 break;
2483 case MessageType.combatProjectile:
2484 if (isForeignDimensionMessage(message))
2485 { break; }
2486 noteCombatWithLocal(message.attackerId, message.targetId);
2487 view?.spawnPhysicalProjectileFx({
2488 ...message,
2489 sprite: "fx:projectile:arrow"
2490 });
2491 break;
2492 case MessageType.combatNoArrows:
2493 toasts?.show("Out of arrows!");
2494 break;
2495 case MessageType.gatherSwing:
2496 case MessageType.tileShove:
2497 if (isForeignDimensionMessage(message))
2498 { break; }
2499 view?.spawnGatherSwing(message);
2500 break;
2501 case MessageType.stationOpen:
2502 if (message.stationId)
2503 { crafting?.openStation(message.stationId); }
2504 break;
2505 case MessageType.shopOpen:
2506 if (message.npcEntityId != null)
2507 { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); }
2508 shop?.handleShopOpen(message);
2509 break;
2510 case MessageType.shopClosed:
2511 if (uiFocus?.kind === "shop")
2512 { clearUiFocus(); }
2513 shop?.handleShopClosed(message);
2514 break;
2515 case MessageType.marketOpen:
2516 market?.handleOpen(message);
2517 break;
2518 case MessageType.marketClosed:
2519 if (uiFocus?.kind === "market")
2520 { clearUiFocus(); }
2521 market?.handleClosed(message);
2522 break;
2523 case MessageType.marketTrade:
2524 market?.handleTrade(message);
2525 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
2526 break;
2527 case MessageType.bountySnapshot:
2528 bounty?.handleSnapshot(message);
2529 break;
2530 case MessageType.closeBounty:
2531 if (uiFocus?.kind === "bounty")
2532 { clearUiFocus(); }
2533 bounty?.handleClosed(message);
2534 break;
2535 case MessageType.characterBounty:
2536 bounty?.handleCharacterBounty(message);
2537 social?.handleCharacterBounty(message);
2538 break;
2539 case MessageType.barberSnapshot:
2540 barber?.handleSnapshot(message);
2541 break;
2542 case MessageType.closeBarber:
2543 if (uiFocus?.kind === "barber")
2544 { clearUiFocus(); }
2545 barber?.handleClosed(message);
2546 break;
2547 case MessageType.itemBubble:
2548 chat?.showItemBubble(message);
2549 break;
2550 case MessageType.gatherComplete:
2551 crafting?.refresh();
2552 break;
2553 case MessageType.combatHit:
2554 {
2555 if (isForeignDimensionMessage(message))
2556 { break; }
2557 noteCombatWithLocal(message.attackerId, message.targetId);
2558 const applyHit = () =>
2559 {
2560 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
2561 view?.flashDamage(message.targetId);
2562 view?.spawnCombatKnockback?.(message);
2563 view?.spawnDamageNumber(message.targetId, message.damage);
2564 if (message.targetId === view?.localEntityId)
2565 {
2566 healthUi?.apply({
2567 current: message.health,
2568 max: message.maxHealth
2569 });
2570 }
2571 };
2572 if (!view?.deferCombatHit?.(message, applyHit))
2573 { applyHit(); }
2574 break;
2575 }
2576 case MessageType.combatMiss:
2577 if (isForeignDimensionMessage(message))
2578 { break; }
2579 noteCombatWithLocal(message.attackerId, message.targetId);
2580 view?.spawnCombatDodge?.(message);
2581 view?.markProjectileMiss?.(message);
2582 break;
2583 case MessageType.combatBlock:
2584 {
2585 if (isForeignDimensionMessage(message))
2586 { break; }
2587 noteCombatWithLocal(message.attackerId, message.targetId);
2588 const applyBlock = () =>
2589 {
2590 view?.flashBlock?.(message.targetId);
2591 if (message.health != null)
2592 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
2593 };
2594 if (!view?.deferCombatHit?.(message, applyBlock))
2595 { applyBlock(); }
2596 break;
2597 }
2598 case MessageType.entityHealth:
2599 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2600 if (message.entityId === view?.localEntityId)
2601 {
2602 healthUi?.apply({
2603 current: message.health,
2604 max: message.maxHealth
2605 });
2606 }
2607 break;
2608 case MessageType.skillLevelUp:
2609 view?.spawnSkillLevelUp(message.entityId, message);
2610 if (message.entityId === view?.localEntityId)
2611 {
2612 const level = message.level | 0;
2613 const previousLevel = message.previousLevel == null
2614 ? Math.max(0, level - 1)
2615 : message.previousLevel | 0;
2616 const unlockCount = skillUnlockMessages(message.skillId, previousLevel, level).length;
2617 toasts?.show(skillLevelUpToastText(message.skillId, level, previousLevel), {
2618 durationMs: 3500 + unlockCount * 1600
2619 });
2620 }
2621 break;
2622 case MessageType.playerDied:
2623 clearAllPendingActions();
2624 clearAutorunFocus();
2625 contextMenu?.hide();
2626 spells?.handleSpellDisarmed?.();
2627 closeCloseablePlayUi();
2628 death?.show();
2629 if (message.entityId === view?.localEntityId)
2630 {
2631 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
2632 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
2633 }
2634 // Red silhouette fade if despawn is delayed or already queued this tick.
2635 view?.beginDeathDissolve?.(message.entityId);
2636 break;
2637 case MessageType.playerRespawned:
2638 death?.hide();
2639 // Drop deferred killing-blow health=0 that may still be queued on a projectile.
2640 view?.cancelDeferredCombatHits?.(message.entityId);
2641 view?.reviveAfterDeath?.(message.entityId, {
2642 tileX: message.tileX,
2643 tileY: message.tileY,
2644 health: message.health,
2645 maxHealth: message.maxHealth,
2646 skullValue: message.skullValue
2647 });
2648 if (message.entityId === view?.localEntityId)
2649 {
2650 healthUi?.apply({
2651 current: message.health,
2652 max: message.maxHealth
2653 });
2654 }
2655 if (message.stamina != null || message.maxStamina != null)
2656 {
2657 staminaUi?.apply({
2658 current: message.stamina ?? staminaUi.getCurrent?.(),
2659 max: message.maxStamina ?? staminaUi.getMax?.()
2660 });
2661 }
2662 break;
2663 case MessageType.error:
2664 if (playing)
2665 { toasts?.show(message.message); }
2666 else
2667 {
2668 const createPanel = document.getElementById("create-panel");
2669 const createError = document.getElementById("create-error");
2670 if (createPanel && !createPanel.hidden && createError)
2671 { createError.textContent = message.message ?? ""; }
2672 else
2673 { showError(message.message); }
2674 }
2675 social?.showError(message.message);
2676 break;
2677 case MessageType.toast:
2678 if (playing)
2679 { toasts?.show(message.message); }
2680 break;
2681 case MessageType.tradeInvite:
2682 case MessageType.tradeInviteExpired:
2683 case MessageType.tradeOpen:
2684 case MessageType.tradeState:
2685 case MessageType.tradeClosed:
2686 if (playing)
2687 { trade?.handleMessage?.(message); }
2688 break;
2689 case MessageType.questsSnapshot:
2690 questsUi?.applySnapshot(message);
2691 break;
2692 case MessageType.questStepComplete:
2693 questsUi?.handleStepComplete(message);
2694 break;
2695 case MessageType.questObjectiveComplete:
2696 questsUi?.handleObjectiveComplete?.(message);
2697 break;
2698 case MessageType.questComplete:
2699 questsUi?.handleComplete?.(message);
2700 break;
2701 case MessageType.dialogueStep:
2702 if (message.npcEntityId != null)
2703 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2704 dialogueUi?.handleStep(message);
2705 break;
2706 case MessageType.dialogueItemRewards:
2707 if (message.npcEntityId != null)
2708 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2709 dialogueUi?.handleItemRewards(message);
2710 break;
2711 case MessageType.dialogueChoices:
2712 if (message.npcEntityId != null)
2713 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2714 dialogueUi?.handleChoices(message);
2715 break;
2716 case MessageType.dialogueClose:
2717 if (uiFocus?.kind === "dialogue")
2718 { clearUiFocus(); }
2719 dialogueUi?.handleClose(message);
2720 break;
2721 case MessageType.forceLogout:
2722 returnToMenu(message.reason);
2723 break;
2724 }
2725 }, {
2726 onClose (event)
2727 {
2728 if (playing)
2729 { returnToMenu(event.reason || "Disconnected from server."); }
2730 }
2731 });
2732 await socket.connect();
2733 if (typeof window !== "undefined")
2734 {
2735 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
2736 {
2737 crafting?.openStation(stationId);
2738 };
2739 }
2740}
2741
2742function returnToMenu (reason = "")
2743{
2744 playing = false;
2745 followTargetId = null;
2746 moveDest = null;
2747 clearAutorunFocus();
2748 clearCombatWithLocal();
2749 autorunWaitingStamina = false;
2750 clearAllPendingActions();
2751 clearUiFocus();
2752 social?.reset();
2753 chat?.reset();
2754 inventory?.reset();
2755 crafting?.reset();
2756 alchemy?.reset();
2757 staminaUi?.hide();
2758 healthUi?.hide();
2759 statusEffectsUi?.hide();
2760 skills?.hide();
2761 spells?.hide();
2762 contextMenu?.hide();
2763 death?.reset();
2764 shop?.close({ notifyServer: false });
2765 bounty?.close();
2766 barber?.close();
2767 questsUi?.reset();
2768 dialogueUi?.reset();
2769 hideWorldTooltip();
2770 if (view)
2771 { view.clearPlaySession(); }
2772 overlay.hidden = false;
2773 hud.hidden = true;
2774 const settingsToggle = document.getElementById("settings-toggle");
2775 if (settingsToggle)
2776 { settingsToggle.hidden = true; }
2777 graphicsSettingsUi?.close();
2778 if (reason)
2779 { statusEl.textContent = reason; }
2780}
2781
2782document.getElementById("create-character-open")?.addEventListener("click", () =>
2783{
2784 showError("");
2785 const createError = document.getElementById("create-error");
2786 if (createError)
2787 { createError.textContent = ""; }
2788 document.getElementById("create-backdrop").hidden = false;
2789 document.getElementById("create-panel").hidden = false;
2790 setCreateTab("appearance");
2791 void createHairControls?.refreshPreview();
2792});
2793
2794function closeCreateModal ()
2795{
2796 document.getElementById("create-backdrop").hidden = true;
2797 document.getElementById("create-panel").hidden = true;
2798}
2799
2800document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
2801document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
2802
2803document.getElementById("create-form").addEventListener("submit", (event) =>
2804{
2805 event.preventDefault();
2806 showError("");
2807 const createError = document.getElementById("create-error");
2808 if (createError)
2809 { createError.textContent = ""; }
2810 const names = validateCharacterNames({
2811 firstName: document.getElementById("first-name").value,
2812 lastName: document.getElementById("last-name").value,
2813 isAdmin: !!session?.isAdmin
2814 });
2815 if (!names.ok)
2816 {
2817 if (createError)
2818 { createError.textContent = names.reason; }
2819 else
2820 { showError(names.reason); }
2821 return;
2822 }
2823 socket.send({
2824 type: MessageType.createCharacter,
2825 firstName: names.firstName,
2826 lastName: names.lastName,
2827 sex: document.getElementById("sex").value,
2828 hair: createHairControls?.currentHair?.() ?? null,
2829 clothing: createClothingControls?.currentClothing?.() ?? null
2830 });
2831});
2832
2833function initCreateTabs ()
2834{
2835 const tabs = document.querySelectorAll(".create-tab");
2836 for (const tab of tabs)
2837 {
2838 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
2839 }
2840 setCreateTab("appearance");
2841}
2842
2843function setCreateTab (name)
2844{
2845 createActiveTab = name === "clothing" ? "clothing" : "appearance";
2846 for (const tab of document.querySelectorAll(".create-tab"))
2847 {
2848 const on = tab.dataset.createTab === createActiveTab;
2849 tab.classList.toggle("active", on);
2850 tab.setAttribute("aria-selected", on ? "true" : "false");
2851 }
2852 for (const pane of document.querySelectorAll("[data-create-pane]"))
2853 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
2854 if (createActiveTab === "clothing")
2855 { void refreshCreateClothingPreview(); }
2856 else
2857 { void createHairControls?.refreshPreview(); }
2858}
2859
2860async function refreshCreateClothingPreview ()
2861{
2862 const canvas = document.getElementById("create-clothing-preview");
2863 if (!canvas || !createClothingControls)
2864 { return; }
2865 try
2866 {
2867 await paintCharacterPreview(canvas, {
2868 sex: document.getElementById("sex")?.value ?? "male",
2869 bag: createClothingControls.previewBag(),
2870 hair: createHairControls?.currentHair?.() ?? null,
2871 hideHeadgear: true,
2872 resolveSpriteUrl (name)
2873 {
2874 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2875 },
2876 scale: 4
2877 });
2878 }
2879 catch (error)
2880 { console.warn(error); }
2881}
2882
2883document.getElementById("leave").addEventListener("click", () =>
2884{
2885 socket.send({ type: MessageType.leaveWorld });
2886 returnToMenu();
2887});
2888
2889main().catch((error) =>
2890{
2891 showError(error.message);
2892 console.error(error);
2893});
2894
2895function isBankTile (view, tileX, tileY)
2896{
2897 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
2898}
2899
2900function isDoorwayTile (view, tileX, tileY)
2901{
2902 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
2903}
2904
2905function isMarketplaceTile (view, tileX, tileY)
2906{
2907 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
2908}
2909
2910function isBountyOfficeTile (view, tileX, tileY)
2911{
2912 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
2913}
2914
2915function isBarberTile (view, tileX, tileY)
2916{
2917 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
2918}
2919
2920function isCauldronTile (view, tileX, tileY)
2921{
2922 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2923}
2924
2925function isChurchAltarTile (view, tileX, tileY)
2926{
2927 return blockTypeAt(view, tileX, tileY) === BlockType.churchAltar;
2928}
2929
2930function isFurnaceTile (view, tileX, tileY)
2931{
2932 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2933}
2934
2935function isOvenTile (view, tileX, tileY)
2936{
2937 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2938}
2939
2940function isCampfireTile (view, tileX, tileY)
2941{
2942 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2943}
2944
2945function isFishingSpotTile (view, tileX, tileY)
2946{
2947 const block = blockAt(view, tileX, tileY);
2948 if (!block || block.typeId !== BlockType.fishingSpot)
2949 { return false; }
2950 return block.state !== "exhausted";
2951}
2952
2953function isAnvilTile (view, tileX, tileY)
2954{
2955 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2956}
2957
2958function isJeweleringStationTile (view, tileX, tileY)
2959{
2960 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2961}
2962
2963function isGroundWoodLog (ground)
2964{
2965 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2966 return def?.familyId === ItemFamilyId.log;
2967}
2968
2969function playerHasUsableTinderbox ()
2970{
2971 const slots = inventory?.getInventorySlots?.() ?? [];
2972 for (const slot of slots)
2973 {
2974 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2975 { continue; }
2976 const charges = slot.instance?.kind === "tinderbox"
2977 ? (slot.instance.charges | 0)
2978 : TINDERBOX_MAX_CHARGES;
2979 if (charges > 0)
2980 { return true; }
2981 }
2982 return false;
2983}
2984
2985function isWoodworkingBenchTile (view, tileX, tileY)
2986{
2987 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2988}
2989
2990function isCraftingBenchTile (view, tileX, tileY)
2991{
2992 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
2993}
2994
2995function isSpinningWheelTile (view, tileX, tileY)
2996{
2997 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
2998}
2999
3000function isLoomTile (view, tileX, tileY)
3001{
3002 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
3003}
3004
3005function isTailorBenchTile (view, tileX, tileY)
3006{
3007 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
3008}
3009
3010function isLeatherworkingTableTile (view, tileX, tileY)
3011{
3012 return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable;
3013}
3014
3015function isOreBoulderTile (view, tileX, tileY)
3016{
3017 const block = blockAt(view, tileX, tileY);
3018 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
3019}
3020
3021function isChopableTreeTile (view, tileX, tileY)
3022{
3023 return isChopableTreeBlock(blockAt(view, tileX, tileY));
3024}
3025
3026function isPickablePlantTile (view, tileX, tileY)
3027{
3028 return isPickablePlantBlock(blockAt(view, tileX, tileY));
3029}
3030
3031const SPELL_ENTITY_SNAP_TILES = 2;
3032
3033function updateSpellTargetHighlight ()
3034{
3035 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
3036 {
3037 view?.clearSpellTargetHighlight();
3038 return;
3039 }
3040 const canvas = scene?.canvas;
3041 if (!canvas)
3042 { return; }
3043 const rect = canvas.getBoundingClientRect();
3044 const mouseX = GameInput.mousePosition.x - rect.left;
3045 const mouseY = GameInput.mousePosition.y - rect.top;
3046 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
3047 {
3048 view.clearSpellTargetHighlight();
3049 return;
3050 }
3051 const armed = spells.getArmedSpell?.();
3052 const local = view.entities.get(view.localEntityId);
3053 if (armed?.target === "entity")
3054 {
3055 const target = nearestSpellEntityAtCursor(mouseX, mouseY);
3056 if (!target)
3057 {
3058 view.clearSpellTargetHighlight();
3059 return;
3060 }
3061 const inRange = !local
3062 || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) <= COMBAT_RANGE_TILES;
3063 view.setSpellEntityTargetHighlight(target.entityId, inRange);
3064 return;
3065 }
3066 const tile = view.screenToTile(mouseX, mouseY);
3067 const inRange = !local
3068 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
3069 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
3070}
3071
3072/**
3073 * Nearest spell-targetable entity within {@link SPELL_ENTITY_SNAP_TILES} of the
3074 * cursor tile (uses both authoritative and visual tile for moving mobs).
3075 */
3076function nearestSpellEntityAtCursor (mouseX, mouseY)
3077{
3078 if (!view)
3079 { return null; }
3080 const cursor = view.screenToTile(mouseX, mouseY);
3081 const tileSize = view.tileSize();
3082 let best = null;
3083 let bestDist = Infinity;
3084 let bestScreen = Infinity;
3085 for (const entity of view.entities.values())
3086 {
3087 if (!isSpellEntityTarget(entity))
3088 { continue; }
3089 const visualTileX = Math.floor((entity.visualX + (entity.stackOffsetX ?? 0)) / tileSize);
3090 const visualTileY = Math.floor((entity.visualY + (entity.stackOffsetY ?? 0)) / tileSize);
3091 const dist = Math.min(
3092 chebyshev(cursor.tileX, cursor.tileY, entity.tileX, entity.tileY),
3093 chebyshev(cursor.tileX, cursor.tileY, visualTileX, visualTileY)
3094 );
3095 if (dist > SPELL_ENTITY_SNAP_TILES)
3096 { continue; }
3097 const box = view.nametagAnchor?.(entity);
3098 const screenDist = box
3099 ? Math.hypot(box.x - mouseX, box.y - mouseY)
3100 : dist;
3101 if (dist < bestDist || (dist === bestDist && screenDist < bestScreen))
3102 {
3103 best = entity;
3104 bestDist = dist;
3105 bestScreen = screenDist;
3106 }
3107 }
3108 return best;
3109}
3110
3111function isSpellEntityTarget (entity)
3112{
3113 if (!entity || entity.entityId === view?.localEntityId)
3114 { return false; }
3115 if (entity.untargetable || entity.freeFlight)
3116 { return false; }
3117 return isAttackableEntity(entity);
3118}
3119
3120function hideWorldTooltip ()
3121{
3122 if (worldTooltip)
3123 {
3124 worldTooltip.hidden = true;
3125 worldTooltip.classList.remove("friend-name");
3126 worldTooltip.style.color = "";
3127 }
3128}
3129
3130/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
3131function updateWorldTooltip ()
3132{
3133 if (!worldTooltip || !view || !scene || uiBlocked())
3134 {
3135 hideWorldTooltip();
3136 return;
3137 }
3138 const canvas = scene.canvas;
3139 const rect = canvas.getBoundingClientRect();
3140 const mouseX = GameInput.mousePosition.x - rect.left;
3141 const mouseY = GameInput.mousePosition.y - rect.top;
3142 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
3143 {
3144 hideWorldTooltip();
3145 return;
3146 }
3147 const entity = view.entityAtScreen(mouseX, mouseY);
3148 if (entity && entity.entityId !== view.localEntityId)
3149 {
3150 const label = entityLabel(entity);
3151 worldTooltip.hidden = false;
3152 worldTooltip.textContent = label;
3153 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
3154 worldTooltip.classList.toggle("friend-name", !!friend);
3155 worldTooltip.style.color = friend ? "#e8c84a" : "";
3156 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
3157 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
3158 return;
3159 }
3160 const tile = view.screenToTile(mouseX, mouseY);
3161 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
3162 if (!label)
3163 {
3164 hideWorldTooltip();
3165 return;
3166 }
3167 worldTooltip.hidden = false;
3168 worldTooltip.textContent = label;
3169 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
3170 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
3171}
3172
3173function blockTypeAt (view, tileX, tileY)
3174{
3175 return blockAt(view, tileX, tileY)?.typeId ?? null;
3176}
3177
3178function blockAt (view, tileX, tileY)
3179{
3180 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3181 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3182 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
3183 if (!snapshot)
3184 { return null; }
3185 const localX = tileX - chunkX * CHUNK_SIZE;
3186 const localY = tileY - chunkY * CHUNK_SIZE;
3187 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
3188}
3189
3190function groundTypeAt (view, tileX, tileY)
3191{
3192 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3193 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3194 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
3195 if (!snapshot)
3196 { return null; }
3197 const localX = tileX - chunkX * CHUNK_SIZE;
3198 const localY = tileY - chunkY * CHUNK_SIZE;
3199 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
3200}
3201
3202/** Best-effort client filter for approach destinations (server still authorizes paths). */
3203function isClientApproachable (tileX, tileY)
3204{
3205 if (!view)
3206 { return true; }
3207 const groundId = groundTypeAt(view, tileX, tileY);
3208 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
3209 if (groundDef && !groundDef.passable)
3210 { return false; }
3211 const block = blockAt(view, tileX, tileY);
3212 if (block?.typeId != null)
3213 {
3214 const blockDef = BLOCK_DEFINITIONS[block.typeId];
3215 if (blockDef && !blockDef.passable)
3216 { return false; }
3217 }
3218 for (const entity of view.entitiesAtTile(tileX, tileY))
3219 {
3220 if (entity.entityId === view.localEntityId)
3221 { continue; }
3222 if (entity.untargetable || entity.freeFlight)
3223 { continue; }
3224 return false;
3225 }
3226 return true;
3227}
3228
3229function chebyshev (ax, ay, bx, by)
3230{
3231 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
3232}
3233
3234function updateAuthUi (authStatus)
3235{
3236 const signIn = document.getElementById("auth-sign-in");
3237 const signOut = document.getElementById("auth-sign-out");
3238 const exportLink = document.getElementById("auth-export");
3239 if (signIn)
3240 {
3241 signIn.hidden = !!authStatus?.authenticated;
3242 signIn.href = loginUrl("/");
3243 }
3244 if (signOut)
3245 {
3246 signOut.hidden = !authStatus?.authenticated;
3247 signOut.href = logoutUrl("/");
3248 }
3249 if (exportLink)
3250 { exportLink.hidden = !authStatus?.authenticated; }
3251 if (createCharacterOpen)
3252 { createCharacterOpen.hidden = !authStatus?.authenticated; }
3253 if (authStatus?.authenticated && !session)
3254 {
3255 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
3256 }
3257}