BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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