BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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