BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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