BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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