BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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