BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

tweaks to sprites, shading
timfa Tim Falken · pushed by timfa · 2 months ago
48b50124 History
main.js 32.7 KiB Download Raw
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock } from "/shared/definitions/tiles.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5import { WorldView } from "../render/worldView.js";
6import { initSocial } from "./social.js";
7import { initChat } from "./chat.js";
8import { initInventory } from "./inventory.js";
9import { initSkills } from "./skills.js";
10import { initCrafting } from "./crafting.js";
11import { initAlchemy } from "./alchemy.js";
12import { initStamina } from "./stamina.js";
13import { initContextMenu } from "./contextMenu.js";
14import { initDeath } from "./death.js";
15import { initToasts } from "./toasts.js";
16import { initShop } from "./shop.js";
17import { initMarket } from "./market.js";
18import { CraftingStationId } from "/shared/definitions/craftingStations.js";
19import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
20import { formatQuantity } from "/shared/items/formatQuantity.js";
21import { ItemId } from "/shared/definitions/items.js";
22import { countCoinsInSlots } from "/shared/items/inventory.js";
23
24const game = new Game();
25const hud = document.getElementById("hud");
26const overlay = document.getElementById("overlay");
27const statusEl = document.getElementById("status");
28const characterList = document.getElementById("character-list");
29const errorEl = document.getElementById("error");
30const worldTooltip = document.getElementById("world-tooltip");
31
32let socket;
33let session = null;
34let playing = false;
35let view = null;
36let scene = null;
37let gait = GAIT.walk;
38let catalog = { grounds: {}, blocks: {} };
39let social;
40let chat;
41let inventory;
42let skills;
43let crafting;
44let alchemy;
45let staminaUi;
46let contextMenu;
47let death;
48let toasts;
49let shop;
50let market;
51let pendingPickup = null;
52/** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
53let pendingInteract = null;
54/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
55let approachMove = null;
56/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
57let leftClickConsumed = false;
58
59function consumeWorldClick ()
60{
61 leftClickConsumed = true;
62}
63
64function showError (message)
65{
66 errorEl.textContent = message ?? "";
67}
68
69function renderCharacters (characters)
70{
71 characterList.innerHTML = "";
72 for (const character of characters)
73 {
74 const row = document.createElement("div");
75 row.className = "character-row";
76 const pending = character.deletionScheduledAt
77 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
78 : "";
79 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
80 const play = document.createElement("button");
81 play.textContent = "Play";
82 play.disabled = !!character.deletionScheduledAt;
83 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
84 const del = document.createElement("button");
85 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
86 del.addEventListener("click", () =>
87 {
88 socket.send({
89 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
90 characterId: character.characterId
91 });
92 });
93 row.append(play, del);
94 characterList.append(row);
95 }
96}
97
98function uiBlocked ()
99{
100 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
101 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
102 || market?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
103}
104
105function clearPendingPickup ()
106{
107 pendingPickup = null;
108}
109
110function clearPendingInteract ()
111{
112 pendingInteract = null;
113 approachMove = null;
114}
115
116function clearAllPendingActions ()
117{
118 clearPendingPickup();
119 clearPendingInteract();
120}
121
122function approachAdjacentTile (tileX, tileY)
123{
124 const local = view.entities.get(view.localEntityId);
125 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
126 {
127 approachMove = null;
128 return true;
129 }
130 let bestWalkable = null;
131 let bestWalkableDist = Infinity;
132 let bestAny = null;
133 let bestAnyDist = Infinity;
134 for (let dy = -1; dy <= 1; dy++)
135 {
136 for (let dx = -1; dx <= 1; dx++)
137 {
138 if (dx === 0 && dy === 0)
139 { continue; }
140 const destX = tileX + dx;
141 const destY = tileY + dy;
142 const dist = local
143 ? chebyshev(local.tileX, local.tileY, destX, destY)
144 : 0;
145 if (dist < bestAnyDist)
146 {
147 bestAnyDist = dist;
148 bestAny = { tileX: destX, tileY: destY };
149 }
150 if (isClientApproachable(destX, destY) && dist < bestWalkableDist)
151 {
152 bestWalkableDist = dist;
153 bestWalkable = { tileX: destX, tileY: destY };
154 }
155 }
156 }
157 const best = bestWalkable ?? bestAny;
158 if (!best)
159 { return false; }
160 if (
161 approachMove
162 && approachMove.focusX === tileX
163 && approachMove.focusY === tileY
164 && approachMove.destX === best.tileX
165 && approachMove.destY === best.tileY
166 )
167 { return false; }
168 approachMove = {
169 focusX: tileX,
170 focusY: tileY,
171 destX: best.tileX,
172 destY: best.tileY
173 };
174 socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY });
175 return false;
176}
177
178function requestOpenBank (tileX, tileY, { getCheques = false } = {})
179{
180 clearAllPendingActions();
181 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
182 const local = view?.entities.get(view.localEntityId);
183 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
184 { flushPendingInteract(); }
185 else
186 { approachAdjacentTile(tileX, tileY); }
187}
188
189function requestOpenMarket (tileX, tileY)
190{
191 clearAllPendingActions();
192 pendingInteract = { kind: "market", tileX, tileY };
193 const local = view?.entities.get(view.localEntityId);
194 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
195 { flushPendingInteract(); }
196 else
197 { approachAdjacentTile(tileX, tileY); }
198}
199
200function requestOpenCauldron (tileX, tileY)
201{
202 clearAllPendingActions();
203 pendingInteract = { kind: "cauldron", tileX, tileY };
204 const local = view?.entities.get(view.localEntityId);
205 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
206 { flushPendingInteract(); }
207 else
208 { approachAdjacentTile(tileX, tileY); }
209}
210
211function requestOpenFurnace (tileX, tileY)
212{
213 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
214}
215
216function requestOpenCraftStation (stationId, tileX, tileY)
217{
218 clearAllPendingActions();
219 pendingInteract = { kind: "station", stationId, tileX, tileY };
220 const local = view?.entities.get(view.localEntityId);
221 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
222 { flushPendingInteract(); }
223 else
224 { approachAdjacentTile(tileX, tileY); }
225}
226
227function requestMine (tileX, tileY)
228{
229 clearAllPendingActions();
230 pendingInteract = { kind: "mine", tileX, tileY };
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 requestChop (tileX, tileY)
239{
240 clearAllPendingActions();
241 pendingInteract = { kind: "chop", 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 requestTalk (targetEntityId)
250{
251 clearAllPendingActions();
252 pendingInteract = { kind: "talk", targetEntityId };
253 const target = view?.entities.get(targetEntityId);
254 if (!target)
255 {
256 clearPendingInteract();
257 return;
258 }
259 if (approachAdjacentTile(target.tileX, target.tileY))
260 { flushPendingInteract(); }
261}
262
263function flushPendingInteract ()
264{
265 if (!pendingInteract || !view)
266 { return; }
267 const local = view.entities.get(view.localEntityId);
268 if (!local)
269 { return; }
270
271 if (pendingInteract.kind === "bank")
272 {
273 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
274 { return; }
275 const getCheques = !!pendingInteract.getCheques;
276 socket.send({ type: MessageType.openBank });
277 if (getCheques)
278 { inventory?.getBlankCheques(); }
279 clearPendingInteract();
280 return;
281 }
282
283 if (pendingInteract.kind === "market")
284 {
285 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
286 { return; }
287 socket.send({ type: MessageType.openMarket });
288 clearPendingInteract();
289 return;
290 }
291
292 if (pendingInteract.kind === "cauldron")
293 {
294 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
295 { return; }
296 socket.send({ type: MessageType.openCauldron });
297 clearPendingInteract();
298 return;
299 }
300
301 if (pendingInteract.kind === "station")
302 {
303 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
304 { return; }
305 socket.send({
306 type: MessageType.openStation,
307 stationId: pendingInteract.stationId
308 });
309 clearPendingInteract();
310 return;
311 }
312
313 if (pendingInteract.kind === "mine")
314 {
315 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
316 { return; }
317 socket.send({
318 type: MessageType.mine,
319 tileX: pendingInteract.tileX,
320 tileY: pendingInteract.tileY
321 });
322 clearPendingInteract();
323 return;
324 }
325
326 if (pendingInteract.kind === "chop")
327 {
328 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
329 { return; }
330 socket.send({
331 type: MessageType.chop,
332 tileX: pendingInteract.tileX,
333 tileY: pendingInteract.tileY
334 });
335 clearPendingInteract();
336 return;
337 }
338
339 if (pendingInteract.kind === "talk")
340 {
341 const target = view.entities.get(pendingInteract.targetEntityId);
342 if (!target)
343 {
344 clearPendingInteract();
345 return;
346 }
347 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
348 {
349 // Target may have moved — keep chasing.
350 approachAdjacentTile(target.tileX, target.tileY);
351 return;
352 }
353 socket.send({ type: MessageType.interact, targetEntityId: pendingInteract.targetEntityId });
354 clearPendingInteract();
355 }
356}
357
358function requestPickup (ground)
359{
360 if (!ground)
361 { return; }
362 clearPendingInteract();
363 pendingPickup = {
364 groundItemId: ground.groundItemId,
365 tileX: ground.tileX,
366 tileY: ground.tileY
367 };
368 const local = view.entities.get(view.localEntityId);
369 if (local && local.tileX === ground.tileX && local.tileY === ground.tileY)
370 {
371 flushPendingPickup();
372 return;
373 }
374 socket.send({ type: MessageType.moveTo, tileX: ground.tileX, tileY: ground.tileY });
375}
376
377function flushPendingPickup ()
378{
379 if (!pendingPickup || !view)
380 { return; }
381 const item = view.groundItems.get(pendingPickup.groundItemId);
382 if (!item)
383 {
384 clearPendingPickup();
385 return;
386 }
387 const local = view.entities.get(view.localEntityId);
388 if (!local)
389 { return; }
390 if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY)
391 { return; }
392 socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId });
393 clearPendingPickup();
394}
395
396function requestAttack (targetEntityId)
397{
398 clearAllPendingActions();
399 socket.send({ type: MessageType.attack, targetEntityId });
400}
401
402function isAttackableEntity (entity)
403{
404 if (!entity || entity.untargetable)
405 { return false; }
406 if (entity.canFight)
407 { return true; }
408 // Snapshots can omit canFight; mobs are still attackable via LMB.
409 return !!entity.mobTypeId && !entity.talkable;
410}
411
412function handleLeftClick (mouseX, mouseY)
413{
414 const entity = view.entityAtScreen(mouseX, mouseY);
415 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
416 {
417 clearPendingPickup();
418 if (entity.characterId)
419 {
420 clearPendingInteract();
421 social.inspect(entity);
422 return;
423 }
424 if (entity.talkable)
425 {
426 requestTalk(entity.entityId);
427 return;
428 }
429 if (isAttackableEntity(entity))
430 {
431 requestAttack(entity.entityId);
432 return;
433 }
434 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
435 return;
436 }
437
438 const tile = view.screenToTile(mouseX, mouseY);
439 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
440 if (ground)
441 { requestPickup(ground); }
442 else if (isBankTile(view, tile.tileX, tile.tileY))
443 { requestOpenBank(tile.tileX, tile.tileY); }
444 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
445 { requestOpenMarket(tile.tileX, tile.tileY); }
446 else if (isCauldronTile(view, tile.tileX, tile.tileY))
447 { requestOpenCauldron(tile.tileX, tile.tileY); }
448 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
449 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
450 else if (isAnvilTile(view, tile.tileX, tile.tileY))
451 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
452 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
453 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
454 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
455 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
456 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
457 { requestMine(tile.tileX, tile.tileY); }
458 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
459 { requestChop(tile.tileX, tile.tileY); }
460 else
461 {
462 clearAllPendingActions();
463 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
464 }
465}
466
467function handleRightClick (event, mouseX, mouseY)
468{
469 event.preventDefault();
470 const tile = view.screenToTile(mouseX, mouseY);
471 const items = [];
472 const walkTileX = tile.tileX;
473 const walkTileY = tile.tileY;
474
475 items.push({
476 label: "Walk here",
477 onSelect: () =>
478 {
479 clearAllPendingActions();
480 socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY });
481 }
482 });
483
484 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY))
485 {
486 if (entity.entityId === view.localEntityId)
487 { continue; }
488 const targetName = entityLabel(entity);
489 items.push({
490 label: `Follow ${targetName}`,
491 onSelect: () =>
492 {
493 clearAllPendingActions();
494 socket.send({ type: MessageType.follow, targetEntityId: entity.entityId });
495 }
496 });
497 if (entity.untargetable)
498 { continue; }
499 if (entity.hasShop)
500 {
501 items.push({
502 label: `Shop ${targetName}`,
503 onSelect: () => requestTalk(entity.entityId)
504 });
505 }
506 else if (entity.talkable)
507 {
508 items.push({
509 label: `Talk to ${targetName}`,
510 onSelect: () => requestTalk(entity.entityId)
511 });
512 }
513 if (entity.characterId)
514 {
515 items.push({
516 label: `${targetName} info`,
517 onSelect: () =>
518 {
519 clearAllPendingActions();
520 social.inspect(entity);
521 }
522 });
523 }
524 items.push({
525 label: `Attack ${targetName}`,
526 onSelect: () => requestAttack(entity.entityId)
527 });
528 }
529
530 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
531 {
532 const name = groundLabel(ground);
533 items.push({
534 label: `Pick up ${name}`,
535 onSelect: () => requestPickup(ground)
536 });
537 }
538
539 if (isBankTile(view, tile.tileX, tile.tileY))
540 {
541 items.push({
542 label: "Bank",
543 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
544 });
545 items.push({
546 label: "Get Blank Cheques",
547 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
548 });
549 }
550
551 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
552 {
553 items.push({
554 label: "Central Exchange",
555 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
556 });
557 }
558
559 if (isCauldronTile(view, tile.tileX, tile.tileY))
560 {
561 items.push({
562 label: "Alchemy",
563 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
564 });
565 }
566
567 if (isFurnaceTile(view, tile.tileX, tile.tileY))
568 {
569 items.push({
570 label: "Smelt",
571 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
572 });
573 }
574
575 if (isAnvilTile(view, tile.tileX, tile.tileY))
576 {
577 items.push({
578 label: "Smith",
579 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
580 });
581 }
582
583 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
584 {
585 items.push({
586 label: "Woodwork",
587 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
588 });
589 }
590
591 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
592 {
593 items.push({
594 label: "Craft",
595 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
596 });
597 }
598
599 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
600 {
601 items.push({
602 label: "Mine",
603 onSelect: () => requestMine(tile.tileX, tile.tileY)
604 });
605 }
606
607 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
608 {
609 items.push({
610 label: "Chop",
611 onSelect: () => requestChop(tile.tileX, tile.tileY)
612 });
613 }
614
615 contextMenu.show(event.clientX, event.clientY, items);
616}
617
618function entityLabel (entity)
619{
620 const first = (entity?.firstName ?? "").trim();
621 const last = (entity?.lastName ?? "").trim();
622 if (first && last)
623 { return `${first} ${last}`; }
624 return first || "target";
625}
626
627function groundLabel (ground)
628{
629 const name = (ground?.displayName ?? "").trim() || "item";
630 const qty = ground?.quantity ?? 1;
631 if (qty <= 1)
632 { return name; }
633 return `${name} (${formatQuantity(qty)})`;
634}
635
636function startPlay (payload)
637{
638 playing = true;
639 overlay.hidden = true;
640 hud.hidden = false;
641 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
642 gait = payload.gait ?? GAIT.walk;
643 document.getElementById("gait").textContent = gait;
644 staminaUi?.show();
645 if (payload.stamina != null)
646 { staminaUi?.apply(payload.stamina); }
647 if (!scene)
648 {
649 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
650 game.loadScene(scene);
651 useNearestNeighbour(scene, game.images);
652 view = new WorldView(game, scene, catalog);
653 const ticker = new GameObject(0, 0, null, 10);
654 ticker.update = (dt) =>
655 {
656 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
657 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
658 if (!leftPressed && !leftHeld)
659 { leftClickConsumed = false; }
660 else if (!leftClickConsumed && playing && !uiBlocked())
661 {
662 leftClickConsumed = true;
663 const canvas = scene.canvas;
664 const rect = canvas.getBoundingClientRect();
665 const mouseX = GameInput.mousePosition.x - rect.left;
666 const mouseY = GameInput.mousePosition.y - rect.top;
667 handleLeftClick(mouseX, mouseY);
668 }
669 if (GameInput.isPressed(82) && !uiBlocked())
670 {
671 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
672 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
673 { return; }
674 socket.send({ type: MessageType.setGait, gait: next });
675 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
676 if (next === GAIT.walk)
677 {
678 gait = next;
679 document.getElementById("gait").textContent = gait;
680 }
681 }
682 if (playing && !death?.isBlocking())
683 {
684 flushPendingPickup();
685 flushPendingInteract();
686 social?.updateNametag(view, scene, view.localEntityId);
687 chat?.update(view, scene);
688 updateWorldTooltip();
689 }
690 else
691 { hideWorldTooltip(); }
692 view.update(dt);
693 };
694 scene.addObject(ticker);
695 window.addEventListener("resize", () =>
696 {
697 scene.size.x = window.innerWidth;
698 scene.size.y = window.innerHeight;
699 scene.g_fixSize();
700 useNearestNeighbour(scene, game.images);
701 });
702 window.addEventListener("wheel", (event) =>
703 {
704 if (!playing || uiBlocked())
705 { return; }
706 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
707 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
708 }, { passive: true });
709 scene.canvas.addEventListener("contextmenu", (event) =>
710 {
711 if (!playing || uiBlocked())
712 { return; }
713 const rect = scene.canvas.getBoundingClientRect();
714 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
715 });
716 }
717 view.setSettings(payload.settings ?? view.settings);
718 chat?.syncSettings();
719 view.worldHour = payload.worldTime?.hour ?? 12;
720 view.setWorldSeason(payload.worldTime?.season);
721 view.setLocalEntity(
722 payload.entityId,
723 payload.tileX,
724 payload.tileY,
725 payload.gait,
726 payload.sex,
727 payload.firstName,
728 payload.lastName,
729 payload.characterId,
730 payload.layers
731 );
732}
733
734async function main ()
735{
736 catalog = await loadSpriteCatalog();
737 await preloadCatalogImages(game, catalog);
738 applySpriteSheets(game.images, catalog);
739 social = initSocial({
740 socket: { send (payload) { socket.send(payload); } },
741 MessageType
742 });
743 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
744 inventory = initInventory({
745 socket: { send (payload) { socket.send(payload); } },
746 MessageType,
747 contextMenu,
748 resolveSpriteUrl (name)
749 {
750 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
751 },
752 getFriends ()
753 {
754 return social?.getFriends?.() ?? [];
755 },
756 getLocalName ()
757 {
758 const you = document.getElementById("you")?.textContent ?? "";
759 return you.split("(")[0].trim() || "Unknown";
760 }
761 });
762 skills = initSkills();
763 crafting = initCrafting({
764 socket: { send (payload) { socket.send(payload); } },
765 MessageType,
766 getInventorySlots ()
767 {
768 return inventory?.getInventorySlots?.() ?? [];
769 },
770 getSkillLevel (skillId)
771 {
772 return skills?.skillLevel?.(skillId) ?? 1;
773 }
774 });
775 alchemy = initAlchemy({
776 socket: { send (payload) { socket.send(payload); } },
777 MessageType,
778 getInventorySlots ()
779 {
780 return inventory?.getInventorySlots?.() ?? [];
781 }
782 });
783 staminaUi = initStamina();
784 toasts = initToasts();
785 shop = initShop({
786 socket: { send (payload) { socket.send(payload); } },
787 MessageType,
788 onSuppressWorldClick: consumeWorldClick,
789 getCoinCount ()
790 {
791 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
792 },
793 getInventorySlots ()
794 {
795 return inventory?.getInventorySlots?.() ?? [];
796 }
797 });
798 market = initMarket({
799 socket: { send (payload) { socket.send(payload); } },
800 MessageType,
801 onSuppressWorldClick: consumeWorldClick,
802 getCoinCount ()
803 {
804 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
805 },
806 getInventorySlots ()
807 {
808 return inventory?.getInventorySlots?.() ?? [];
809 }
810 });
811 chat = initChat({
812 socket: { send (payload) { socket.send(payload); } },
813 MessageType,
814 getSettings: () => view?.settings
815 });
816 death = initDeath({
817 socket: { send (payload) { socket.send(payload); } },
818 MessageType
819 });
820 game.startGame();
821
822 socket = new GameSocket(defaultSocketUrl(), (message) =>
823 {
824 switch (message.type)
825 {
826 case MessageType.session:
827 session = message;
828 statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`;
829 renderCharacters(message.characters);
830 break;
831 case MessageType.characterList:
832 renderCharacters(message.characters);
833 if (!playing)
834 { overlay.hidden = false; }
835 break;
836 case MessageType.enterWorld:
837 startPlay(message);
838 inventory?.setLocalCharacterId(message.characterId);
839 break;
840 case MessageType.chunkSnapshot:
841 view?.applySnapshot(message);
842 break;
843 case MessageType.chunkDelta:
844 for (const tile of message.tiles ?? [])
845 {
846 view?.updateAuthoredTile(
847 message.chunkX,
848 message.chunkY,
849 tile.localX,
850 tile.localY,
851 { ground: tile.ground, block: tile.block, light: tile.light }
852 );
853 }
854 break;
855 case MessageType.unsubscribeChunk:
856 view?.removeChunk(message.chunkX, message.chunkY);
857 break;
858 case MessageType.entitySpawn:
859 view?.spawnEntity(message);
860 break;
861 case MessageType.entityMove:
862 view?.moveEntity(message);
863 if (message.entityId === view?.localEntityId && message.gait)
864 {
865 gait = message.gait;
866 document.getElementById("gait").textContent = gait;
867 }
868 break;
869 case MessageType.entityDespawn:
870 view?.despawnEntity(message.entityId);
871 break;
872 case MessageType.entityAppearance:
873 view?.setAppearance(message);
874 break;
875 case MessageType.groundItemAppear:
876 view?.upsertGroundItem(message);
877 break;
878 case MessageType.groundItemDespawn:
879 view?.despawnGroundItem(message.groundItemId);
880 break;
881 case MessageType.inventory:
882 inventory?.handleInventory(message);
883 crafting?.refresh();
884 alchemy?.refresh();
885 shop?.refresh();
886 market?.refresh();
887 break;
888 case MessageType.skills:
889 skills?.render(message.skills);
890 crafting?.refresh();
891 break;
892 case MessageType.stamina:
893 staminaUi?.apply(message);
894 if (message.gait)
895 {
896 gait = message.gait;
897 document.getElementById("gait").textContent = gait;
898 }
899 break;
900 case MessageType.bankSnapshot:
901 inventory?.handleBank(message);
902 break;
903 case MessageType.cauldronSnapshot:
904 alchemy?.handleSnapshot(message);
905 break;
906 case MessageType.pigeonDispatched:
907 inventory?.handlePigeonDispatched(message);
908 break;
909 case MessageType.pigeonDelivered:
910 inventory?.handlePigeonDelivered(message);
911 break;
912 case MessageType.characterSearchResult:
913 inventory?.handleCharacterSearch(message);
914 break;
915 case MessageType.craftResult:
916 crafting?.handleCraftResult(message);
917 break;
918 case MessageType.worldStatus:
919 if (view)
920 {
921 view.setSettings(message.settings ?? view.settings);
922 view.worldHour = message.worldTime?.hour ?? view.worldHour;
923 view.setWorldSeason(message.worldTime?.season);
924 chat?.syncSettings();
925 }
926 break;
927 case MessageType.chatBubble:
928 chat?.showBubble(message);
929 break;
930 case MessageType.friends:
931 social?.handleFriends(message);
932 break;
933 case MessageType.combatSwing:
934 view?.spawnCombatSwing(message);
935 break;
936 case MessageType.gatherSwing:
937 case MessageType.tileShove:
938 view?.spawnGatherSwing(message);
939 break;
940 case MessageType.stationOpen:
941 if (message.stationId)
942 { crafting?.openStation(message.stationId); }
943 break;
944 case MessageType.shopOpen:
945 shop?.handleShopOpen(message);
946 break;
947 case MessageType.shopClosed:
948 shop?.handleShopClosed(message);
949 break;
950 case MessageType.marketOpen:
951 market?.handleOpen(message);
952 break;
953 case MessageType.marketClosed:
954 market?.handleClosed(message);
955 break;
956 case MessageType.marketTrade:
957 market?.handleTrade(message);
958 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
959 break;
960 case MessageType.itemBubble:
961 chat?.showItemBubble(message);
962 break;
963 case MessageType.gatherComplete:
964 crafting?.refresh();
965 break;
966 case MessageType.combatHit:
967 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
968 view?.flashDamage(message.targetId);
969 view?.spawnDamageNumber(message.targetId, message.damage);
970 break;
971 case MessageType.skillLevelUp:
972 view?.spawnSkillLevelUp(message.entityId, message);
973 if (message.entityId === view?.localEntityId)
974 {
975 const name = message.displayName ?? message.skillId ?? "Skill";
976 toasts?.show(`${name} level ${message.level}!`);
977 }
978 break;
979 case MessageType.playerDied:
980 clearAllPendingActions();
981 contextMenu?.hide();
982 death?.show();
983 break;
984 case MessageType.playerRespawned:
985 death?.hide();
986 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
987 if (message.stamina != null || message.maxStamina != null)
988 {
989 staminaUi?.apply({
990 current: message.stamina ?? staminaUi.getCurrent?.(),
991 max: message.maxStamina ?? staminaUi.getMax?.()
992 });
993 }
994 break;
995 case MessageType.error:
996 if (playing)
997 { toasts?.show(message.message); }
998 else
999 { showError(message.message); }
1000 social?.showError(message.message);
1001 break;
1002 case MessageType.toast:
1003 if (playing)
1004 { toasts?.show(message.message); }
1005 break;
1006 case MessageType.forceLogout:
1007 returnToMenu(message.reason);
1008 break;
1009 }
1010 }, {
1011 onClose (event)
1012 {
1013 if (playing)
1014 { returnToMenu(event.reason || "Disconnected from server."); }
1015 }
1016 });
1017 await socket.connect();
1018 if (typeof window !== "undefined")
1019 {
1020 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
1021 {
1022 crafting?.openStation(stationId);
1023 };
1024 }
1025}
1026
1027function returnToMenu (reason = "")
1028{
1029 playing = false;
1030 clearAllPendingActions();
1031 social?.reset();
1032 chat?.reset();
1033 inventory?.reset();
1034 crafting?.reset();
1035 alchemy?.reset();
1036 staminaUi?.hide();
1037 skills?.hide();
1038 contextMenu?.hide();
1039 death?.reset();
1040 shop?.close({ notifyServer: false });
1041 hideWorldTooltip();
1042 if (view)
1043 {
1044 for (const key of [...(view.chunks?.keys?.() ?? [])])
1045 {
1046 const [chunkX, chunkY] = key.split(",").map(Number);
1047 view.removeChunk(chunkX, chunkY);
1048 }
1049 }
1050 overlay.hidden = false;
1051 hud.hidden = true;
1052 if (reason)
1053 { statusEl.textContent = reason; }
1054}
1055
1056document.getElementById("create-form").addEventListener("submit", (event) =>
1057{
1058 event.preventDefault();
1059 showError("");
1060 socket.send({
1061 type: MessageType.createCharacter,
1062 firstName: document.getElementById("first-name").value,
1063 lastName: document.getElementById("last-name").value,
1064 sex: document.getElementById("sex").value
1065 });
1066});
1067
1068document.getElementById("leave").addEventListener("click", () =>
1069{
1070 socket.send({ type: MessageType.leaveWorld });
1071 returnToMenu();
1072});
1073
1074main().catch((error) =>
1075{
1076 showError(error.message);
1077 console.error(error);
1078});
1079
1080function isBankTile (view, tileX, tileY)
1081{
1082 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
1083}
1084
1085function isMarketplaceTile (view, tileX, tileY)
1086{
1087 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1088}
1089
1090function isCauldronTile (view, tileX, tileY)
1091{
1092 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
1093}
1094
1095function isFurnaceTile (view, tileX, tileY)
1096{
1097 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
1098}
1099
1100function isAnvilTile (view, tileX, tileY)
1101{
1102 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
1103}
1104
1105function isWoodworkingBenchTile (view, tileX, tileY)
1106{
1107 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
1108}
1109
1110function isCraftingBenchTile (view, tileX, tileY)
1111{
1112 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1113}
1114
1115function isOreBoulderTile (view, tileX, tileY)
1116{
1117 const block = blockAt(view, tileX, tileY);
1118 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
1119}
1120
1121function isChopableTreeTile (view, tileX, tileY)
1122{
1123 return isChopableTreeBlock(blockAt(view, tileX, tileY));
1124}
1125
1126function hideWorldTooltip ()
1127{
1128 if (worldTooltip)
1129 { worldTooltip.hidden = true; }
1130}
1131
1132/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
1133function updateWorldTooltip ()
1134{
1135 if (!worldTooltip || !view || !scene || uiBlocked())
1136 {
1137 hideWorldTooltip();
1138 return;
1139 }
1140 const canvas = scene.canvas;
1141 const rect = canvas.getBoundingClientRect();
1142 const mouseX = GameInput.mousePosition.x - rect.left;
1143 const mouseY = GameInput.mousePosition.y - rect.top;
1144 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1145 {
1146 hideWorldTooltip();
1147 return;
1148 }
1149 const entity = view.entityAtScreen(mouseX, mouseY);
1150 if (entity && entity.entityId !== view.localEntityId)
1151 {
1152 hideWorldTooltip();
1153 return;
1154 }
1155 const tile = view.screenToTile(mouseX, mouseY);
1156 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
1157 if (!label)
1158 {
1159 hideWorldTooltip();
1160 return;
1161 }
1162 worldTooltip.hidden = false;
1163 worldTooltip.textContent = label;
1164 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
1165 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
1166}
1167
1168function blockTypeAt (view, tileX, tileY)
1169{
1170 return blockAt(view, tileX, tileY)?.typeId ?? null;
1171}
1172
1173function blockAt (view, tileX, tileY)
1174{
1175 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1176 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1177 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1178 if (!snapshot)
1179 { return null; }
1180 const localX = tileX - chunkX * CHUNK_SIZE;
1181 const localY = tileY - chunkY * CHUNK_SIZE;
1182 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
1183}
1184
1185function groundTypeAt (view, tileX, tileY)
1186{
1187 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1188 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1189 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1190 if (!snapshot)
1191 { return null; }
1192 const localX = tileX - chunkX * CHUNK_SIZE;
1193 const localY = tileY - chunkY * CHUNK_SIZE;
1194 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
1195}
1196
1197/** Best-effort client filter for approach destinations (server still authorizes paths). */
1198function isClientApproachable (tileX, tileY)
1199{
1200 if (!view)
1201 { return true; }
1202 const groundId = groundTypeAt(view, tileX, tileY);
1203 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
1204 if (groundDef && !groundDef.passable)
1205 { return false; }
1206 const block = blockAt(view, tileX, tileY);
1207 if (block?.typeId != null)
1208 {
1209 const blockDef = BLOCK_DEFINITIONS[block.typeId];
1210 if (blockDef && !blockDef.passable)
1211 { return false; }
1212 }
1213 for (const entity of view.entitiesAtTile(tileX, tileY))
1214 {
1215 if (entity.entityId === view.localEntityId)
1216 { continue; }
1217 if (entity.untargetable || entity.freeFlight)
1218 { continue; }
1219 return false;
1220 }
1221 return true;
1222}
1223
1224function chebyshev (ax, ay, bx, by)
1225{
1226 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
1227}