BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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