BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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