BlueGit

timfa questward

Merge branch 'feature/dimension-interactions-fix'

timfa Tim Falken · pushed by timfa

Authored 2026-09-07 · 2 months ago

Hash
34c7d1942dcdb656e936bf179db23215aa4a725d
27 files changed +1069 −222
client/editor.html +1 −0
@@ -17,6 +17,7 @@
17 17 <p id="error" class="error"></p>
18 18 </div>
19 19 <button id="editor-restart-now" type="button" hidden title="Graceful shutdown; systemd restarts the server">Restart now</button>
20 <a id="editor-to-play" class="editor-to-play" href="/">Play</a>
20 21 </header>
21 22 <aside>
22 23 <p>Chunk <strong id="coords">0, 0</strong></p>
@@ -17,6 +17,7 @@
17 <p id="error" class="error"></p>
17 <p id="error" class="error"></p>
18 </div>
18 </div>
19 <button id="editor-restart-now" type="button" hidden title="Graceful shutdown; systemd restarts the server">Restart now</button>
19 <button id="editor-restart-now" type="button" hidden title="Graceful shutdown; systemd restarts the server">Restart now</button>
20 <a id="editor-to-play" class="editor-to-play" href="/">Play</a>
20 </header>
21 </header>
21 <aside>
22 <aside>
22 <p>Chunk <strong id="coords">0, 0</strong></p>
23 <p>Chunk <strong id="coords">0, 0</strong></p>
client/src/play/main.js +39 −0
@@ -544,6 +544,17 @@ function requestOpenCauldron (tileX, tileY)
544 544 { approachAdjacentTile(tileX, tileY); }
545 545 }
546 546
547 function requestPrayAtAltar (tileX, tileY)
548 {
549 clearAllPendingActions();
550 pendingInteract = { kind: "pray-altar", tileX, tileY };
551 const local = view?.entities.get(view.localEntityId);
552 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
553 { flushPendingInteract(); }
554 else
555 { approachAdjacentTile(tileX, tileY); }
556 }
557
547 558 function requestOpenFurnace (tileX, tileY)
548 559 {
549 560 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
@@ -892,6 +903,19 @@ function flushPendingInteract ()
892 903 return;
893 904 }
894 905
906 if (pendingInteract.kind === "pray-altar")
907 {
908 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
909 { return; }
910 socket.send({
911 type: MessageType.prayAtAltar,
912 tileX: pendingInteract.tileX,
913 tileY: pendingInteract.tileY
914 });
915 clearPendingInteract();
916 return;
917 }
918
895 919 if (pendingInteract.kind === "station")
896 920 {
897 921 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
@@ -1226,6 +1250,8 @@ function handleLeftClick (mouseX, mouseY)
1226 1250 { requestOpenBarber(tile.tileX, tile.tileY); }
1227 1251 else if (isCauldronTile(view, tile.tileX, tile.tileY))
1228 1252 { requestOpenCauldron(tile.tileX, tile.tileY); }
1253 else if (isChurchAltarTile(view, tile.tileX, tile.tileY))
1254 { requestPrayAtAltar(tile.tileX, tile.tileY); }
1229 1255 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
1230 1256 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
1231 1257 else if (isOvenTile(view, tile.tileX, tile.tileY))
@@ -1465,6 +1491,14 @@ function handleRightClick (event, mouseX, mouseY)
1465 1491 });
1466 1492 }
1467 1493
1494 if (isChurchAltarTile(view, tile.tileX, tile.tileY))
1495 {
1496 items.push({
1497 label: "Pray",
1498 onSelect: () => requestPrayAtAltar(tile.tileX, tile.tileY)
1499 });
1500 }
1501
1468 1502 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1469 1503 {
1470 1504 items.push({
@@ -2757,6 +2791,11 @@ function isCauldronTile (view, tileX, tileY)
2757 2791 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2758 2792 }
2759 2793
2794 function isChurchAltarTile (view, tileX, tileY)
2795 {
2796 return blockTypeAt(view, tileX, tileY) === BlockType.churchAltar;
2797 }
2798
2760 2799 function isFurnaceTile (view, tileX, tileY)
2761 2800 {
2762 2801 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
@@ -544,6 +544,17 @@ function requestOpenCauldron (tileX, tileY)
544 { approachAdjacentTile(tileX, tileY); }
544 { approachAdjacentTile(tileX, tileY); }
545}
545}
546
546
547function requestPrayAtAltar (tileX, tileY)
548{
549 clearAllPendingActions();
550 pendingInteract = { kind: "pray-altar", tileX, tileY };
551 const local = view?.entities.get(view.localEntityId);
552 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
553 { flushPendingInteract(); }
554 else
555 { approachAdjacentTile(tileX, tileY); }
556}
557
547function requestOpenFurnace (tileX, tileY)
558function requestOpenFurnace (tileX, tileY)
548{
559{
549 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
560 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
@@ -892,6 +903,19 @@ function flushPendingInteract ()
892 return;
903 return;
893 }
904 }
894
905
906 if (pendingInteract.kind === "pray-altar")
907 {
908 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
909 { return; }
910 socket.send({
911 type: MessageType.prayAtAltar,
912 tileX: pendingInteract.tileX,
913 tileY: pendingInteract.tileY
914 });
915 clearPendingInteract();
916 return;
917 }
918
895 if (pendingInteract.kind === "station")
919 if (pendingInteract.kind === "station")
896 {
920 {
897 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
921 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
@@ -1226,6 +1250,8 @@ function handleLeftClick (mouseX, mouseY)
1226 { requestOpenBarber(tile.tileX, tile.tileY); }
1250 { requestOpenBarber(tile.tileX, tile.tileY); }
1227 else if (isCauldronTile(view, tile.tileX, tile.tileY))
1251 else if (isCauldronTile(view, tile.tileX, tile.tileY))
1228 { requestOpenCauldron(tile.tileX, tile.tileY); }
1252 { requestOpenCauldron(tile.tileX, tile.tileY); }
1253 else if (isChurchAltarTile(view, tile.tileX, tile.tileY))
1254 { requestPrayAtAltar(tile.tileX, tile.tileY); }
1229 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
1255 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
1230 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
1256 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
1231 else if (isOvenTile(view, tile.tileX, tile.tileY))
1257 else if (isOvenTile(view, tile.tileX, tile.tileY))
@@ -1465,6 +1491,14 @@ function handleRightClick (event, mouseX, mouseY)
1465 });
1491 });
1466 }
1492 }
1467
1493
1494 if (isChurchAltarTile(view, tile.tileX, tile.tileY))
1495 {
1496 items.push({
1497 label: "Pray",
1498 onSelect: () => requestPrayAtAltar(tile.tileX, tile.tileY)
1499 });
1500 }
1501
1468 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1502 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1469 {
1503 {
1470 items.push({
1504 items.push({
@@ -2757,6 +2791,11 @@ function isCauldronTile (view, tileX, tileY)
2757 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2791 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2758}
2792}
2759
2793
2794function isChurchAltarTile (view, tileX, tileY)
2795{
2796 return blockTypeAt(view, tileX, tileY) === BlockType.churchAltar;
2797}
2798
2760function isFurnaceTile (view, tileX, tileY)
2799function isFurnaceTile (view, tileX, tileY)
2761{
2800{
2762 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2801 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
client/ui/editor.css +17 −0
@@ -43,6 +43,23 @@ body>header {
43 43 white-space: nowrap;
44 44 }
45 45
46 .editor-to-play {
47 flex: 0 0 auto;
48 margin-top: 0.15rem;
49 padding: 0.35rem 0.65rem;
50 border: 1px solid #3a4250;
51 border-radius: 0.35rem;
52 background: #1a1f28;
53 color: #c8d0dc;
54 font: inherit;
55 text-decoration: none;
56 white-space: nowrap;
57 }
58
59 .editor-to-play:hover {
60 background: #243044;
61 }
62
46 63 #editor-restart-now:hover:not(:disabled) {
47 64 background: #3a2020;
48 65 }
@@ -43,6 +43,23 @@ body>header {
43 white-space: nowrap;
43 white-space: nowrap;
44}
44}
45
45
46.editor-to-play {
47 flex: 0 0 auto;
48 margin-top: 0.15rem;
49 padding: 0.35rem 0.65rem;
50 border: 1px solid #3a4250;
51 border-radius: 0.35rem;
52 background: #1a1f28;
53 color: #c8d0dc;
54 font: inherit;
55 text-decoration: none;
56 white-space: nowrap;
57}
58
59.editor-to-play:hover {
60 background: #243044;
61}
62
46#editor-restart-now:hover:not(:disabled) {
63#editor-restart-now:hover:not(:disabled) {
47 background: #3a2020;
64 background: #3a2020;
48}
65}
server/src/alchemy/service.js +6 −3
@@ -37,6 +37,7 @@ import {
37 37 } from "../../../shared/definitions/gathering.js";
38 38 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
39 39 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
40 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
40 41 import { randomUUID } from "node:crypto";
41 42 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
42 43
@@ -105,15 +106,16 @@ function sessionView (session)
105 106 };
106 107 }
107 108
108 function nearCauldron (world, tileX, tileY)
109 function nearCauldron (world, tileX, tileY, dimensionId = OVERWORLD_ID)
109 110 {
111 const dim = normalizeDimensionId(dimensionId);
110 112 for (let dy = -1; dy <= 1; dy++)
111 113 {
112 114 for (let dx = -1; dx <= 1; dx++)
113 115 {
114 116 if (dx === 0 && dy === 0)
115 117 { continue; }
116 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
118 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim);
117 119 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
118 120 if (data.blocks[index]?.typeId === BlockType.cauldron)
119 121 { return true; }
@@ -125,7 +127,8 @@ function nearCauldron (world, tileX, tileY)
125 127 function requireNearCauldron (world, handle)
126 128 {
127 129 const position = world.ecs.get(handle, Component.position);
128 if (!nearCauldron(world, position.tileX, position.tileY))
130 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
131 if (!nearCauldron(world, position.tileX, position.tileY, dim))
129 132 { throw userError("Stand next to a cauldron."); }
130 133 }
131 134
@@ -37,6 +37,7 @@ import {
37} from "../../../shared/definitions/gathering.js";
37} from "../../../shared/definitions/gathering.js";
38import { tileToChunk, tileToLocal } from "../world/coordinates.js";
38import { tileToChunk, tileToLocal } from "../world/coordinates.js";
39import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
39import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
40import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
40import { randomUUID } from "node:crypto";
41import { randomUUID } from "node:crypto";
41import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
42import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
42
43
@@ -105,15 +106,16 @@ function sessionView (session)
105 };
106 };
106}
107}
107
108
108function nearCauldron (world, tileX, tileY)
109function nearCauldron (world, tileX, tileY, dimensionId = OVERWORLD_ID)
109{
110{
111 const dim = normalizeDimensionId(dimensionId);
110 for (let dy = -1; dy <= 1; dy++)
112 for (let dy = -1; dy <= 1; dy++)
111 {
113 {
112 for (let dx = -1; dx <= 1; dx++)
114 for (let dx = -1; dx <= 1; dx++)
113 {
115 {
114 if (dx === 0 && dy === 0)
116 if (dx === 0 && dy === 0)
115 { continue; }
117 { continue; }
116 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
118 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim);
117 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
119 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
118 if (data.blocks[index]?.typeId === BlockType.cauldron)
120 if (data.blocks[index]?.typeId === BlockType.cauldron)
119 { return true; }
121 { return true; }
@@ -125,7 +127,8 @@ function nearCauldron (world, tileX, tileY)
125function requireNearCauldron (world, handle)
127function requireNearCauldron (world, handle)
126{
128{
127 const position = world.ecs.get(handle, Component.position);
129 const position = world.ecs.get(handle, Component.position);
128 if (!nearCauldron(world, position.tileX, position.tileY))
130 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
131 if (!nearCauldron(world, position.tileX, position.tileY, dim))
129 { throw userError("Stand next to a cauldron."); }
132 { throw userError("Stand next to a cauldron."); }
130}
133}
131
134
server/src/barber/service.js +9 −5
@@ -8,6 +8,7 @@ import {
8 8 } from "../../../shared/appearance/hair.js";
9 9 import { BlockType } from "../../../shared/definitions/tiles.js";
10 10 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
11 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
11 12 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
12 13
13 14 function userError (message)
@@ -102,34 +103,37 @@ export class BarberService
102 103 const position = entityId ? this.simulation.positionOf(entityId) : null;
103 104 if (!position)
104 105 { throw userError("Enter the world before visiting the barber."); }
105 if (!isAdjacentToBarber(this.simulation, position.tileX, position.tileY))
106 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
107 if (!isAdjacentToBarber(this.simulation, position.tileX, position.tileY, dim))
106 108 { throw userError("Stand next to a Barber."); }
107 109 return position;
108 110 }
109 111 }
110 112
111 function isAdjacentToBarber (simulation, tileX, tileY)
113 function isAdjacentToBarber (simulation, tileX, tileY, dimensionId = OVERWORLD_ID)
112 114 {
115 const dim = normalizeDimensionId(dimensionId);
113 116 for (let dy = -1; dy <= 1; dy++)
114 117 {
115 118 for (let dx = -1; dx <= 1; dx++)
116 119 {
117 120 if (dx === 0 && dy === 0)
118 121 { continue; }
119 if (blockTypeAt(simulation, tileX + dx, tileY + dy) === BlockType.barber)
122 if (blockTypeAt(simulation, tileX + dx, tileY + dy, dim) === BlockType.barber)
120 123 { return true; }
121 124 }
122 125 }
123 126 return false;
124 127 }
125 128
126 function blockTypeAt (simulation, tileX, tileY)
129 function blockTypeAt (simulation, tileX, tileY, dimensionId = OVERWORLD_ID)
127 130 {
131 const dim = normalizeDimensionId(dimensionId);
128 132 const chunkX = tileToChunk(tileX);
129 133 const chunkY = tileToChunk(tileY);
130 134 for (const worker of simulation.workers ?? [])
131 135 {
132 const data = worker.world?.chunkData?.(chunkX, chunkY);
136 const data = worker.world?.chunkData?.(chunkX, chunkY, dim);
133 137 if (!data?.blocks)
134 138 { continue; }
135 139 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
@@ -8,6 +8,7 @@ import {
8} from "../../../shared/appearance/hair.js";
8} from "../../../shared/appearance/hair.js";
9import { BlockType } from "../../../shared/definitions/tiles.js";
9import { BlockType } from "../../../shared/definitions/tiles.js";
10import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
10import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
11import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
11import { tileToChunk, tileToLocal } from "../world/coordinates.js";
12import { tileToChunk, tileToLocal } from "../world/coordinates.js";
12
13
13function userError (message)
14function userError (message)
@@ -102,34 +103,37 @@ export class BarberService
102 const position = entityId ? this.simulation.positionOf(entityId) : null;
103 const position = entityId ? this.simulation.positionOf(entityId) : null;
103 if (!position)
104 if (!position)
104 { throw userError("Enter the world before visiting the barber."); }
105 { throw userError("Enter the world before visiting the barber."); }
105 if (!isAdjacentToBarber(this.simulation, position.tileX, position.tileY))
106 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
107 if (!isAdjacentToBarber(this.simulation, position.tileX, position.tileY, dim))
106 { throw userError("Stand next to a Barber."); }
108 { throw userError("Stand next to a Barber."); }
107 return position;
109 return position;
108 }
110 }
109}
111}
110
112
111function isAdjacentToBarber (simulation, tileX, tileY)
113function isAdjacentToBarber (simulation, tileX, tileY, dimensionId = OVERWORLD_ID)
112{
114{
115 const dim = normalizeDimensionId(dimensionId);
113 for (let dy = -1; dy <= 1; dy++)
116 for (let dy = -1; dy <= 1; dy++)
114 {
117 {
115 for (let dx = -1; dx <= 1; dx++)
118 for (let dx = -1; dx <= 1; dx++)
116 {
119 {
117 if (dx === 0 && dy === 0)
120 if (dx === 0 && dy === 0)
118 { continue; }
121 { continue; }
119 if (blockTypeAt(simulation, tileX + dx, tileY + dy) === BlockType.barber)
122 if (blockTypeAt(simulation, tileX + dx, tileY + dy, dim) === BlockType.barber)
120 { return true; }
123 { return true; }
121 }
124 }
122 }
125 }
123 return false;
126 return false;
124}
127}
125
128
126function blockTypeAt (simulation, tileX, tileY)
129function blockTypeAt (simulation, tileX, tileY, dimensionId = OVERWORLD_ID)
127{
130{
131 const dim = normalizeDimensionId(dimensionId);
128 const chunkX = tileToChunk(tileX);
132 const chunkX = tileToChunk(tileX);
129 const chunkY = tileToChunk(tileY);
133 const chunkY = tileToChunk(tileY);
130 for (const worker of simulation.workers ?? [])
134 for (const worker of simulation.workers ?? [])
131 {
135 {
132 const data = worker.world?.chunkData?.(chunkX, chunkY);
136 const data = worker.world?.chunkData?.(chunkX, chunkY, dim);
133 if (!data?.blocks)
137 if (!data?.blocks)
134 { continue; }
138 { continue; }
135 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
139 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
server/src/bounty/service.js +4 −1
@@ -15,6 +15,7 @@ import {
15 15 takeCoinsFromSlots
16 16 } from "../../../shared/items/inventory.js";
17 17 import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
18 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
18 19
19 20 function userError (message)
20 21 {
@@ -342,8 +343,10 @@ export class BountyService
342 343 const tiles = this.courier?.bountyOfficeTiles ?? [];
343 344 if (!tiles.length)
344 345 { throw userError("No Bounty Office exists in this world yet."); }
346 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
345 347 const near = tiles.some((tile) =>
346 isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
348 normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim
349 && isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
347 350 if (!near)
348 351 { throw userError("Stand next to a Bounty Office."); }
349 352 return position;
@@ -15,6 +15,7 @@ import {
15 takeCoinsFromSlots
15 takeCoinsFromSlots
16} from "../../../shared/items/inventory.js";
16} from "../../../shared/items/inventory.js";
17import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
17import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
18import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
18
19
19function userError (message)
20function userError (message)
20{
21{
@@ -342,8 +343,10 @@ export class BountyService
342 const tiles = this.courier?.bountyOfficeTiles ?? [];
343 const tiles = this.courier?.bountyOfficeTiles ?? [];
343 if (!tiles.length)
344 if (!tiles.length)
344 { throw userError("No Bounty Office exists in this world yet."); }
345 { throw userError("No Bounty Office exists in this world yet."); }
346 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
345 const near = tiles.some((tile) =>
347 const near = tiles.some((tile) =>
346 isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
348 normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim
349 && isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
347 if (!near)
350 if (!near)
348 { throw userError("Stand next to a Bounty Office."); }
351 { throw userError("Stand next to a Bounty Office."); }
349 return position;
352 return position;
server/src/combat/service.js +78 −23
@@ -19,7 +19,7 @@ import {
19 19 } from "../../../shared/combat/combatLevel.js";
20 20 import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js";
21 21 import { skullAttractsTownGuards } from "../../../shared/combat/skull.js";
22 import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
22 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
23 23 import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js";
24 24 import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
25 25 import { mobDamageAffinities } from "../../../shared/combat/magic.js";
@@ -585,17 +585,19 @@ export function clearEngage (ecs, entityId)
585 585 }
586 586 }
587 587
588 export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
588 export function hasCombatLineOfSight (world, fromX, fromY, toX, toY, dimensionId = OVERWORLD_ID)
589 589 {
590 const dim = normalizeDimensionId(dimensionId);
590 591 const isClear = world.isClearForRangedAttack
591 ? (x, y) => world.isClearForRangedAttack(x, y)
592 : (x, y) => world.isEnterable(x, y);
592 ? (x, y) => world.isClearForRangedAttack(x, y, dim)
593 : (x, y) => world.isEnterable(x, y, dim);
593 594 return rayReaches(fromX, fromY, toX, toY, isClear);
594 595 }
595 596
596 function lightOcclusionAtWorld (world, x, y)
597 function lightOcclusionAtWorld (world, x, y, dimensionId = OVERWORLD_ID)
597 598 {
598 const data = world.chunkData?.(tileToChunk(x), tileToChunk(y));
599 const dim = normalizeDimensionId(dimensionId);
600 const data = world.chunkData?.(tileToChunk(x), tileToChunk(y), dim);
599 601 if (!data)
600 602 { return LightOcclusion.clear; }
601 603 const index = tileIndexLocal(x, y);
@@ -611,11 +613,12 @@ function lightOcclusionAtWorld (world, x, y)
611 613 * Block lights (torches, …) use live occlusion so passage-open doors let light through;
612 614 * entity/spell lights layer on top (same compositing as client inner 3×3).
613 615 */
614 export function tileLightAt (world, tileX, tileY, now = Date.now())
616 export function tileLightAt (world, tileX, tileY, now = Date.now(), dimensionId = OVERWORLD_ID)
615 617 {
616 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y);
618 const dim = normalizeDimensionId(dimensionId);
619 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y, dim);
617 620 const blockSources = blockLightSourcesNearTile(
618 (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY),
621 (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY, dim),
619 622 tileX,
620 623 tileY
621 624 );
@@ -833,7 +836,11 @@ export function stepAggression (world, now = Date.now())
833 836 {
834 837 for (const entity of world.ecs.query(Component.creature, Component.position))
835 838 {
836 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
839 if (!world.chunkIsSimulating?.(
840 entity.position.tileX,
841 entity.position.tileY,
842 entity.position.dimensionId ?? OVERWORLD_ID
843 ))
837 844 { continue; }
838 845 const def = mobDefinition(entity.creature.mobTypeId);
839 846 if (world.ecs.get(entity.handle, Component.summon))
@@ -1001,6 +1008,10 @@ function considerAggressionCandidate (world, attacker, targetHandle, targetEntit
1001 1008 const health = world.ecs.get(targetHandle, Component.health);
1002 1009 if (health && health.current <= 0)
1003 1010 { return null; }
1011 const attackerDim = normalizeDimensionId(attacker.position.dimensionId ?? OVERWORLD_ID);
1012 const targetDim = normalizeDimensionId(targetPos.dimensionId ?? OVERWORLD_ID);
1013 if (attackerDim !== targetDim)
1014 { return null; }
1004 1015 const dist = chebyshev(
1005 1016 attacker.position.tileX,
1006 1017 attacker.position.tileY,
@@ -1012,7 +1023,7 @@ function considerAggressionCandidate (world, attacker, targetHandle, targetEntit
1012 1023 let effectiveDist = dist;
1013 1024 if (dist > 1)
1014 1025 {
1015 const light = tileLightAt(world, targetPos.tileX, targetPos.tileY);
1026 const light = tileLightAt(world, targetPos.tileX, targetPos.tileY, Date.now(), attackerDim);
1016 1027 effectiveDist = dist * aggroDistanceMultiplier(light);
1017 1028 }
1018 1029 if (effectiveDist > range)
@@ -1022,7 +1033,8 @@ function considerAggressionCandidate (world, attacker, targetHandle, targetEntit
1022 1033 attacker.position.tileX,
1023 1034 attacker.position.tileY,
1024 1035 targetPos.tileX,
1025 targetPos.tileY
1036 targetPos.tileY,
1037 attackerDim
1026 1038 ))
1027 1039 { return null; }
1028 1040 return dist;
@@ -1055,7 +1067,11 @@ export function resolveCombatTarget (world, targetId)
1055 1067 return {
1056 1068 local: false,
1057 1069 handle: null,
1058 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
1070 pos: {
1071 tileX: ghost.tileX,
1072 tileY: ghost.tileY,
1073 dimensionId: normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID)
1074 },
1059 1075 health
1060 1076 };
1061 1077 }
@@ -1088,7 +1104,11 @@ export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20)
1088 1104 const { handle, entityId, health, position, character } = entity;
1089 1105 if (world.ecs.has(handle, Component.dead))
1090 1106 { continue; }
1091 if (!world.chunkIsSimulating?.(position.tileX, position.tileY))
1107 if (!world.chunkIsSimulating?.(
1108 position.tileX,
1109 position.tileY,
1110 position.dimensionId ?? OVERWORLD_ID
1111 ))
1092 1112 { continue; }
1093 1113 if ((health.current | 0) >= (health.max | 0))
1094 1114 { continue; }
@@ -1132,7 +1152,11 @@ export function stepCombat (world, now = Date.now())
1132 1152 dropCombatTarget(world, entity);
1133 1153 continue;
1134 1154 }
1135 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
1155 if (!world.chunkIsSimulating?.(
1156 entity.position.tileX,
1157 entity.position.tileY,
1158 entity.position.dimensionId ?? OVERWORLD_ID
1159 ))
1136 1160 { continue; }
1137 1161 const combat = entity.combat;
1138 1162 clearLeashingIfHome(world, entity);
@@ -1206,7 +1230,8 @@ export function stepCombat (world, now = Date.now())
1206 1230 entity.position.tileX,
1207 1231 entity.position.tileY,
1208 1232 targetPos.tileX,
1209 targetPos.tileY
1233 targetPos.tileY,
1234 entity.position.dimensionId ?? OVERWORLD_ID
1210 1235 );
1211 1236 if (!inRange || !hasArrows)
1212 1237 {
@@ -1252,7 +1277,8 @@ export function stepCombat (world, now = Date.now())
1252 1277 entity.position.tileX,
1253 1278 entity.position.tileY,
1254 1279 targetPos.tileX,
1255 targetPos.tileY
1280 targetPos.tileY,
1281 entity.position.dimensionId ?? OVERWORLD_ID
1256 1282 );
1257 1283 if (!inSpellRange)
1258 1284 {
@@ -1425,7 +1451,14 @@ function coverStepCost (world, threatPos, goalX, goalY, x, y)
1425 1451 // Final adjacent step is always in LOS — don't punish the last lunge.
1426 1452 if (x === goalX && y === goalY)
1427 1453 { return 1; }
1428 if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y))
1454 if (hasCombatLineOfSight(
1455 world,
1456 threatPos.tileX,
1457 threatPos.tileY,
1458 x,
1459 y,
1460 threatPos.dimensionId ?? OVERWORLD_ID
1461 ))
1429 1462 { return COVER_EXPOSED_STEP_COST; }
1430 1463 return 1;
1431 1464 }
@@ -1435,7 +1468,14 @@ function pathCoverScore (world, threatPos, tiles)
1435 1468 let score = 0;
1436 1469 for (const step of tiles)
1437 1470 {
1438 score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y)
1471 score += hasCombatLineOfSight(
1472 world,
1473 threatPos.tileX,
1474 threatPos.tileY,
1475 step.x,
1476 step.y,
1477 threatPos.dimensionId ?? OVERWORLD_ID
1478 )
1439 1479 ? COVER_EXPOSED_STEP_COST
1440 1480 : 1;
1441 1481 }
@@ -1535,7 +1575,14 @@ function queueFleeToCover (world, entityId, handle, position, threatPos)
1535 1575 { return false; }
1536 1576 if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1)
1537 1577 { return false; }
1538 return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y);
1578 return !hasCombatLineOfSight(
1579 world,
1580 threatPos.tileX,
1581 threatPos.tileY,
1582 x,
1583 y,
1584 threatPos.dimensionId ?? OVERWORLD_ID
1585 );
1539 1586 };
1540 1587 if (isGoal(position.tileX, position.tileY))
1541 1588 {
@@ -1744,11 +1791,12 @@ export function queueStandInRangeApproach (
1744 1791
1745 1792 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
1746 1793 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1794 const dimensionId = position.dimensionId ?? OVERWORLD_ID;
1747 1795 if (
1748 1796 distToTarget <= maxRange
1749 1797 && distToTarget >= minStandDist
1750 1798 && aloneHere
1751 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
1799 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY, dimensionId)
1752 1800 )
1753 1801 {
1754 1802 path.tiles = [];
@@ -1769,7 +1817,7 @@ export function queueStandInRangeApproach (
1769 1817 const key = combatTileKey(x, y);
1770 1818 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
1771 1819 { return false; }
1772 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
1820 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY, dimensionId);
1773 1821 };
1774 1822
1775 1823 const tiles = findPathToNearestGoal(
@@ -1934,7 +1982,14 @@ function standInRangePathStale (world, entityId, path, goal, targetTileX, target
1934 1982 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
1935 1983 if (standOff < minStandDist || standOff > maxRange)
1936 1984 { return true; }
1937 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
1985 if (!hasCombatLineOfSight(
1986 world,
1987 dest.x,
1988 dest.y,
1989 targetTileX,
1990 targetTileY,
1991 position.dimensionId ?? OVERWORLD_ID
1992 ))
1938 1993 { return true; }
1939 1994 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
1940 1995 { return true; }
@@ -19,7 +19,7 @@ import {
19} from "../../../shared/combat/combatLevel.js";
19} from "../../../shared/combat/combatLevel.js";
20import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js";
20import { chunkPeaceAggressionImmunity } from "../../../shared/navigation/chunkPresence.js";
21import { skullAttractsTownGuards } from "../../../shared/combat/skull.js";
21import { skullAttractsTownGuards } from "../../../shared/combat/skull.js";
22import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
22import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
23import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js";
23import { spellDefinition, spellMinMagicLevel } from "../../../shared/definitions/spells.js";
24import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
24import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
25import { mobDamageAffinities } from "../../../shared/combat/magic.js";
25import { mobDamageAffinities } from "../../../shared/combat/magic.js";
@@ -585,17 +585,19 @@ export function clearEngage (ecs, entityId)
585 }
585 }
586}
586}
587
587
588export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
588export function hasCombatLineOfSight (world, fromX, fromY, toX, toY, dimensionId = OVERWORLD_ID)
589{
589{
590 const dim = normalizeDimensionId(dimensionId);
590 const isClear = world.isClearForRangedAttack
591 const isClear = world.isClearForRangedAttack
591 ? (x, y) => world.isClearForRangedAttack(x, y)
592 ? (x, y) => world.isClearForRangedAttack(x, y, dim)
592 : (x, y) => world.isEnterable(x, y);
593 : (x, y) => world.isEnterable(x, y, dim);
593 return rayReaches(fromX, fromY, toX, toY, isClear);
594 return rayReaches(fromX, fromY, toX, toY, isClear);
594}
595}
595
596
596function lightOcclusionAtWorld (world, x, y)
597function lightOcclusionAtWorld (world, x, y, dimensionId = OVERWORLD_ID)
597{
598{
598 const data = world.chunkData?.(tileToChunk(x), tileToChunk(y));
599 const dim = normalizeDimensionId(dimensionId);
600 const data = world.chunkData?.(tileToChunk(x), tileToChunk(y), dim);
599 if (!data)
601 if (!data)
600 { return LightOcclusion.clear; }
602 { return LightOcclusion.clear; }
601 const index = tileIndexLocal(x, y);
603 const index = tileIndexLocal(x, y);
@@ -611,11 +613,12 @@ function lightOcclusionAtWorld (world, x, y)
611 * Block lights (torches, …) use live occlusion so passage-open doors let light through;
613 * Block lights (torches, …) use live occlusion so passage-open doors let light through;
612 * entity/spell lights layer on top (same compositing as client inner 3×3).
614 * entity/spell lights layer on top (same compositing as client inner 3×3).
613 */
615 */
614export function tileLightAt (world, tileX, tileY, now = Date.now())
616export function tileLightAt (world, tileX, tileY, now = Date.now(), dimensionId = OVERWORLD_ID)
615{
617{
616 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y);
618 const dim = normalizeDimensionId(dimensionId);
619 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y, dim);
617 const blockSources = blockLightSourcesNearTile(
620 const blockSources = blockLightSourcesNearTile(
618 (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY),
621 (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY, dim),
619 tileX,
622 tileX,
620 tileY
623 tileY
621 );
624 );
@@ -833,7 +836,11 @@ export function stepAggression (world, now = Date.now())
833{
836{
834 for (const entity of world.ecs.query(Component.creature, Component.position))
837 for (const entity of world.ecs.query(Component.creature, Component.position))
835 {
838 {
836 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
839 if (!world.chunkIsSimulating?.(
840 entity.position.tileX,
841 entity.position.tileY,
842 entity.position.dimensionId ?? OVERWORLD_ID
843 ))
837 { continue; }
844 { continue; }
838 const def = mobDefinition(entity.creature.mobTypeId);
845 const def = mobDefinition(entity.creature.mobTypeId);
839 if (world.ecs.get(entity.handle, Component.summon))
846 if (world.ecs.get(entity.handle, Component.summon))
@@ -1001,6 +1008,10 @@ function considerAggressionCandidate (world, attacker, targetHandle, targetEntit
1001 const health = world.ecs.get(targetHandle, Component.health);
1008 const health = world.ecs.get(targetHandle, Component.health);
1002 if (health && health.current <= 0)
1009 if (health && health.current <= 0)
1003 { return null; }
1010 { return null; }
1011 const attackerDim = normalizeDimensionId(attacker.position.dimensionId ?? OVERWORLD_ID);
1012 const targetDim = normalizeDimensionId(targetPos.dimensionId ?? OVERWORLD_ID);
1013 if (attackerDim !== targetDim)
1014 { return null; }
1004 const dist = chebyshev(
1015 const dist = chebyshev(
1005 attacker.position.tileX,
1016 attacker.position.tileX,
1006 attacker.position.tileY,
1017 attacker.position.tileY,
@@ -1012,7 +1023,7 @@ function considerAggressionCandidate (world, attacker, targetHandle, targetEntit
1012 let effectiveDist = dist;
1023 let effectiveDist = dist;
1013 if (dist > 1)
1024 if (dist > 1)
1014 {
1025 {
1015 const light = tileLightAt(world, targetPos.tileX, targetPos.tileY);
1026 const light = tileLightAt(world, targetPos.tileX, targetPos.tileY, Date.now(), attackerDim);
1016 effectiveDist = dist * aggroDistanceMultiplier(light);
1027 effectiveDist = dist * aggroDistanceMultiplier(light);
1017 }
1028 }
1018 if (effectiveDist > range)
1029 if (effectiveDist > range)
@@ -1022,7 +1033,8 @@ function considerAggressionCandidate (world, attacker, targetHandle, targetEntit
1022 attacker.position.tileX,
1033 attacker.position.tileX,
1023 attacker.position.tileY,
1034 attacker.position.tileY,
1024 targetPos.tileX,
1035 targetPos.tileX,
1025 targetPos.tileY
1036 targetPos.tileY,
1037 attackerDim
1026 ))
1038 ))
1027 { return null; }
1039 { return null; }
1028 return dist;
1040 return dist;
@@ -1055,7 +1067,11 @@ export function resolveCombatTarget (world, targetId)
1055 return {
1067 return {
1056 local: false,
1068 local: false,
1057 handle: null,
1069 handle: null,
1058 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
1070 pos: {
1071 tileX: ghost.tileX,
1072 tileY: ghost.tileY,
1073 dimensionId: normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID)
1074 },
1059 health
1075 health
1060 };
1076 };
1061}
1077}
@@ -1088,7 +1104,11 @@ export function stepPassiveHealthRegen (world, now = Date.now(), dt = 1 / 20)
1088 const { handle, entityId, health, position, character } = entity;
1104 const { handle, entityId, health, position, character } = entity;
1089 if (world.ecs.has(handle, Component.dead))
1105 if (world.ecs.has(handle, Component.dead))
1090 { continue; }
1106 { continue; }
1091 if (!world.chunkIsSimulating?.(position.tileX, position.tileY))
1107 if (!world.chunkIsSimulating?.(
1108 position.tileX,
1109 position.tileY,
1110 position.dimensionId ?? OVERWORLD_ID
1111 ))
1092 { continue; }
1112 { continue; }
1093 if ((health.current | 0) >= (health.max | 0))
1113 if ((health.current | 0) >= (health.max | 0))
1094 { continue; }
1114 { continue; }
@@ -1132,7 +1152,11 @@ export function stepCombat (world, now = Date.now())
1132 dropCombatTarget(world, entity);
1152 dropCombatTarget(world, entity);
1133 continue;
1153 continue;
1134 }
1154 }
1135 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
1155 if (!world.chunkIsSimulating?.(
1156 entity.position.tileX,
1157 entity.position.tileY,
1158 entity.position.dimensionId ?? OVERWORLD_ID
1159 ))
1136 { continue; }
1160 { continue; }
1137 const combat = entity.combat;
1161 const combat = entity.combat;
1138 clearLeashingIfHome(world, entity);
1162 clearLeashingIfHome(world, entity);
@@ -1206,7 +1230,8 @@ export function stepCombat (world, now = Date.now())
1206 entity.position.tileX,
1230 entity.position.tileX,
1207 entity.position.tileY,
1231 entity.position.tileY,
1208 targetPos.tileX,
1232 targetPos.tileX,
1209 targetPos.tileY
1233 targetPos.tileY,
1234 entity.position.dimensionId ?? OVERWORLD_ID
1210 );
1235 );
1211 if (!inRange || !hasArrows)
1236 if (!inRange || !hasArrows)
1212 {
1237 {
@@ -1252,7 +1277,8 @@ export function stepCombat (world, now = Date.now())
1252 entity.position.tileX,
1277 entity.position.tileX,
1253 entity.position.tileY,
1278 entity.position.tileY,
1254 targetPos.tileX,
1279 targetPos.tileX,
1255 targetPos.tileY
1280 targetPos.tileY,
1281 entity.position.dimensionId ?? OVERWORLD_ID
1256 );
1282 );
1257 if (!inSpellRange)
1283 if (!inSpellRange)
1258 {
1284 {
@@ -1425,7 +1451,14 @@ function coverStepCost (world, threatPos, goalX, goalY, x, y)
1425 // Final adjacent step is always in LOS — don't punish the last lunge.
1451 // Final adjacent step is always in LOS — don't punish the last lunge.
1426 if (x === goalX && y === goalY)
1452 if (x === goalX && y === goalY)
1427 { return 1; }
1453 { return 1; }
1428 if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y))
1454 if (hasCombatLineOfSight(
1455 world,
1456 threatPos.tileX,
1457 threatPos.tileY,
1458 x,
1459 y,
1460 threatPos.dimensionId ?? OVERWORLD_ID
1461 ))
1429 { return COVER_EXPOSED_STEP_COST; }
1462 { return COVER_EXPOSED_STEP_COST; }
1430 return 1;
1463 return 1;
1431}
1464}
@@ -1435,7 +1468,14 @@ function pathCoverScore (world, threatPos, tiles)
1435 let score = 0;
1468 let score = 0;
1436 for (const step of tiles)
1469 for (const step of tiles)
1437 {
1470 {
1438 score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y)
1471 score += hasCombatLineOfSight(
1472 world,
1473 threatPos.tileX,
1474 threatPos.tileY,
1475 step.x,
1476 step.y,
1477 threatPos.dimensionId ?? OVERWORLD_ID
1478 )
1439 ? COVER_EXPOSED_STEP_COST
1479 ? COVER_EXPOSED_STEP_COST
1440 : 1;
1480 : 1;
1441 }
1481 }
@@ -1535,7 +1575,14 @@ function queueFleeToCover (world, entityId, handle, position, threatPos)
1535 { return false; }
1575 { return false; }
1536 if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1)
1576 if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1)
1537 { return false; }
1577 { return false; }
1538 return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y);
1578 return !hasCombatLineOfSight(
1579 world,
1580 threatPos.tileX,
1581 threatPos.tileY,
1582 x,
1583 y,
1584 threatPos.dimensionId ?? OVERWORLD_ID
1585 );
1539 };
1586 };
1540 if (isGoal(position.tileX, position.tileY))
1587 if (isGoal(position.tileX, position.tileY))
1541 {
1588 {
@@ -1744,11 +1791,12 @@ export function queueStandInRangeApproach (
1744
1791
1745 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
1792 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
1746 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1793 const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
1794 const dimensionId = position.dimensionId ?? OVERWORLD_ID;
1747 if (
1795 if (
1748 distToTarget <= maxRange
1796 distToTarget <= maxRange
1749 && distToTarget >= minStandDist
1797 && distToTarget >= minStandDist
1750 && aloneHere
1798 && aloneHere
1751 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
1799 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY, dimensionId)
1752 )
1800 )
1753 {
1801 {
1754 path.tiles = [];
1802 path.tiles = [];
@@ -1769,7 +1817,7 @@ export function queueStandInRangeApproach (
1769 const key = combatTileKey(x, y);
1817 const key = combatTileKey(x, y);
1770 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
1818 if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
1771 { return false; }
1819 { return false; }
1772 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
1820 return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY, dimensionId);
1773 };
1821 };
1774
1822
1775 const tiles = findPathToNearestGoal(
1823 const tiles = findPathToNearestGoal(
@@ -1934,7 +1982,14 @@ function standInRangePathStale (world, entityId, path, goal, targetTileX, target
1934 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
1982 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
1935 if (standOff < minStandDist || standOff > maxRange)
1983 if (standOff < minStandDist || standOff > maxRange)
1936 { return true; }
1984 { return true; }
1937 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
1985 if (!hasCombatLineOfSight(
1986 world,
1987 dest.x,
1988 dest.y,
1989 targetTileX,
1990 targetTileY,
1991 position.dimensionId ?? OVERWORLD_ID
1992 ))
1938 { return true; }
1993 { return true; }
1939 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
1994 if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
1940 { return true; }
1995 { return true; }
server/src/courier/service.js +20 −9
@@ -7,6 +7,7 @@ import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVa
7 7 import { attachOrigins, normalizeOrigins } from "../../../shared/items/origin.js";
8 8 import { advanceCourierFlight } from "../../../shared/courier/flight.js";
9 9 import { GAIT } from "../../../shared/protocol/constants.js";
10 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10 11 import { decodeChunkBlob } from "../world/chunkData.js";
11 12 import { findReservedChequeIndex } from "../items/bags.js";
12 13 import {
@@ -49,7 +50,8 @@ export class CourierService
49 50 const tiles = [];
50 51 for (const coord of this.worldDb.listChunkCoords(revisionId))
51 52 {
52 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
53 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
54 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim);
53 55 if (!row)
54 56 { continue; }
55 57 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
@@ -62,7 +64,8 @@ export class CourierService
62 64 { continue; }
63 65 tiles.push({
64 66 tileX: coord.chunk_x * CHUNK_SIZE + localX,
65 tileY: coord.chunk_y * CHUNK_SIZE + localY
67 tileY: coord.chunk_y * CHUNK_SIZE + localY,
68 dimensionId: dim
66 69 });
67 70 }
68 71 }
@@ -70,30 +73,38 @@ export class CourierService
70 73 return tiles;
71 74 }
72 75
73 nearestBank (tileX, tileY)
76 nearestBank (tileX, tileY, dimensionId = null)
74 77 {
75 return this.#nearestTile(this.bankTiles, tileX, tileY);
78 return this.#nearestTile(this.bankTiles, tileX, tileY, dimensionId);
76 79 }
77 80
78 nearestBountyOffice (tileX, tileY)
81 nearestBountyOffice (tileX, tileY, dimensionId = null)
79 82 {
80 return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY);
83 return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY, dimensionId);
81 84 }
82 85
83 isAdjacentToBountyOffice (tileX, tileY)
86 isAdjacentToBountyOffice (tileX, tileY, dimensionId = null)
84 87 {
88 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
85 89 return this.bountyOfficeTiles.some((office) =>
86 Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1);
90 {
91 if (dim != null && normalizeDimensionId(office.dimensionId ?? OVERWORLD_ID) !== dim)
92 { return false; }
93 return Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1;
94 });
87 95 }
88 96
89 #nearestTile (tiles, tileX, tileY)
97 #nearestTile (tiles, tileX, tileY, dimensionId = null)
90 98 {
91 99 if (!tiles.length)
92 100 { return null; }
101 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
93 102 let best = null;
94 103 let bestDist = Infinity;
95 104 for (const tile of tiles)
96 105 {
106 if (dim != null && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
107 { continue; }
97 108 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
98 109 if (dist < bestDist)
99 110 {
@@ -7,6 +7,7 @@ import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVa
7import { attachOrigins, normalizeOrigins } from "../../../shared/items/origin.js";
7import { attachOrigins, normalizeOrigins } from "../../../shared/items/origin.js";
8import { advanceCourierFlight } from "../../../shared/courier/flight.js";
8import { advanceCourierFlight } from "../../../shared/courier/flight.js";
9import { GAIT } from "../../../shared/protocol/constants.js";
9import { GAIT } from "../../../shared/protocol/constants.js";
10import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10import { decodeChunkBlob } from "../world/chunkData.js";
11import { decodeChunkBlob } from "../world/chunkData.js";
11import { findReservedChequeIndex } from "../items/bags.js";
12import { findReservedChequeIndex } from "../items/bags.js";
12import {
13import {
@@ -49,7 +50,8 @@ export class CourierService
49 const tiles = [];
50 const tiles = [];
50 for (const coord of this.worldDb.listChunkCoords(revisionId))
51 for (const coord of this.worldDb.listChunkCoords(revisionId))
51 {
52 {
52 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
53 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
54 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim);
53 if (!row)
55 if (!row)
54 { continue; }
56 { continue; }
55 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
57 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
@@ -62,7 +64,8 @@ export class CourierService
62 { continue; }
64 { continue; }
63 tiles.push({
65 tiles.push({
64 tileX: coord.chunk_x * CHUNK_SIZE + localX,
66 tileX: coord.chunk_x * CHUNK_SIZE + localX,
65 tileY: coord.chunk_y * CHUNK_SIZE + localY
67 tileY: coord.chunk_y * CHUNK_SIZE + localY,
68 dimensionId: dim
66 });
69 });
67 }
70 }
68 }
71 }
@@ -70,30 +73,38 @@ export class CourierService
70 return tiles;
73 return tiles;
71 }
74 }
72
75
73 nearestBank (tileX, tileY)
76 nearestBank (tileX, tileY, dimensionId = null)
74 {
77 {
75 return this.#nearestTile(this.bankTiles, tileX, tileY);
78 return this.#nearestTile(this.bankTiles, tileX, tileY, dimensionId);
76 }
79 }
77
80
78 nearestBountyOffice (tileX, tileY)
81 nearestBountyOffice (tileX, tileY, dimensionId = null)
79 {
82 {
80 return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY);
83 return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY, dimensionId);
81 }
84 }
82
85
83 isAdjacentToBountyOffice (tileX, tileY)
86 isAdjacentToBountyOffice (tileX, tileY, dimensionId = null)
84 {
87 {
88 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
85 return this.bountyOfficeTiles.some((office) =>
89 return this.bountyOfficeTiles.some((office) =>
86 Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1);
90 {
91 if (dim != null && normalizeDimensionId(office.dimensionId ?? OVERWORLD_ID) !== dim)
92 { return false; }
93 return Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1;
94 });
87 }
95 }
88
96
89 #nearestTile (tiles, tileX, tileY)
97 #nearestTile (tiles, tileX, tileY, dimensionId = null)
90 {
98 {
91 if (!tiles.length)
99 if (!tiles.length)
92 { return null; }
100 { return null; }
101 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
93 let best = null;
102 let best = null;
94 let bestDist = Infinity;
103 let bestDist = Infinity;
95 for (const tile of tiles)
104 for (const tile of tiles)
96 {
105 {
106 if (dim != null && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
107 { continue; }
97 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
108 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
98 if (dist < bestDist)
109 if (dist < bestDist)
99 {
110 {
server/src/crafting/service.js +10 −5
@@ -29,6 +29,7 @@ import { craftDurationMultiplier } from "../../../shared/equipment/jewelryEffect
29 29 import { bagView } from "../items/bags.js";
30 30 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
31 31 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
32 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
32 33 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
33 34
34 35 function userError (message)
@@ -52,15 +53,16 @@ function ensureCraftSessions (world)
52 53 return world.craftSessions;
53 54 }
54 55
55 function nearStationBlock (world, tileX, tileY, blockType)
56 function nearStationBlock (world, tileX, tileY, blockType, dimensionId = OVERWORLD_ID)
56 57 {
58 const dim = normalizeDimensionId(dimensionId);
57 59 for (let dy = -1; dy <= 1; dy++)
58 60 {
59 61 for (let dx = -1; dx <= 1; dx++)
60 62 {
61 63 if (dx === 0 && dy === 0)
62 64 { continue; }
63 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
65 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim);
64 66 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
65 67 if (data.blocks[index]?.typeId === blockType)
66 68 { return true; }
@@ -173,8 +175,9 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
173 175 { throw userError("That recipe cannot be made here."); }
174 176
175 177 const position = world.ecs.get(handle, Component.position);
178 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
176 179 const blockType = stationBlockType(stationId);
177 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
180 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
178 181 { throw userError("You need to stand next to the station."); }
179 182
180 183 const inventory = world.ecs.get(handle, Component.inventory);
@@ -305,7 +308,8 @@ export function openStation (world, sessionId, characterId, stationId)
305 308 { throw userError("Unknown crafting station."); }
306 309 const blockType = stationBlockType(stationId);
307 310 const position = world.ecs.get(handle, Component.position);
308 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
311 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
312 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
309 313 { throw userError("You need to stand next to the station."); }
310 314
311 315 const events = [];
@@ -370,11 +374,12 @@ export function stepCrafting (world, now)
370 374 const inventory = world.ecs.get(handle, Component.inventory);
371 375 const skills = world.ecs.get(handle, Component.skills);
372 376 const position = world.ecs.get(handle, Component.position);
377 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
373 378 const blockType = stationBlockType(session.stationId);
374 379 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
375 380
376 381 if (!recipe || !stationDef || !inventory
377 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
382 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
378 383 || !canCraftFitInventory(inventory.slots, recipe, { dyeColorKey: session.dyeColorKey })
379 384 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
380 385 {
@@ -29,6 +29,7 @@ import { craftDurationMultiplier } from "../../../shared/equipment/jewelryEffect
29import { bagView } from "../items/bags.js";
29import { bagView } from "../items/bags.js";
30import { tileToChunk, tileToLocal } from "../world/coordinates.js";
30import { tileToChunk, tileToLocal } from "../world/coordinates.js";
31import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
31import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
32import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
32import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
33import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
33
34
34function userError (message)
35function userError (message)
@@ -52,15 +53,16 @@ function ensureCraftSessions (world)
52 return world.craftSessions;
53 return world.craftSessions;
53}
54}
54
55
55function nearStationBlock (world, tileX, tileY, blockType)
56function nearStationBlock (world, tileX, tileY, blockType, dimensionId = OVERWORLD_ID)
56{
57{
58 const dim = normalizeDimensionId(dimensionId);
57 for (let dy = -1; dy <= 1; dy++)
59 for (let dy = -1; dy <= 1; dy++)
58 {
60 {
59 for (let dx = -1; dx <= 1; dx++)
61 for (let dx = -1; dx <= 1; dx++)
60 {
62 {
61 if (dx === 0 && dy === 0)
63 if (dx === 0 && dy === 0)
62 { continue; }
64 { continue; }
63 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
65 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim);
64 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
66 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
65 if (data.blocks[index]?.typeId === blockType)
67 if (data.blocks[index]?.typeId === blockType)
66 { return true; }
68 { return true; }
@@ -173,8 +175,9 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
173 { throw userError("That recipe cannot be made here."); }
175 { throw userError("That recipe cannot be made here."); }
174
176
175 const position = world.ecs.get(handle, Component.position);
177 const position = world.ecs.get(handle, Component.position);
178 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
176 const blockType = stationBlockType(stationId);
179 const blockType = stationBlockType(stationId);
177 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
180 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
178 { throw userError("You need to stand next to the station."); }
181 { throw userError("You need to stand next to the station."); }
179
182
180 const inventory = world.ecs.get(handle, Component.inventory);
183 const inventory = world.ecs.get(handle, Component.inventory);
@@ -305,7 +308,8 @@ export function openStation (world, sessionId, characterId, stationId)
305 { throw userError("Unknown crafting station."); }
308 { throw userError("Unknown crafting station."); }
306 const blockType = stationBlockType(stationId);
309 const blockType = stationBlockType(stationId);
307 const position = world.ecs.get(handle, Component.position);
310 const position = world.ecs.get(handle, Component.position);
308 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
311 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
312 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
309 { throw userError("You need to stand next to the station."); }
313 { throw userError("You need to stand next to the station."); }
310
314
311 const events = [];
315 const events = [];
@@ -370,11 +374,12 @@ export function stepCrafting (world, now)
370 const inventory = world.ecs.get(handle, Component.inventory);
374 const inventory = world.ecs.get(handle, Component.inventory);
371 const skills = world.ecs.get(handle, Component.skills);
375 const skills = world.ecs.get(handle, Component.skills);
372 const position = world.ecs.get(handle, Component.position);
376 const position = world.ecs.get(handle, Component.position);
377 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
373 const blockType = stationBlockType(session.stationId);
378 const blockType = stationBlockType(session.stationId);
374 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
379 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
375
380
376 if (!recipe || !stationDef || !inventory
381 if (!recipe || !stationDef || !inventory
377 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
382 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType, dim))
378 || !canCraftFitInventory(inventory.slots, recipe, { dyeColorKey: session.dyeColorKey })
383 || !canCraftFitInventory(inventory.slots, recipe, { dyeColorKey: session.dyeColorKey })
379 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
384 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
380 {
385 {
server/src/firestarting/service.js +27 −14
@@ -22,6 +22,7 @@ import { placeOrMergeGroundStack, publicGroundItem, removeGroundItem, bagView }
22 22 import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
23 23 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
24 24 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
25 26
26 27 const FIRE_ATTEMPT_MS = 1100;
27 28 const MAX_LIGHT_ATTEMPTS = 3;
@@ -40,9 +41,10 @@ function characterDisplayName (world, handle)
40 41 return name || "someone";
41 42 }
42 43
43 function tileKey (tileX, tileY)
44 function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
44 45 {
45 return `${tileX},${tileY}`;
46 const dim = normalizeDimensionId(dimensionId);
47 return `${dim}:${tileX},${tileY}`;
46 48 }
47 49
48 50 function ensureCampfires (world)
@@ -112,13 +114,14 @@ function consumeTinderboxCharge (slots, slotIndex)
112 114 return { ok: true, slots: next, exhausted: false };
113 115 }
114 116
115 function placeBlock (world, tileX, tileY, typeId, state, config = null)
117 function placeBlock (world, tileX, tileY, typeId, state, config = null, dimensionId = OVERWORLD_ID)
116 118 {
119 const dim = normalizeDimensionId(dimensionId);
117 120 const chunkX = tileToChunk(tileX);
118 121 const chunkY = tileToChunk(tileY);
119 122 const localX = tileToLocal(tileX);
120 123 const localY = tileToLocal(tileY);
121 const data = world.chunkData(chunkX, chunkY);
124 const data = world.chunkData(chunkX, chunkY, dim);
122 125 const index = localY * CHUNK_SIZE + localX;
123 126 const block = { typeId, state, config };
124 127 data.blocks[index] = block;
@@ -126,6 +129,7 @@ function placeBlock (world, tileX, tileY, typeId, state, config = null)
126 129 type: "chunk-delta",
127 130 chunkX,
128 131 chunkY,
132 dimensionId: dim,
129 133 tileX,
130 134 tileY,
131 135 localX,
@@ -134,13 +138,14 @@ function placeBlock (world, tileX, tileY, typeId, state, config = null)
134 138 };
135 139 }
136 140
137 function clearBlockAt (world, tileX, tileY)
141 function clearBlockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
138 142 {
143 const dim = normalizeDimensionId(dimensionId);
139 144 const chunkX = tileToChunk(tileX);
140 145 const chunkY = tileToChunk(tileY);
141 146 const localX = tileToLocal(tileX);
142 147 const localY = tileToLocal(tileY);
143 const data = world.chunkData(chunkX, chunkY);
148 const data = world.chunkData(chunkX, chunkY, dim);
144 149 const index = localY * CHUNK_SIZE + localX;
145 150 if (!data.blocks[index])
146 151 { return null; }
@@ -149,6 +154,7 @@ function clearBlockAt (world, tileX, tileY)
149 154 type: "chunk-delta",
150 155 chunkX,
151 156 chunkY,
157 dimensionId: dim,
152 158 tileX,
153 159 tileY,
154 160 localX,
@@ -157,9 +163,10 @@ function clearBlockAt (world, tileX, tileY)
157 163 };
158 164 }
159 165
160 function blockAt (world, tileX, tileY)
166 function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
161 167 {
162 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
168 const dim = normalizeDimensionId(dimensionId);
169 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
163 170 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
164 171 return data.blocks[index] ?? null;
165 172 }
@@ -237,7 +244,8 @@ export function startFire (world, sessionId, characterId, groundItemId, now)
237 244 if (!isAdjacentTile(position.tileX, position.tileY, item.tileX, item.tileY))
238 245 { throw userError("You need to stand next to the logs."); }
239 246
240 if (blockAt(world, item.tileX, item.tileY))
247 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
248 if (blockAt(world, item.tileX, item.tileY, dim))
241 249 { throw userError("There is no room for a fire there."); }
242 250
243 251 const difficulty = firestartingDifficulty(woodTier);
@@ -271,6 +279,7 @@ export function startFire (world, sessionId, characterId, groundItemId, now)
271 279 groundItemId: item.groundItemId,
272 280 tileX: item.tileX,
273 281 tileY: item.tileY,
282 dimensionId: dim,
274 283 woodTier,
275 284 difficulty,
276 285 attemptsLeft: MAX_LIGHT_ATTEMPTS,
@@ -316,7 +325,7 @@ function succeedLight (world, handle, entityId, characterId, session, events, pr
316 325 clearFireSession(world, characterId);
317 326 return;
318 327 }
319 if (blockAt(world, session.tileX, session.tileY))
328 if (blockAt(world, session.tileX, session.tileY, normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID)))
320 329 {
321 330 events.push({
322 331 type: "command-error",
@@ -330,18 +339,21 @@ function succeedLight (world, handle, entityId, characterId, session, events, pr
330 339 consumeOneGroundLog(world, item, events);
331 340 const expiresAt = now + campfireDurationMs(session.woodTier);
332 341 const litByName = characterDisplayName(world, handle);
342 const dim = normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID);
333 343 const delta = placeBlock(
334 344 world,
335 345 session.tileX,
336 346 session.tileY,
337 347 BlockType.campfire,
338 348 session.woodTier,
339 { woodTier: session.woodTier, litAt: now, expiresAt, litByName }
349 { woodTier: session.woodTier, litAt: now, expiresAt, litByName },
350 dim
340 351 );
341 352 events.push(delta);
342 ensureCampfires(world).set(tileKey(session.tileX, session.tileY), {
353 ensureCampfires(world).set(tileKey(session.tileX, session.tileY, dim), {
343 354 tileX: session.tileX,
344 355 tileY: session.tileY,
356 dimensionId: dim,
345 357 woodTier: session.woodTier,
346 358 expiresAt,
347 359 litByName
@@ -470,10 +482,11 @@ export function stepCampfireExpires (world, now)
470 482 if (now < entry.expiresAt)
471 483 { continue; }
472 484 expires.delete(key);
473 const block = blockAt(world, entry.tileX, entry.tileY);
485 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
486 const block = blockAt(world, entry.tileX, entry.tileY, dim);
474 487 if (!block || block.typeId !== BlockType.campfire)
475 488 { continue; }
476 const delta = clearBlockAt(world, entry.tileX, entry.tileY);
489 const delta = clearBlockAt(world, entry.tileX, entry.tileY, dim);
477 490 if (delta)
478 491 { events.push(delta); }
479 492 spawnAsh(
@@ -22,6 +22,7 @@ import { placeOrMergeGroundStack, publicGroundItem, removeGroundItem, bagView }
22import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
22import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
23import { tileToChunk, tileToLocal } from "../world/coordinates.js";
23import { tileToChunk, tileToLocal } from "../world/coordinates.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
25
26
26const FIRE_ATTEMPT_MS = 1100;
27const FIRE_ATTEMPT_MS = 1100;
27const MAX_LIGHT_ATTEMPTS = 3;
28const MAX_LIGHT_ATTEMPTS = 3;
@@ -40,9 +41,10 @@ function characterDisplayName (world, handle)
40 return name || "someone";
41 return name || "someone";
41}
42}
42
43
43function tileKey (tileX, tileY)
44function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
44{
45{
45 return `${tileX},${tileY}`;
46 const dim = normalizeDimensionId(dimensionId);
47 return `${dim}:${tileX},${tileY}`;
46}
48}
47
49
48function ensureCampfires (world)
50function ensureCampfires (world)
@@ -112,13 +114,14 @@ function consumeTinderboxCharge (slots, slotIndex)
112 return { ok: true, slots: next, exhausted: false };
114 return { ok: true, slots: next, exhausted: false };
113}
115}
114
116
115function placeBlock (world, tileX, tileY, typeId, state, config = null)
117function placeBlock (world, tileX, tileY, typeId, state, config = null, dimensionId = OVERWORLD_ID)
116{
118{
119 const dim = normalizeDimensionId(dimensionId);
117 const chunkX = tileToChunk(tileX);
120 const chunkX = tileToChunk(tileX);
118 const chunkY = tileToChunk(tileY);
121 const chunkY = tileToChunk(tileY);
119 const localX = tileToLocal(tileX);
122 const localX = tileToLocal(tileX);
120 const localY = tileToLocal(tileY);
123 const localY = tileToLocal(tileY);
121 const data = world.chunkData(chunkX, chunkY);
124 const data = world.chunkData(chunkX, chunkY, dim);
122 const index = localY * CHUNK_SIZE + localX;
125 const index = localY * CHUNK_SIZE + localX;
123 const block = { typeId, state, config };
126 const block = { typeId, state, config };
124 data.blocks[index] = block;
127 data.blocks[index] = block;
@@ -126,6 +129,7 @@ function placeBlock (world, tileX, tileY, typeId, state, config = null)
126 type: "chunk-delta",
129 type: "chunk-delta",
127 chunkX,
130 chunkX,
128 chunkY,
131 chunkY,
132 dimensionId: dim,
129 tileX,
133 tileX,
130 tileY,
134 tileY,
131 localX,
135 localX,
@@ -134,13 +138,14 @@ function placeBlock (world, tileX, tileY, typeId, state, config = null)
134 };
138 };
135}
139}
136
140
137function clearBlockAt (world, tileX, tileY)
141function clearBlockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
138{
142{
143 const dim = normalizeDimensionId(dimensionId);
139 const chunkX = tileToChunk(tileX);
144 const chunkX = tileToChunk(tileX);
140 const chunkY = tileToChunk(tileY);
145 const chunkY = tileToChunk(tileY);
141 const localX = tileToLocal(tileX);
146 const localX = tileToLocal(tileX);
142 const localY = tileToLocal(tileY);
147 const localY = tileToLocal(tileY);
143 const data = world.chunkData(chunkX, chunkY);
148 const data = world.chunkData(chunkX, chunkY, dim);
144 const index = localY * CHUNK_SIZE + localX;
149 const index = localY * CHUNK_SIZE + localX;
145 if (!data.blocks[index])
150 if (!data.blocks[index])
146 { return null; }
151 { return null; }
@@ -149,6 +154,7 @@ function clearBlockAt (world, tileX, tileY)
149 type: "chunk-delta",
154 type: "chunk-delta",
150 chunkX,
155 chunkX,
151 chunkY,
156 chunkY,
157 dimensionId: dim,
152 tileX,
158 tileX,
153 tileY,
159 tileY,
154 localX,
160 localX,
@@ -157,9 +163,10 @@ function clearBlockAt (world, tileX, tileY)
157 };
163 };
158}
164}
159
165
160function blockAt (world, tileX, tileY)
166function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
161{
167{
162 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
168 const dim = normalizeDimensionId(dimensionId);
169 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
163 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
170 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
164 return data.blocks[index] ?? null;
171 return data.blocks[index] ?? null;
165}
172}
@@ -237,7 +244,8 @@ export function startFire (world, sessionId, characterId, groundItemId, now)
237 if (!isAdjacentTile(position.tileX, position.tileY, item.tileX, item.tileY))
244 if (!isAdjacentTile(position.tileX, position.tileY, item.tileX, item.tileY))
238 { throw userError("You need to stand next to the logs."); }
245 { throw userError("You need to stand next to the logs."); }
239
246
240 if (blockAt(world, item.tileX, item.tileY))
247 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
248 if (blockAt(world, item.tileX, item.tileY, dim))
241 { throw userError("There is no room for a fire there."); }
249 { throw userError("There is no room for a fire there."); }
242
250
243 const difficulty = firestartingDifficulty(woodTier);
251 const difficulty = firestartingDifficulty(woodTier);
@@ -271,6 +279,7 @@ export function startFire (world, sessionId, characterId, groundItemId, now)
271 groundItemId: item.groundItemId,
279 groundItemId: item.groundItemId,
272 tileX: item.tileX,
280 tileX: item.tileX,
273 tileY: item.tileY,
281 tileY: item.tileY,
282 dimensionId: dim,
274 woodTier,
283 woodTier,
275 difficulty,
284 difficulty,
276 attemptsLeft: MAX_LIGHT_ATTEMPTS,
285 attemptsLeft: MAX_LIGHT_ATTEMPTS,
@@ -316,7 +325,7 @@ function succeedLight (world, handle, entityId, characterId, session, events, pr
316 clearFireSession(world, characterId);
325 clearFireSession(world, characterId);
317 return;
326 return;
318 }
327 }
319 if (blockAt(world, session.tileX, session.tileY))
328 if (blockAt(world, session.tileX, session.tileY, normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID)))
320 {
329 {
321 events.push({
330 events.push({
322 type: "command-error",
331 type: "command-error",
@@ -330,18 +339,21 @@ function succeedLight (world, handle, entityId, characterId, session, events, pr
330 consumeOneGroundLog(world, item, events);
339 consumeOneGroundLog(world, item, events);
331 const expiresAt = now + campfireDurationMs(session.woodTier);
340 const expiresAt = now + campfireDurationMs(session.woodTier);
332 const litByName = characterDisplayName(world, handle);
341 const litByName = characterDisplayName(world, handle);
342 const dim = normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID);
333 const delta = placeBlock(
343 const delta = placeBlock(
334 world,
344 world,
335 session.tileX,
345 session.tileX,
336 session.tileY,
346 session.tileY,
337 BlockType.campfire,
347 BlockType.campfire,
338 session.woodTier,
348 session.woodTier,
339 { woodTier: session.woodTier, litAt: now, expiresAt, litByName }
349 { woodTier: session.woodTier, litAt: now, expiresAt, litByName },
350 dim
340 );
351 );
341 events.push(delta);
352 events.push(delta);
342 ensureCampfires(world).set(tileKey(session.tileX, session.tileY), {
353 ensureCampfires(world).set(tileKey(session.tileX, session.tileY, dim), {
343 tileX: session.tileX,
354 tileX: session.tileX,
344 tileY: session.tileY,
355 tileY: session.tileY,
356 dimensionId: dim,
345 woodTier: session.woodTier,
357 woodTier: session.woodTier,
346 expiresAt,
358 expiresAt,
347 litByName
359 litByName
@@ -470,10 +482,11 @@ export function stepCampfireExpires (world, now)
470 if (now < entry.expiresAt)
482 if (now < entry.expiresAt)
471 { continue; }
483 { continue; }
472 expires.delete(key);
484 expires.delete(key);
473 const block = blockAt(world, entry.tileX, entry.tileY);
485 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
486 const block = blockAt(world, entry.tileX, entry.tileY, dim);
474 if (!block || block.typeId !== BlockType.campfire)
487 if (!block || block.typeId !== BlockType.campfire)
475 { continue; }
488 { continue; }
476 const delta = clearBlockAt(world, entry.tileX, entry.tileY);
489 const delta = clearBlockAt(world, entry.tileX, entry.tileY, dim);
477 if (delta)
490 if (delta)
478 { events.push(delta); }
491 { events.push(delta); }
479 spawnAsh(
492 spawnAsh(
server/src/fishing/service.js +26 −15
@@ -44,6 +44,7 @@ import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
44 44 import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
45 45 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
46 46 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
47 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
47 48 import { tileShoveEvent } from "../simulation/tileInteract.js";
48 49 import { seasonIdAt } from "../../../shared/world/season.js";
49 50
@@ -60,9 +61,10 @@ function userError (message)
60 61 return error;
61 62 }
62 63
63 function tileKey (tileX, tileY)
64 function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
64 65 {
65 return `${tileX},${tileY}`;
66 const dim = normalizeDimensionId(dimensionId);
67 return `${dim}:${tileX},${tileY}`;
66 68 }
67 69
68 70 function characterDisplayName (world, handle)
@@ -91,27 +93,30 @@ function clearFishSession (world, characterId)
91 93 ensureFishSessions(world).delete(characterId);
92 94 }
93 95
94 function blockAt (world, tileX, tileY)
96 function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
95 97 {
96 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
98 const dim = normalizeDimensionId(dimensionId);
99 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
97 100 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
98 101 return data.blocks[index] ?? null;
99 102 }
100 103
101 function groundAt (world, tileX, tileY)
104 function groundAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
102 105 {
103 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
106 const dim = normalizeDimensionId(dimensionId);
107 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
104 108 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
105 109 return normalizeGround(data.grounds[index]).typeId;
106 110 }
107 111
108 function setBlockState (world, tileX, tileY, state)
112 function setBlockState (world, tileX, tileY, state, dimensionId = OVERWORLD_ID)
109 113 {
114 const dim = normalizeDimensionId(dimensionId);
110 115 const chunkX = tileToChunk(tileX);
111 116 const chunkY = tileToChunk(tileY);
112 117 const localX = tileToLocal(tileX);
113 118 const localY = tileToLocal(tileY);
114 const data = world.chunkData(chunkX, chunkY);
119 const data = world.chunkData(chunkX, chunkY, dim);
115 120 const index = localY * CHUNK_SIZE + localX;
116 121 const existing = data.blocks[index];
117 122 if (!existing)
@@ -122,6 +127,7 @@ function setBlockState (world, tileX, tileY, state)
122 127 type: "chunk-delta",
123 128 chunkX,
124 129 chunkY,
130 dimensionId: dim,
125 131 tileX,
126 132 tileY,
127 133 localX,
@@ -193,13 +199,14 @@ export function startFish (world, sessionId, characterId, tileX, tileY, now = Da
193 199 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
194 200 { throw userError("You need to stand next to the fishing spot."); }
195 201
196 const block = blockAt(world, tileX, tileY);
202 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
203 const block = blockAt(world, tileX, tileY, dim);
197 204 if (!block || block.typeId !== BlockType.fishingSpot)
198 205 { throw userError("There is no fishing spot there."); }
199 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY)))
206 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY, dim)))
200 207 { throw userError("The fish have scattered. Wait for them to return."); }
201 208
202 const ground = groundAt(world, tileX, tileY);
209 const ground = groundAt(world, tileX, tileY, dim);
203 210 const season = seasonIdAt(now);
204 211 if (ground !== GroundType.water && ground !== GroundType.deepWater)
205 212 { throw userError("Fishing spots must be on water."); }
@@ -272,6 +279,7 @@ export function startFish (world, sessionId, characterId, tileX, tileY, now = Da
272 279 sessionId,
273 280 tileX,
274 281 tileY,
282 dimensionId: dim,
275 283 toolItemId: resolved.tool.def.itemId,
276 284 isNet,
277 285 baitRank,
@@ -382,12 +390,14 @@ function completeCatch (world, handle, entityId, characterId, session, events, p
382 390 });
383 391 }
384 392
385 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted");
393 const dim = normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID);
394 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted", dim);
386 395 if (exhausted)
387 396 { events.push(exhausted); }
388 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), {
397 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY, dim), {
389 398 tileX: session.tileX,
390 399 tileY: session.tileY,
400 dimensionId: dim,
391 401 respawnsAt: now + fishingExhaustDurationMs(fishRank)
392 402 });
393 403
@@ -595,10 +605,11 @@ export function stepFishingSpotRespawns (world, now)
595 605 if (now < entry.respawnsAt)
596 606 { continue; }
597 607 respawns.delete(key);
598 const block = blockAt(world, entry.tileX, entry.tileY);
608 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
609 const block = blockAt(world, entry.tileX, entry.tileY, dim);
599 610 if (!block || block.typeId !== BlockType.fishingSpot)
600 611 { continue; }
601 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot");
612 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot", dim);
602 613 if (delta)
603 614 { events.push(delta); }
604 615 }
@@ -44,6 +44,7 @@ import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
44import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
44import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
45import { tileToChunk, tileToLocal } from "../world/coordinates.js";
45import { tileToChunk, tileToLocal } from "../world/coordinates.js";
46import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
46import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
47import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
47import { tileShoveEvent } from "../simulation/tileInteract.js";
48import { tileShoveEvent } from "../simulation/tileInteract.js";
48import { seasonIdAt } from "../../../shared/world/season.js";
49import { seasonIdAt } from "../../../shared/world/season.js";
49
50
@@ -60,9 +61,10 @@ function userError (message)
60 return error;
61 return error;
61}
62}
62
63
63function tileKey (tileX, tileY)
64function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
64{
65{
65 return `${tileX},${tileY}`;
66 const dim = normalizeDimensionId(dimensionId);
67 return `${dim}:${tileX},${tileY}`;
66}
68}
67
69
68function characterDisplayName (world, handle)
70function characterDisplayName (world, handle)
@@ -91,27 +93,30 @@ function clearFishSession (world, characterId)
91 ensureFishSessions(world).delete(characterId);
93 ensureFishSessions(world).delete(characterId);
92}
94}
93
95
94function blockAt (world, tileX, tileY)
96function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
95{
97{
96 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
98 const dim = normalizeDimensionId(dimensionId);
99 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
97 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
100 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
98 return data.blocks[index] ?? null;
101 return data.blocks[index] ?? null;
99}
102}
100
103
101function groundAt (world, tileX, tileY)
104function groundAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
102{
105{
103 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
106 const dim = normalizeDimensionId(dimensionId);
107 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
104 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
108 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
105 return normalizeGround(data.grounds[index]).typeId;
109 return normalizeGround(data.grounds[index]).typeId;
106}
110}
107
111
108function setBlockState (world, tileX, tileY, state)
112function setBlockState (world, tileX, tileY, state, dimensionId = OVERWORLD_ID)
109{
113{
114 const dim = normalizeDimensionId(dimensionId);
110 const chunkX = tileToChunk(tileX);
115 const chunkX = tileToChunk(tileX);
111 const chunkY = tileToChunk(tileY);
116 const chunkY = tileToChunk(tileY);
112 const localX = tileToLocal(tileX);
117 const localX = tileToLocal(tileX);
113 const localY = tileToLocal(tileY);
118 const localY = tileToLocal(tileY);
114 const data = world.chunkData(chunkX, chunkY);
119 const data = world.chunkData(chunkX, chunkY, dim);
115 const index = localY * CHUNK_SIZE + localX;
120 const index = localY * CHUNK_SIZE + localX;
116 const existing = data.blocks[index];
121 const existing = data.blocks[index];
117 if (!existing)
122 if (!existing)
@@ -122,6 +127,7 @@ function setBlockState (world, tileX, tileY, state)
122 type: "chunk-delta",
127 type: "chunk-delta",
123 chunkX,
128 chunkX,
124 chunkY,
129 chunkY,
130 dimensionId: dim,
125 tileX,
131 tileX,
126 tileY,
132 tileY,
127 localX,
133 localX,
@@ -193,13 +199,14 @@ export function startFish (world, sessionId, characterId, tileX, tileY, now = Da
193 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
199 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
194 { throw userError("You need to stand next to the fishing spot."); }
200 { throw userError("You need to stand next to the fishing spot."); }
195
201
196 const block = blockAt(world, tileX, tileY);
202 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
203 const block = blockAt(world, tileX, tileY, dim);
197 if (!block || block.typeId !== BlockType.fishingSpot)
204 if (!block || block.typeId !== BlockType.fishingSpot)
198 { throw userError("There is no fishing spot there."); }
205 { throw userError("There is no fishing spot there."); }
199 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY)))
206 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY, dim)))
200 { throw userError("The fish have scattered. Wait for them to return."); }
207 { throw userError("The fish have scattered. Wait for them to return."); }
201
208
202 const ground = groundAt(world, tileX, tileY);
209 const ground = groundAt(world, tileX, tileY, dim);
203 const season = seasonIdAt(now);
210 const season = seasonIdAt(now);
204 if (ground !== GroundType.water && ground !== GroundType.deepWater)
211 if (ground !== GroundType.water && ground !== GroundType.deepWater)
205 { throw userError("Fishing spots must be on water."); }
212 { throw userError("Fishing spots must be on water."); }
@@ -272,6 +279,7 @@ export function startFish (world, sessionId, characterId, tileX, tileY, now = Da
272 sessionId,
279 sessionId,
273 tileX,
280 tileX,
274 tileY,
281 tileY,
282 dimensionId: dim,
275 toolItemId: resolved.tool.def.itemId,
283 toolItemId: resolved.tool.def.itemId,
276 isNet,
284 isNet,
277 baitRank,
285 baitRank,
@@ -382,12 +390,14 @@ function completeCatch (world, handle, entityId, characterId, session, events, p
382 });
390 });
383 }
391 }
384
392
385 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted");
393 const dim = normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID);
394 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted", dim);
386 if (exhausted)
395 if (exhausted)
387 { events.push(exhausted); }
396 { events.push(exhausted); }
388 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), {
397 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY, dim), {
389 tileX: session.tileX,
398 tileX: session.tileX,
390 tileY: session.tileY,
399 tileY: session.tileY,
400 dimensionId: dim,
391 respawnsAt: now + fishingExhaustDurationMs(fishRank)
401 respawnsAt: now + fishingExhaustDurationMs(fishRank)
392 });
402 });
393
403
@@ -595,10 +605,11 @@ export function stepFishingSpotRespawns (world, now)
595 if (now < entry.respawnsAt)
605 if (now < entry.respawnsAt)
596 { continue; }
606 { continue; }
597 respawns.delete(key);
607 respawns.delete(key);
598 const block = blockAt(world, entry.tileX, entry.tileY);
608 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
609 const block = blockAt(world, entry.tileX, entry.tileY, dim);
599 if (!block || block.typeId !== BlockType.fishingSpot)
610 if (!block || block.typeId !== BlockType.fishingSpot)
600 { continue; }
611 { continue; }
601 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot");
612 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot", dim);
602 if (delta)
613 if (delta)
603 { events.push(delta); }
614 { events.push(delta); }
604 }
615 }
server/src/gateway/websocket.js +9 −0
@@ -302,6 +302,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
302 302 characterId: session.characterId
303 303 });
304 304 break;
305 case MessageType.prayAtAltar:
306 requirePlaying(session);
307 simulation.enqueue(session.id, {
308 type: "pray-at-altar",
309 characterId: session.characterId,
310 tileX: message.tileX | 0,
311 tileY: message.tileY | 0
312 });
313 break;
305 314 case MessageType.enterDoorway:
306 315 requirePlaying(session);
307 316 simulation.enqueue(session.id, {
@@ -302,6 +302,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
302 characterId: session.characterId
302 characterId: session.characterId
303 });
303 });
304 break;
304 break;
305 case MessageType.prayAtAltar:
306 requirePlaying(session);
307 simulation.enqueue(session.id, {
308 type: "pray-at-altar",
309 characterId: session.characterId,
310 tileX: message.tileX | 0,
311 tileY: message.tileY | 0
312 });
313 break;
305 case MessageType.enterDoorway:
314 case MessageType.enterDoorway:
306 requirePlaying(session);
315 requirePlaying(session);
307 simulation.enqueue(session.id, {
316 simulation.enqueue(session.id, {
server/src/gathering/service.js +97 −35
@@ -58,8 +58,9 @@ import {
58 58 import { bagView, placeOrMergeGroundStack, publicGroundItem, removeGroundItem } from "../items/bags.js";
59 59 import { clearEngage } from "../combat/service.js";
60 60 import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
61 import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
61 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
62 62 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
63 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
63 64 import {
64 65 barkItemIdForWood,
65 66 debarkedLogInstance,
@@ -71,6 +72,28 @@ const GATHER_SWING_INTERVAL_MS = 900;
71 72 /** Fixed strip duration — short axe work on a felled log. */
72 73 export const DEBARK_DURATION_MS = 2000;
73 74
75 function respawnTileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
76 {
77 const dim = normalizeDimensionId(dimensionId);
78 return `${dim}:${tileX},${tileY}`;
79 }
80
81 function parseRespawnTileKey (key)
82 {
83 const raw = String(key ?? "");
84 const colon = raw.indexOf(":");
85 if (colon < 0)
86 {
87 const [tileX, tileY] = raw.split(",").map(Number);
88 return { dimensionId: OVERWORLD_ID, tileX, tileY };
89 }
90 return {
91 dimensionId: normalizeDimensionId(raw.slice(0, colon)),
92 tileX: Number(raw.slice(colon + 1).split(",")[0]),
93 tileY: Number(raw.slice(colon + 1).split(",")[1])
94 };
95 }
96
74 97 function userError (message)
75 98 {
76 99 const error = new Error(message);
@@ -106,19 +129,21 @@ function ensurePlantRespawns (world)
106 129 return world.plantRespawns;
107 130 }
108 131
109 function blockAt (world, tileX, tileY)
132 function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
110 133 {
111 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
134 const dim = normalizeDimensionId(dimensionId);
135 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
112 136 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
113 137 }
114 138
115 function setBlockState (world, tileX, tileY, typeId, state)
139 function setBlockState (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID)
116 140 {
141 const dim = normalizeDimensionId(dimensionId);
117 142 const chunkX = tileToChunk(tileX);
118 143 const chunkY = tileToChunk(tileY);
119 144 const localX = tileToLocal(tileX);
120 145 const localY = tileToLocal(tileY);
121 const data = world.chunkData(chunkX, chunkY);
146 const data = world.chunkData(chunkX, chunkY, dim);
122 147 const index = localY * CHUNK_SIZE + localX;
123 148 const prev = data?.blocks?.[index];
124 149 if (!prev || prev.typeId !== typeId)
@@ -129,6 +154,7 @@ function setBlockState (world, tileX, tileY, typeId, state)
129 154 type: "chunk-delta",
130 155 chunkX,
131 156 chunkY,
157 dimensionId: dim,
132 158 tileX,
133 159 tileY,
134 160 localX,
@@ -137,23 +163,24 @@ function setBlockState (world, tileX, tileY, typeId, state)
137 163 };
138 164 }
139 165
140 function setBoulderState (world, tileX, tileY, state)
166 function setBoulderState (world, tileX, tileY, state, dimensionId = OVERWORLD_ID)
141 167 {
142 return setBlockState(world, tileX, tileY, BlockType.boulder, state);
168 return setBlockState(world, tileX, tileY, BlockType.boulder, state, dimensionId);
143 169 }
144 170
145 function setTreeState (world, tileX, tileY, typeId, state)
171 function setTreeState (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID)
146 172 {
147 return setBlockState(world, tileX, tileY, typeId, state);
173 return setBlockState(world, tileX, tileY, typeId, state, dimensionId);
148 174 }
149 175
150 function clearBlock (world, tileX, tileY, typeId)
176 function clearBlock (world, tileX, tileY, typeId, dimensionId = OVERWORLD_ID)
151 177 {
178 const dim = normalizeDimensionId(dimensionId);
152 179 const chunkX = tileToChunk(tileX);
153 180 const chunkY = tileToChunk(tileY);
154 181 const localX = tileToLocal(tileX);
155 182 const localY = tileToLocal(tileY);
156 const data = world.chunkData(chunkX, chunkY);
183 const data = world.chunkData(chunkX, chunkY, dim);
157 184 const index = localY * CHUNK_SIZE + localX;
158 185 const prev = data?.blocks?.[index];
159 186 if (!prev || prev.typeId !== typeId)
@@ -163,6 +190,7 @@ function clearBlock (world, tileX, tileY, typeId)
163 190 type: "chunk-delta",
164 191 chunkX,
165 192 chunkY,
193 dimensionId: dim,
166 194 tileX,
167 195 tileY,
168 196 localX,
@@ -171,13 +199,14 @@ function clearBlock (world, tileX, tileY, typeId)
171 199 };
172 200 }
173 201
174 function placeBlock (world, tileX, tileY, typeId, state)
202 function placeBlock (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID)
175 203 {
204 const dim = normalizeDimensionId(dimensionId);
176 205 const chunkX = tileToChunk(tileX);
177 206 const chunkY = tileToChunk(tileY);
178 207 const localX = tileToLocal(tileX);
179 208 const localY = tileToLocal(tileY);
180 const data = world.chunkData(chunkX, chunkY);
209 const data = world.chunkData(chunkX, chunkY, dim);
181 210 const index = localY * CHUNK_SIZE + localX;
182 211 const block = { typeId, state, config: null };
183 212 data.blocks[index] = block;
@@ -185,6 +214,7 @@ function placeBlock (world, tileX, tileY, typeId, state)
185 214 type: "chunk-delta",
186 215 chunkX,
187 216 chunkY,
217 dimensionId: dim,
188 218 tileX,
189 219 tileY,
190 220 localX,
@@ -231,41 +261,50 @@ export function cancelGather (ecs, handle)
231 261 }
232 262
233 263 /** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
234 export function clearOreRespawnsForChunk (world, chunkX, chunkY)
264 export function clearOreRespawnsForChunk (world, chunkX, chunkY, dimensionId = null)
235 265 {
236 266 const respawns = world.oreRespawns;
237 267 if (!respawns?.size)
238 268 { return; }
269 const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
239 270 for (const key of [...respawns.keys()])
240 271 {
241 const [tileX, tileY] = key.split(",").map(Number);
272 const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key);
273 if (dimFilter != null && keyDim !== dimFilter)
274 { continue; }
242 275 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
243 276 { respawns.delete(key); }
244 277 }
245 278 }
246 279
247 280 /** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */
248 export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
281 export function clearTreeRespawnsForChunk (world, chunkX, chunkY, dimensionId = null)
249 282 {
250 283 const respawns = world.treeRespawns;
251 284 if (!respawns?.size)
252 285 { return; }
286 const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
253 287 for (const key of [...respawns.keys()])
254 288 {
255 const [tileX, tileY] = key.split(",").map(Number);
289 const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key);
290 if (dimFilter != null && keyDim !== dimFilter)
291 { continue; }
256 292 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
257 293 { respawns.delete(key); }
258 294 }
259 295 }
260 296
261 export function clearPlantRespawnsForChunk (world, chunkX, chunkY)
297 export function clearPlantRespawnsForChunk (world, chunkX, chunkY, dimensionId = null)
262 298 {
263 299 const respawns = world.plantRespawns;
264 300 if (!respawns?.size)
265 301 { return; }
302 const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
266 303 for (const key of [...respawns.keys()])
267 304 {
268 const [tileX, tileY] = key.split(",").map(Number);
305 const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key);
306 if (dimFilter != null && keyDim !== dimFilter)
307 { continue; }
269 308 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
270 309 { respawns.delete(key); }
271 310 }
@@ -285,7 +324,8 @@ export function stepOreRespawns (world, now)
285 324 if (now < entry.respawnsAt)
286 325 { continue; }
287 326 respawns.delete(key);
288 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
327 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
328 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId), dim);
289 329 if (delta)
290 330 { events.push(delta); }
291 331 }
@@ -306,12 +346,14 @@ export function stepTreeRespawns (world, now)
306 346 if (now < entry.respawnsAt)
307 347 { continue; }
308 348 respawns.delete(key);
349 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
309 350 const delta = setTreeState(
310 351 world,
311 352 entry.tileX,
312 353 entry.tileY,
313 354 entry.typeId,
314 SeasonId.summer
355 SeasonId.summer,
356 dim
315 357 );
316 358 if (delta)
317 359 { events.push(delta); }
@@ -330,13 +372,14 @@ export function stepPlantRespawns (world, now)
330 372 if (now < entry.respawnsAt)
331 373 { continue; }
332 374 respawns.delete(key);
333 const existing = blockAt(world, entry.tileX, entry.tileY);
375 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
376 const existing = blockAt(world, entry.tileX, entry.tileY, dim);
334 377 if (existing)
335 378 { continue; }
336 379 const state = entry.typeId === BlockType.flower
337 380 ? flowerBlockState(randomFlowerColorId())
338 381 : (entry.state ?? defaultPlantState(entry.typeId));
339 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
382 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state, dim);
340 383 if (delta)
341 384 { events.push(delta); }
342 385 }
@@ -351,6 +394,7 @@ function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
351 394 { path.tiles = []; }
352 395 world.ecs.add(handle, Component.gather, {
353 396 ...gatherFields,
397 dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID),
354 398 startedAt: now,
355 399 finishesAt: now + gatherFields.durationMs,
356 400 nextSwingAt: now
@@ -388,7 +432,8 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
388 432 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
389 433 { throw userError("You need to stand next to the rock."); }
390 434
391 const block = blockAt(world, tileX, tileY);
435 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
436 const block = blockAt(world, tileX, tileY, dim);
392 437 if (!block || block.typeId !== BlockType.boulder)
393 438 { throw userError("There is nothing to mine there."); }
394 439 const materialId = materialFromOreBoulderState(block.state);
@@ -439,7 +484,8 @@ export function startChop (world, sessionId, characterId, tileX, tileY, now)
439 484 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
440 485 { throw userError("You need to stand next to the tree."); }
441 486
442 const block = blockAt(world, tileX, tileY);
487 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
488 const block = blockAt(world, tileX, tileY, dim);
443 489 if (!isChopableTreeBlock(block))
444 490 {
445 491 throw userError(block && woodTierForTreeBlock(block.typeId) != null
@@ -567,7 +613,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
567 613 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
568 614 { throw userError("You need to stand next to the plant."); }
569 615
570 const block = blockAt(world, tileX, tileY);
616 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
617 const block = blockAt(world, tileX, tileY, dim);
571 618 const plant = plantGatherForBlock(block);
572 619 if (!plant)
573 620 { throw userError("There is nothing to pick there."); }
@@ -617,7 +664,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
617 664 tileX,
618 665 tileY,
619 666 BlockType.flower,
620 flowerBlockState(flowerColorId)
667 flowerBlockState(flowerColorId),
668 dim
621 669 );
622 670 if (delta)
623 671 { prefixEvents.push(delta); }
@@ -712,14 +760,17 @@ function completeMining (world, handle, entityId, character, gather, events, pri
712 760 world,
713 761 gather.tileX,
714 762 gather.tileY,
715 EXHAUSTED_ORE_BOULDER_STATE
763 EXHAUSTED_ORE_BOULDER_STATE,
764 normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID)
716 765 );
717 766 if (exhausted)
718 767 {
719 768 events.push(exhausted);
720 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
769 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
770 ensureOreRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), {
721 771 tileX: gather.tileX,
722 772 tileY: gather.tileY,
773 dimensionId: dim,
723 774 materialId: gather.materialId,
724 775 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
725 776 });
@@ -784,19 +835,22 @@ function completeWoodcutting (world, handle, entityId, character, gather, events
784 835 }
785 836
786 837 const stumpState = treeStumpStateForSeason(seasonIdAt(now));
838 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
787 839 const exhausted = setTreeState(
788 840 world,
789 841 gather.tileX,
790 842 gather.tileY,
791 843 gather.typeId,
792 stumpState
844 stumpState,
845 dim
793 846 );
794 847 if (exhausted)
795 848 {
796 849 events.push(exhausted);
797 ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
850 ensureTreeRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), {
798 851 tileX: gather.tileX,
799 852 tileY: gather.tileY,
853 dimensionId: dim,
800 854 typeId: gather.typeId,
801 855 woodTier: gather.woodTier,
802 856 respawnsAt: now + scaleRegrowDurationMs(treeExhaustDurationMs(gather.woodTier), now)
@@ -930,7 +984,8 @@ function completePlant (world, handle, entityId, character, gather, events, priv
930 984 if (gather.plantKind === "flower")
931 985 {
932 986 itemId = ItemId.flower;
933 const live = blockAt(world, gather.tileX, gather.tileY);
987 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
988 const live = blockAt(world, gather.tileX, gather.tileY, dim);
934 989 const colorId = gather.flowerColorId
935 990 ?? flowerColorIdFromBlockState(live?.state)
936 991 ?? randomFlowerColorId();
@@ -1004,12 +1059,14 @@ function completePlant (world, handle, entityId, character, gather, events, priv
1004 1059 { levelUps.push(result.levelUp); }
1005 1060 }
1006 1061
1007 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
1062 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
1063 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId, dim);
1008 1064 if (delta)
1009 1065 { events.push(delta); }
1010 ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
1066 ensurePlantRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), {
1011 1067 tileX: gather.tileX,
1012 1068 tileY: gather.tileY,
1069 dimensionId: dim,
1013 1070 typeId: gather.typeId,
1014 1071 // Colour is chosen when the node refreshes (see stepPlantRespawns).
1015 1072 state: gather.plantKind === "flower"
@@ -1055,7 +1112,12 @@ export function stepGather (world, now)
1055 1112 clearGather(world.ecs, handle);
1056 1113 continue;
1057 1114 }
1058 const block = blockAt(world, gather.tileX, gather.tileY);
1115 const block = blockAt(
1116 world,
1117 gather.tileX,
1118 gather.tileY,
1119 normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID)
1120 );
1059 1121
1060 1122 if (gather.kind === "mining")
1061 1123 {
@@ -58,8 +58,9 @@ import {
58import { bagView, placeOrMergeGroundStack, publicGroundItem, removeGroundItem } from "../items/bags.js";
58import { bagView, placeOrMergeGroundStack, publicGroundItem, removeGroundItem } from "../items/bags.js";
59import { clearEngage } from "../combat/service.js";
59import { clearEngage } from "../combat/service.js";
60import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
60import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
61import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
61import { tileToChunk, tileToLocal } from "../world/coordinates.js";
62import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
62import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
63import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
63import {
64import {
64 barkItemIdForWood,
65 barkItemIdForWood,
65 debarkedLogInstance,
66 debarkedLogInstance,
@@ -71,6 +72,28 @@ const GATHER_SWING_INTERVAL_MS = 900;
71/** Fixed strip duration — short axe work on a felled log. */
72/** Fixed strip duration — short axe work on a felled log. */
72export const DEBARK_DURATION_MS = 2000;
73export const DEBARK_DURATION_MS = 2000;
73
74
75function respawnTileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
76{
77 const dim = normalizeDimensionId(dimensionId);
78 return `${dim}:${tileX},${tileY}`;
79}
80
81function parseRespawnTileKey (key)
82{
83 const raw = String(key ?? "");
84 const colon = raw.indexOf(":");
85 if (colon < 0)
86 {
87 const [tileX, tileY] = raw.split(",").map(Number);
88 return { dimensionId: OVERWORLD_ID, tileX, tileY };
89 }
90 return {
91 dimensionId: normalizeDimensionId(raw.slice(0, colon)),
92 tileX: Number(raw.slice(colon + 1).split(",")[0]),
93 tileY: Number(raw.slice(colon + 1).split(",")[1])
94 };
95}
96
74function userError (message)
97function userError (message)
75{
98{
76 const error = new Error(message);
99 const error = new Error(message);
@@ -106,19 +129,21 @@ function ensurePlantRespawns (world)
106 return world.plantRespawns;
129 return world.plantRespawns;
107}
130}
108
131
109function blockAt (world, tileX, tileY)
132function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
110{
133{
111 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
134 const dim = normalizeDimensionId(dimensionId);
135 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
112 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
136 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
113}
137}
114
138
115function setBlockState (world, tileX, tileY, typeId, state)
139function setBlockState (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID)
116{
140{
141 const dim = normalizeDimensionId(dimensionId);
117 const chunkX = tileToChunk(tileX);
142 const chunkX = tileToChunk(tileX);
118 const chunkY = tileToChunk(tileY);
143 const chunkY = tileToChunk(tileY);
119 const localX = tileToLocal(tileX);
144 const localX = tileToLocal(tileX);
120 const localY = tileToLocal(tileY);
145 const localY = tileToLocal(tileY);
121 const data = world.chunkData(chunkX, chunkY);
146 const data = world.chunkData(chunkX, chunkY, dim);
122 const index = localY * CHUNK_SIZE + localX;
147 const index = localY * CHUNK_SIZE + localX;
123 const prev = data?.blocks?.[index];
148 const prev = data?.blocks?.[index];
124 if (!prev || prev.typeId !== typeId)
149 if (!prev || prev.typeId !== typeId)
@@ -129,6 +154,7 @@ function setBlockState (world, tileX, tileY, typeId, state)
129 type: "chunk-delta",
154 type: "chunk-delta",
130 chunkX,
155 chunkX,
131 chunkY,
156 chunkY,
157 dimensionId: dim,
132 tileX,
158 tileX,
133 tileY,
159 tileY,
134 localX,
160 localX,
@@ -137,23 +163,24 @@ function setBlockState (world, tileX, tileY, typeId, state)
137 };
163 };
138}
164}
139
165
140function setBoulderState (world, tileX, tileY, state)
166function setBoulderState (world, tileX, tileY, state, dimensionId = OVERWORLD_ID)
141{
167{
142 return setBlockState(world, tileX, tileY, BlockType.boulder, state);
168 return setBlockState(world, tileX, tileY, BlockType.boulder, state, dimensionId);
143}
169}
144
170
145function setTreeState (world, tileX, tileY, typeId, state)
171function setTreeState (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID)
146{
172{
147 return setBlockState(world, tileX, tileY, typeId, state);
173 return setBlockState(world, tileX, tileY, typeId, state, dimensionId);
148}
174}
149
175
150function clearBlock (world, tileX, tileY, typeId)
176function clearBlock (world, tileX, tileY, typeId, dimensionId = OVERWORLD_ID)
151{
177{
178 const dim = normalizeDimensionId(dimensionId);
152 const chunkX = tileToChunk(tileX);
179 const chunkX = tileToChunk(tileX);
153 const chunkY = tileToChunk(tileY);
180 const chunkY = tileToChunk(tileY);
154 const localX = tileToLocal(tileX);
181 const localX = tileToLocal(tileX);
155 const localY = tileToLocal(tileY);
182 const localY = tileToLocal(tileY);
156 const data = world.chunkData(chunkX, chunkY);
183 const data = world.chunkData(chunkX, chunkY, dim);
157 const index = localY * CHUNK_SIZE + localX;
184 const index = localY * CHUNK_SIZE + localX;
158 const prev = data?.blocks?.[index];
185 const prev = data?.blocks?.[index];
159 if (!prev || prev.typeId !== typeId)
186 if (!prev || prev.typeId !== typeId)
@@ -163,6 +190,7 @@ function clearBlock (world, tileX, tileY, typeId)
163 type: "chunk-delta",
190 type: "chunk-delta",
164 chunkX,
191 chunkX,
165 chunkY,
192 chunkY,
193 dimensionId: dim,
166 tileX,
194 tileX,
167 tileY,
195 tileY,
168 localX,
196 localX,
@@ -171,13 +199,14 @@ function clearBlock (world, tileX, tileY, typeId)
171 };
199 };
172}
200}
173
201
174function placeBlock (world, tileX, tileY, typeId, state)
202function placeBlock (world, tileX, tileY, typeId, state, dimensionId = OVERWORLD_ID)
175{
203{
204 const dim = normalizeDimensionId(dimensionId);
176 const chunkX = tileToChunk(tileX);
205 const chunkX = tileToChunk(tileX);
177 const chunkY = tileToChunk(tileY);
206 const chunkY = tileToChunk(tileY);
178 const localX = tileToLocal(tileX);
207 const localX = tileToLocal(tileX);
179 const localY = tileToLocal(tileY);
208 const localY = tileToLocal(tileY);
180 const data = world.chunkData(chunkX, chunkY);
209 const data = world.chunkData(chunkX, chunkY, dim);
181 const index = localY * CHUNK_SIZE + localX;
210 const index = localY * CHUNK_SIZE + localX;
182 const block = { typeId, state, config: null };
211 const block = { typeId, state, config: null };
183 data.blocks[index] = block;
212 data.blocks[index] = block;
@@ -185,6 +214,7 @@ function placeBlock (world, tileX, tileY, typeId, state)
185 type: "chunk-delta",
214 type: "chunk-delta",
186 chunkX,
215 chunkX,
187 chunkY,
216 chunkY,
217 dimensionId: dim,
188 tileX,
218 tileX,
189 tileY,
219 tileY,
190 localX,
220 localX,
@@ -231,41 +261,50 @@ export function cancelGather (ecs, handle)
231}
261}
232
262
233/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
263/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
234export function clearOreRespawnsForChunk (world, chunkX, chunkY)
264export function clearOreRespawnsForChunk (world, chunkX, chunkY, dimensionId = null)
235{
265{
236 const respawns = world.oreRespawns;
266 const respawns = world.oreRespawns;
237 if (!respawns?.size)
267 if (!respawns?.size)
238 { return; }
268 { return; }
269 const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
239 for (const key of [...respawns.keys()])
270 for (const key of [...respawns.keys()])
240 {
271 {
241 const [tileX, tileY] = key.split(",").map(Number);
272 const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key);
273 if (dimFilter != null && keyDim !== dimFilter)
274 { continue; }
242 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
275 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
243 { respawns.delete(key); }
276 { respawns.delete(key); }
244 }
277 }
245}
278}
246
279
247/** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */
280/** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */
248export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
281export function clearTreeRespawnsForChunk (world, chunkX, chunkY, dimensionId = null)
249{
282{
250 const respawns = world.treeRespawns;
283 const respawns = world.treeRespawns;
251 if (!respawns?.size)
284 if (!respawns?.size)
252 { return; }
285 { return; }
286 const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
253 for (const key of [...respawns.keys()])
287 for (const key of [...respawns.keys()])
254 {
288 {
255 const [tileX, tileY] = key.split(",").map(Number);
289 const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key);
290 if (dimFilter != null && keyDim !== dimFilter)
291 { continue; }
256 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
292 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
257 { respawns.delete(key); }
293 { respawns.delete(key); }
258 }
294 }
259}
295}
260
296
261export function clearPlantRespawnsForChunk (world, chunkX, chunkY)
297export function clearPlantRespawnsForChunk (world, chunkX, chunkY, dimensionId = null)
262{
298{
263 const respawns = world.plantRespawns;
299 const respawns = world.plantRespawns;
264 if (!respawns?.size)
300 if (!respawns?.size)
265 { return; }
301 { return; }
302 const dimFilter = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
266 for (const key of [...respawns.keys()])
303 for (const key of [...respawns.keys()])
267 {
304 {
268 const [tileX, tileY] = key.split(",").map(Number);
305 const { dimensionId: keyDim, tileX, tileY } = parseRespawnTileKey(key);
306 if (dimFilter != null && keyDim !== dimFilter)
307 { continue; }
269 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
308 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
270 { respawns.delete(key); }
309 { respawns.delete(key); }
271 }
310 }
@@ -285,7 +324,8 @@ export function stepOreRespawns (world, now)
285 if (now < entry.respawnsAt)
324 if (now < entry.respawnsAt)
286 { continue; }
325 { continue; }
287 respawns.delete(key);
326 respawns.delete(key);
288 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
327 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
328 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId), dim);
289 if (delta)
329 if (delta)
290 { events.push(delta); }
330 { events.push(delta); }
291 }
331 }
@@ -306,12 +346,14 @@ export function stepTreeRespawns (world, now)
306 if (now < entry.respawnsAt)
346 if (now < entry.respawnsAt)
307 { continue; }
347 { continue; }
308 respawns.delete(key);
348 respawns.delete(key);
349 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
309 const delta = setTreeState(
350 const delta = setTreeState(
310 world,
351 world,
311 entry.tileX,
352 entry.tileX,
312 entry.tileY,
353 entry.tileY,
313 entry.typeId,
354 entry.typeId,
314 SeasonId.summer
355 SeasonId.summer,
356 dim
315 );
357 );
316 if (delta)
358 if (delta)
317 { events.push(delta); }
359 { events.push(delta); }
@@ -330,13 +372,14 @@ export function stepPlantRespawns (world, now)
330 if (now < entry.respawnsAt)
372 if (now < entry.respawnsAt)
331 { continue; }
373 { continue; }
332 respawns.delete(key);
374 respawns.delete(key);
333 const existing = blockAt(world, entry.tileX, entry.tileY);
375 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
376 const existing = blockAt(world, entry.tileX, entry.tileY, dim);
334 if (existing)
377 if (existing)
335 { continue; }
378 { continue; }
336 const state = entry.typeId === BlockType.flower
379 const state = entry.typeId === BlockType.flower
337 ? flowerBlockState(randomFlowerColorId())
380 ? flowerBlockState(randomFlowerColorId())
338 : (entry.state ?? defaultPlantState(entry.typeId));
381 : (entry.state ?? defaultPlantState(entry.typeId));
339 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
382 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state, dim);
340 if (delta)
383 if (delta)
341 { events.push(delta); }
384 { events.push(delta); }
342 }
385 }
@@ -351,6 +394,7 @@ function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
351 { path.tiles = []; }
394 { path.tiles = []; }
352 world.ecs.add(handle, Component.gather, {
395 world.ecs.add(handle, Component.gather, {
353 ...gatherFields,
396 ...gatherFields,
397 dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID),
354 startedAt: now,
398 startedAt: now,
355 finishesAt: now + gatherFields.durationMs,
399 finishesAt: now + gatherFields.durationMs,
356 nextSwingAt: now
400 nextSwingAt: now
@@ -388,7 +432,8 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
388 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
432 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
389 { throw userError("You need to stand next to the rock."); }
433 { throw userError("You need to stand next to the rock."); }
390
434
391 const block = blockAt(world, tileX, tileY);
435 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
436 const block = blockAt(world, tileX, tileY, dim);
392 if (!block || block.typeId !== BlockType.boulder)
437 if (!block || block.typeId !== BlockType.boulder)
393 { throw userError("There is nothing to mine there."); }
438 { throw userError("There is nothing to mine there."); }
394 const materialId = materialFromOreBoulderState(block.state);
439 const materialId = materialFromOreBoulderState(block.state);
@@ -439,7 +484,8 @@ export function startChop (world, sessionId, characterId, tileX, tileY, now)
439 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
484 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
440 { throw userError("You need to stand next to the tree."); }
485 { throw userError("You need to stand next to the tree."); }
441
486
442 const block = blockAt(world, tileX, tileY);
487 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
488 const block = blockAt(world, tileX, tileY, dim);
443 if (!isChopableTreeBlock(block))
489 if (!isChopableTreeBlock(block))
444 {
490 {
445 throw userError(block && woodTierForTreeBlock(block.typeId) != null
491 throw userError(block && woodTierForTreeBlock(block.typeId) != null
@@ -567,7 +613,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
567 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
613 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
568 { throw userError("You need to stand next to the plant."); }
614 { throw userError("You need to stand next to the plant."); }
569
615
570 const block = blockAt(world, tileX, tileY);
616 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
617 const block = blockAt(world, tileX, tileY, dim);
571 const plant = plantGatherForBlock(block);
618 const plant = plantGatherForBlock(block);
572 if (!plant)
619 if (!plant)
573 { throw userError("There is nothing to pick there."); }
620 { throw userError("There is nothing to pick there."); }
@@ -617,7 +664,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
617 tileX,
664 tileX,
618 tileY,
665 tileY,
619 BlockType.flower,
666 BlockType.flower,
620 flowerBlockState(flowerColorId)
667 flowerBlockState(flowerColorId),
668 dim
621 );
669 );
622 if (delta)
670 if (delta)
623 { prefixEvents.push(delta); }
671 { prefixEvents.push(delta); }
@@ -712,14 +760,17 @@ function completeMining (world, handle, entityId, character, gather, events, pri
712 world,
760 world,
713 gather.tileX,
761 gather.tileX,
714 gather.tileY,
762 gather.tileY,
715 EXHAUSTED_ORE_BOULDER_STATE
763 EXHAUSTED_ORE_BOULDER_STATE,
764 normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID)
716 );
765 );
717 if (exhausted)
766 if (exhausted)
718 {
767 {
719 events.push(exhausted);
768 events.push(exhausted);
720 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
769 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
770 ensureOreRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), {
721 tileX: gather.tileX,
771 tileX: gather.tileX,
722 tileY: gather.tileY,
772 tileY: gather.tileY,
773 dimensionId: dim,
723 materialId: gather.materialId,
774 materialId: gather.materialId,
724 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
775 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
725 });
776 });
@@ -784,19 +835,22 @@ function completeWoodcutting (world, handle, entityId, character, gather, events
784 }
835 }
785
836
786 const stumpState = treeStumpStateForSeason(seasonIdAt(now));
837 const stumpState = treeStumpStateForSeason(seasonIdAt(now));
838 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
787 const exhausted = setTreeState(
839 const exhausted = setTreeState(
788 world,
840 world,
789 gather.tileX,
841 gather.tileX,
790 gather.tileY,
842 gather.tileY,
791 gather.typeId,
843 gather.typeId,
792 stumpState
844 stumpState,
845 dim
793 );
846 );
794 if (exhausted)
847 if (exhausted)
795 {
848 {
796 events.push(exhausted);
849 events.push(exhausted);
797 ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
850 ensureTreeRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), {
798 tileX: gather.tileX,
851 tileX: gather.tileX,
799 tileY: gather.tileY,
852 tileY: gather.tileY,
853 dimensionId: dim,
800 typeId: gather.typeId,
854 typeId: gather.typeId,
801 woodTier: gather.woodTier,
855 woodTier: gather.woodTier,
802 respawnsAt: now + scaleRegrowDurationMs(treeExhaustDurationMs(gather.woodTier), now)
856 respawnsAt: now + scaleRegrowDurationMs(treeExhaustDurationMs(gather.woodTier), now)
@@ -930,7 +984,8 @@ function completePlant (world, handle, entityId, character, gather, events, priv
930 if (gather.plantKind === "flower")
984 if (gather.plantKind === "flower")
931 {
985 {
932 itemId = ItemId.flower;
986 itemId = ItemId.flower;
933 const live = blockAt(world, gather.tileX, gather.tileY);
987 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
988 const live = blockAt(world, gather.tileX, gather.tileY, dim);
934 const colorId = gather.flowerColorId
989 const colorId = gather.flowerColorId
935 ?? flowerColorIdFromBlockState(live?.state)
990 ?? flowerColorIdFromBlockState(live?.state)
936 ?? randomFlowerColorId();
991 ?? randomFlowerColorId();
@@ -1004,12 +1059,14 @@ function completePlant (world, handle, entityId, character, gather, events, priv
1004 { levelUps.push(result.levelUp); }
1059 { levelUps.push(result.levelUp); }
1005 }
1060 }
1006
1061
1007 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
1062 const dim = normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID);
1063 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId, dim);
1008 if (delta)
1064 if (delta)
1009 { events.push(delta); }
1065 { events.push(delta); }
1010 ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
1066 ensurePlantRespawns(world).set(respawnTileKey(gather.tileX, gather.tileY, dim), {
1011 tileX: gather.tileX,
1067 tileX: gather.tileX,
1012 tileY: gather.tileY,
1068 tileY: gather.tileY,
1069 dimensionId: dim,
1013 typeId: gather.typeId,
1070 typeId: gather.typeId,
1014 // Colour is chosen when the node refreshes (see stepPlantRespawns).
1071 // Colour is chosen when the node refreshes (see stepPlantRespawns).
1015 state: gather.plantKind === "flower"
1072 state: gather.plantKind === "flower"
@@ -1055,7 +1112,12 @@ export function stepGather (world, now)
1055 clearGather(world.ecs, handle);
1112 clearGather(world.ecs, handle);
1056 continue;
1113 continue;
1057 }
1114 }
1058 const block = blockAt(world, gather.tileX, gather.tileY);
1115 const block = blockAt(
1116 world,
1117 gather.tileX,
1118 gather.tileY,
1119 normalizeDimensionId(gather.dimensionId ?? OVERWORLD_ID)
1120 );
1059
1121
1060 if (gather.kind === "mining")
1122 if (gather.kind === "mining")
1061 {
1123 {
server/src/items/bags.js +8 −4
@@ -28,6 +28,7 @@ import
28 28 } from "../../../shared/items/inventory.js";
29 29 import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
30 30 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
31 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
31 32 import { randomUUID } from "node:crypto";
32 33 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
33 34 import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js";
@@ -816,7 +817,8 @@ function openBank (world, sessionId, command)
816 817 {
817 818 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
818 819 const position = world.ecs.get(handle, Component.position);
819 if (!nearBank(world, position.tileX, position.tileY))
820 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
821 if (!nearBank(world, position.tileX, position.tileY, dim))
820 822 { throw userError("Stand next to a bank."); }
821 823 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);
822 824 return {
@@ -1189,19 +1191,21 @@ function normalizeLetterBody (raw)
1189 1191 function requireBank (world, handle)
1190 1192 {
1191 1193 const position = world.ecs.get(handle, Component.position);
1192 if (!nearBank(world, position.tileX, position.tileY))
1194 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1195 if (!nearBank(world, position.tileX, position.tileY, dim))
1193 1196 { throw userError("Stand next to a bank."); }
1194 1197 }
1195 1198
1196 function nearBank (world, tileX, tileY)
1199 function nearBank (world, tileX, tileY, dimensionId = OVERWORLD_ID)
1197 1200 {
1201 const dim = normalizeDimensionId(dimensionId);
1198 1202 for (let dy = -1; dy <= 1; dy++)
1199 1203 {
1200 1204 for (let dx = -1; dx <= 1; dx++)
1201 1205 {
1202 1206 if (dx === 0 && dy === 0)
1203 1207 { continue; }
1204 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
1208 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim);
1205 1209 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
1206 1210 if (data.blocks[index]?.typeId === BlockType.bank)
1207 1211 { return true; }
@@ -28,6 +28,7 @@ import
28 } from "../../../shared/items/inventory.js";
28 } from "../../../shared/items/inventory.js";
29import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
29import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
30import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
30import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
31import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
31import { randomUUID } from "node:crypto";
32import { randomUUID } from "node:crypto";
32import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
33import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
33import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js";
34import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js";
@@ -816,7 +817,8 @@ function openBank (world, sessionId, command)
816{
817{
817 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
818 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
818 const position = world.ecs.get(handle, Component.position);
819 const position = world.ecs.get(handle, Component.position);
819 if (!nearBank(world, position.tileX, position.tileY))
820 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
821 if (!nearBank(world, position.tileX, position.tileY, dim))
820 { throw userError("Stand next to a bank."); }
822 { throw userError("Stand next to a bank."); }
821 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);
823 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);
822 return {
824 return {
@@ -1189,19 +1191,21 @@ function normalizeLetterBody (raw)
1189function requireBank (world, handle)
1191function requireBank (world, handle)
1190{
1192{
1191 const position = world.ecs.get(handle, Component.position);
1193 const position = world.ecs.get(handle, Component.position);
1192 if (!nearBank(world, position.tileX, position.tileY))
1194 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1195 if (!nearBank(world, position.tileX, position.tileY, dim))
1193 { throw userError("Stand next to a bank."); }
1196 { throw userError("Stand next to a bank."); }
1194}
1197}
1195
1198
1196function nearBank (world, tileX, tileY)
1199function nearBank (world, tileX, tileY, dimensionId = OVERWORLD_ID)
1197{
1200{
1201 const dim = normalizeDimensionId(dimensionId);
1198 for (let dy = -1; dy <= 1; dy++)
1202 for (let dy = -1; dy <= 1; dy++)
1199 {
1203 {
1200 for (let dx = -1; dx <= 1; dx++)
1204 for (let dx = -1; dx <= 1; dx++)
1201 {
1205 {
1202 if (dx === 0 && dy === 0)
1206 if (dx === 0 && dy === 0)
1203 { continue; }
1207 { continue; }
1204 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
1208 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim);
1205 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
1209 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
1206 if (data.blocks[index]?.typeId === BlockType.bank)
1210 if (data.blocks[index]?.typeId === BlockType.bank)
1207 { return true; }
1211 { return true; }
server/src/market/service.js +51 −18
@@ -36,6 +36,7 @@ import {
36 36 } from "../../../shared/market/listingKey.js";
37 37 import { decodeChunkBlob } from "../world/chunkData.js";
38 38 import { withTransaction } from "../persistence/database.js";
39 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
39 40
40 41 function userError (message)
41 42 {
@@ -56,8 +57,8 @@ export class MarketService
56 57 this.marketTiles = [];
57 58 /**
58 59 * Players holding a CE UI open at a staff station.
59 * key `${stationTileX},${stationTileY}` →
60 * { stationTileX, stationTileY, marketTileX, marketTileY, browsers: Map<characterId, sessionId> }
60 * key `${dimensionId}:${stationTileX},${stationTileY}` →
61 * { stationTileX, stationTileY, marketTileX, marketTileY, dimensionId, browsers: Map<characterId, sessionId> }
61 62 * @type {Map<string, object>}
62 63 */
63 64 this.stationAttendance = new Map();
@@ -74,7 +75,8 @@ export class MarketService
74 75 const tiles = [];
75 76 for (const coord of this.worldDb.listChunkCoords(revisionId))
76 77 {
77 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
78 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
79 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim);
78 80 if (!row)
79 81 { continue; }
80 82 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
@@ -87,7 +89,8 @@ export class MarketService
87 89 { continue; }
88 90 tiles.push({
89 91 tileX: coord.chunk_x * CHUNK_SIZE + localX,
90 tileY: coord.chunk_y * CHUNK_SIZE + localY
92 tileY: coord.chunk_y * CHUNK_SIZE + localY,
93 dimensionId: dim
91 94 });
92 95 }
93 96 }
@@ -95,14 +98,17 @@ export class MarketService
95 98 this.marketTiles = tiles;
96 99 }
97 100
98 nearestMarket (tileX, tileY)
101 nearestMarket (tileX, tileY, dimensionId = null)
99 102 {
100 103 if (!this.marketTiles.length)
101 104 { return null; }
105 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
102 106 let best = null;
103 107 let bestDist = Infinity;
104 108 for (const tile of this.marketTiles)
105 109 {
110 if (dim != null && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
111 { continue; }
106 112 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
107 113 if (dist < bestDist)
108 114 {
@@ -182,7 +188,8 @@ export class MarketService
182 188 openMarket (sessionId, characterId, now = Date.now())
183 189 {
184 190 const { position } = this.#requireAtMarket(characterId);
185 this.#attendStations(sessionId, characterId, position.tileX, position.tileY);
191 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
192 this.#attendStations(sessionId, characterId, position.tileX, position.tileY, dim);
186 193 return {
187 194 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
188 195 };
@@ -772,18 +779,23 @@ export class MarketService
772 779 { throw userError("Enter the world before using the Central Exchange."); }
773 780 if (!this.marketTiles.length)
774 781 { throw userError("The Central Exchange is not open in this world yet."); }
782 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
775 783 const near = this.marketTiles.some((tile) =>
776 isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
784 normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim
785 && isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
777 786 if (!near)
778 787 { throw userError("Stand next to the Central Exchange counter."); }
779 788 return { position, entityId };
780 789 }
781 790
782 #stationTargetsForPlayer (tileX, tileY)
791 #stationTargetsForPlayer (tileX, tileY, dimensionId = OVERWORLD_ID)
783 792 {
793 const dim = normalizeDimensionId(dimensionId);
784 794 const targets = [];
785 795 for (const tile of this.marketTiles)
786 796 {
797 if (normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
798 { continue; }
787 799 if (!isAdjacentTile(tileX, tileY, tile.tileX, tile.tileY))
788 800 { continue; }
789 801 if (tile.tileX === tileX && tile.tileY === tileY)
@@ -796,23 +808,26 @@ export class MarketService
796 808 marketTileX: tile.tileX,
797 809 marketTileY: tile.tileY,
798 810 stationTileX,
799 stationTileY
811 stationTileY,
812 dimensionId: dim
800 813 });
801 814 }
802 815 return targets;
803 816 }
804 817
805 #stationKey (stationTileX, stationTileY)
818 #stationKey (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
806 819 {
807 return `${stationTileX | 0},${stationTileY | 0}`;
820 const dim = normalizeDimensionId(dimensionId);
821 return `${dim}:${stationTileX | 0},${stationTileY | 0}`;
808 822 }
809 823
810 #attendStations (sessionId, characterId, tileX, tileY)
824 #attendStations (sessionId, characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
811 825 {
812 826 const id = characterId | 0;
813 for (const target of this.#stationTargetsForPlayer(tileX, tileY))
827 const dim = normalizeDimensionId(dimensionId);
828 for (const target of this.#stationTargetsForPlayer(tileX, tileY, dim))
814 829 {
815 const key = this.#stationKey(target.stationTileX, target.stationTileY);
830 const key = this.#stationKey(target.stationTileX, target.stationTileY, dim);
816 831 let entry = this.stationAttendance.get(key);
817 832 if (!entry)
818 833 {
@@ -821,6 +836,7 @@ export class MarketService
821 836 stationTileY: target.stationTileY,
822 837 marketTileX: target.marketTileX,
823 838 marketTileY: target.marketTileY,
839 dimensionId: dim,
824 840 browsers: new Map()
825 841 };
826 842 this.stationAttendance.set(key, entry);
@@ -828,7 +844,12 @@ export class MarketService
828 844 entry.browsers.set(id, sessionId);
829 845 entry.marketTileX = target.marketTileX;
830 846 entry.marketTileY = target.marketTileY;
831 this.simulation.stationExchangeClerk?.(target.stationTileX, target.stationTileY);
847 entry.dimensionId = dim;
848 this.simulation.stationExchangeClerk?.(
849 target.stationTileX,
850 target.stationTileY,
851 dim
852 );
832 853 }
833 854 }
834 855
@@ -843,12 +864,15 @@ export class MarketService
843 864 return false;
844 865 }
845 866
846 #stillAtMarketCounter (characterId, marketTileX, marketTileY)
867 #stillAtMarketCounter (characterId, marketTileX, marketTileY, dimensionId = OVERWORLD_ID)
847 868 {
848 869 const entityId = this.simulation.characterEntities.get(characterId);
849 870 const position = entityId ? this.simulation.positionOf(entityId) : null;
850 871 if (!position)
851 872 { return false; }
873 const dim = normalizeDimensionId(dimensionId);
874 if (normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID) !== dim)
875 { return false; }
852 876 return isAdjacentTile(position.tileX, position.tileY, marketTileX, marketTileY);
853 877 }
854 878
@@ -858,7 +882,11 @@ export class MarketService
858 882 if (!entry)
859 883 { return; }
860 884 this.stationAttendance.delete(key);
861 this.simulation.releaseExchangeClerk?.(entry.stationTileX, entry.stationTileY);
885 this.simulation.releaseExchangeClerk?.(
886 entry.stationTileX,
887 entry.stationTileY,
888 normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID)
889 );
862 890 }
863 891
864 892 /**
@@ -875,7 +903,12 @@ export class MarketService
875 903 {
876 904 for (const [characterId, sessionId] of [...entry.browsers.entries()])
877 905 {
878 if (this.#stillAtMarketCounter(characterId, entry.marketTileX, entry.marketTileY))
906 if (this.#stillAtMarketCounter(
907 characterId,
908 entry.marketTileX,
909 entry.marketTileY,
910 entry.dimensionId ?? OVERWORLD_ID
911 ))
879 912 { continue; }
880 913 entry.browsers.delete(characterId);
881 914 departed.set(characterId, sessionId);
@@ -36,6 +36,7 @@ import {
36} from "../../../shared/market/listingKey.js";
36} from "../../../shared/market/listingKey.js";
37import { decodeChunkBlob } from "../world/chunkData.js";
37import { decodeChunkBlob } from "../world/chunkData.js";
38import { withTransaction } from "../persistence/database.js";
38import { withTransaction } from "../persistence/database.js";
39import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
39
40
40function userError (message)
41function userError (message)
41{
42{
@@ -56,8 +57,8 @@ export class MarketService
56 this.marketTiles = [];
57 this.marketTiles = [];
57 /**
58 /**
58 * Players holding a CE UI open at a staff station.
59 * Players holding a CE UI open at a staff station.
59 * key `${stationTileX},${stationTileY}` →
60 * key `${dimensionId}:${stationTileX},${stationTileY}` →
60 * { stationTileX, stationTileY, marketTileX, marketTileY, browsers: Map<characterId, sessionId> }
61 * { stationTileX, stationTileY, marketTileX, marketTileY, dimensionId, browsers: Map<characterId, sessionId> }
61 * @type {Map<string, object>}
62 * @type {Map<string, object>}
62 */
63 */
63 this.stationAttendance = new Map();
64 this.stationAttendance = new Map();
@@ -74,7 +75,8 @@ export class MarketService
74 const tiles = [];
75 const tiles = [];
75 for (const coord of this.worldDb.listChunkCoords(revisionId))
76 for (const coord of this.worldDb.listChunkCoords(revisionId))
76 {
77 {
77 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
78 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
79 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim);
78 if (!row)
80 if (!row)
79 { continue; }
81 { continue; }
80 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
82 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
@@ -87,7 +89,8 @@ export class MarketService
87 { continue; }
89 { continue; }
88 tiles.push({
90 tiles.push({
89 tileX: coord.chunk_x * CHUNK_SIZE + localX,
91 tileX: coord.chunk_x * CHUNK_SIZE + localX,
90 tileY: coord.chunk_y * CHUNK_SIZE + localY
92 tileY: coord.chunk_y * CHUNK_SIZE + localY,
93 dimensionId: dim
91 });
94 });
92 }
95 }
93 }
96 }
@@ -95,14 +98,17 @@ export class MarketService
95 this.marketTiles = tiles;
98 this.marketTiles = tiles;
96 }
99 }
97
100
98 nearestMarket (tileX, tileY)
101 nearestMarket (tileX, tileY, dimensionId = null)
99 {
102 {
100 if (!this.marketTiles.length)
103 if (!this.marketTiles.length)
101 { return null; }
104 { return null; }
105 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
102 let best = null;
106 let best = null;
103 let bestDist = Infinity;
107 let bestDist = Infinity;
104 for (const tile of this.marketTiles)
108 for (const tile of this.marketTiles)
105 {
109 {
110 if (dim != null && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
111 { continue; }
106 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
112 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
107 if (dist < bestDist)
113 if (dist < bestDist)
108 {
114 {
@@ -182,7 +188,8 @@ export class MarketService
182 openMarket (sessionId, characterId, now = Date.now())
188 openMarket (sessionId, characterId, now = Date.now())
183 {
189 {
184 const { position } = this.#requireAtMarket(characterId);
190 const { position } = this.#requireAtMarket(characterId);
185 this.#attendStations(sessionId, characterId, position.tileX, position.tileY);
191 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
192 this.#attendStations(sessionId, characterId, position.tileX, position.tileY, dim);
186 return {
193 return {
187 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
194 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
188 };
195 };
@@ -772,18 +779,23 @@ export class MarketService
772 { throw userError("Enter the world before using the Central Exchange."); }
779 { throw userError("Enter the world before using the Central Exchange."); }
773 if (!this.marketTiles.length)
780 if (!this.marketTiles.length)
774 { throw userError("The Central Exchange is not open in this world yet."); }
781 { throw userError("The Central Exchange is not open in this world yet."); }
782 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
775 const near = this.marketTiles.some((tile) =>
783 const near = this.marketTiles.some((tile) =>
776 isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
784 normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim
785 && isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
777 if (!near)
786 if (!near)
778 { throw userError("Stand next to the Central Exchange counter."); }
787 { throw userError("Stand next to the Central Exchange counter."); }
779 return { position, entityId };
788 return { position, entityId };
780 }
789 }
781
790
782 #stationTargetsForPlayer (tileX, tileY)
791 #stationTargetsForPlayer (tileX, tileY, dimensionId = OVERWORLD_ID)
783 {
792 {
793 const dim = normalizeDimensionId(dimensionId);
784 const targets = [];
794 const targets = [];
785 for (const tile of this.marketTiles)
795 for (const tile of this.marketTiles)
786 {
796 {
797 if (normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
798 { continue; }
787 if (!isAdjacentTile(tileX, tileY, tile.tileX, tile.tileY))
799 if (!isAdjacentTile(tileX, tileY, tile.tileX, tile.tileY))
788 { continue; }
800 { continue; }
789 if (tile.tileX === tileX && tile.tileY === tileY)
801 if (tile.tileX === tileX && tile.tileY === tileY)
@@ -796,23 +808,26 @@ export class MarketService
796 marketTileX: tile.tileX,
808 marketTileX: tile.tileX,
797 marketTileY: tile.tileY,
809 marketTileY: tile.tileY,
798 stationTileX,
810 stationTileX,
799 stationTileY
811 stationTileY,
812 dimensionId: dim
800 });
813 });
801 }
814 }
802 return targets;
815 return targets;
803 }
816 }
804
817
805 #stationKey (stationTileX, stationTileY)
818 #stationKey (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
806 {
819 {
807 return `${stationTileX | 0},${stationTileY | 0}`;
820 const dim = normalizeDimensionId(dimensionId);
821 return `${dim}:${stationTileX | 0},${stationTileY | 0}`;
808 }
822 }
809
823
810 #attendStations (sessionId, characterId, tileX, tileY)
824 #attendStations (sessionId, characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
811 {
825 {
812 const id = characterId | 0;
826 const id = characterId | 0;
813 for (const target of this.#stationTargetsForPlayer(tileX, tileY))
827 const dim = normalizeDimensionId(dimensionId);
828 for (const target of this.#stationTargetsForPlayer(tileX, tileY, dim))
814 {
829 {
815 const key = this.#stationKey(target.stationTileX, target.stationTileY);
830 const key = this.#stationKey(target.stationTileX, target.stationTileY, dim);
816 let entry = this.stationAttendance.get(key);
831 let entry = this.stationAttendance.get(key);
817 if (!entry)
832 if (!entry)
818 {
833 {
@@ -821,6 +836,7 @@ export class MarketService
821 stationTileY: target.stationTileY,
836 stationTileY: target.stationTileY,
822 marketTileX: target.marketTileX,
837 marketTileX: target.marketTileX,
823 marketTileY: target.marketTileY,
838 marketTileY: target.marketTileY,
839 dimensionId: dim,
824 browsers: new Map()
840 browsers: new Map()
825 };
841 };
826 this.stationAttendance.set(key, entry);
842 this.stationAttendance.set(key, entry);
@@ -828,7 +844,12 @@ export class MarketService
828 entry.browsers.set(id, sessionId);
844 entry.browsers.set(id, sessionId);
829 entry.marketTileX = target.marketTileX;
845 entry.marketTileX = target.marketTileX;
830 entry.marketTileY = target.marketTileY;
846 entry.marketTileY = target.marketTileY;
831 this.simulation.stationExchangeClerk?.(target.stationTileX, target.stationTileY);
847 entry.dimensionId = dim;
848 this.simulation.stationExchangeClerk?.(
849 target.stationTileX,
850 target.stationTileY,
851 dim
852 );
832 }
853 }
833 }
854 }
834
855
@@ -843,12 +864,15 @@ export class MarketService
843 return false;
864 return false;
844 }
865 }
845
866
846 #stillAtMarketCounter (characterId, marketTileX, marketTileY)
867 #stillAtMarketCounter (characterId, marketTileX, marketTileY, dimensionId = OVERWORLD_ID)
847 {
868 {
848 const entityId = this.simulation.characterEntities.get(characterId);
869 const entityId = this.simulation.characterEntities.get(characterId);
849 const position = entityId ? this.simulation.positionOf(entityId) : null;
870 const position = entityId ? this.simulation.positionOf(entityId) : null;
850 if (!position)
871 if (!position)
851 { return false; }
872 { return false; }
873 const dim = normalizeDimensionId(dimensionId);
874 if (normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID) !== dim)
875 { return false; }
852 return isAdjacentTile(position.tileX, position.tileY, marketTileX, marketTileY);
876 return isAdjacentTile(position.tileX, position.tileY, marketTileX, marketTileY);
853 }
877 }
854
878
@@ -858,7 +882,11 @@ export class MarketService
858 if (!entry)
882 if (!entry)
859 { return; }
883 { return; }
860 this.stationAttendance.delete(key);
884 this.stationAttendance.delete(key);
861 this.simulation.releaseExchangeClerk?.(entry.stationTileX, entry.stationTileY);
885 this.simulation.releaseExchangeClerk?.(
886 entry.stationTileX,
887 entry.stationTileY,
888 normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID)
889 );
862 }
890 }
863
891
864 /**
892 /**
@@ -875,7 +903,12 @@ export class MarketService
875 {
903 {
876 for (const [characterId, sessionId] of [...entry.browsers.entries()])
904 for (const [characterId, sessionId] of [...entry.browsers.entries()])
877 {
905 {
878 if (this.#stillAtMarketCounter(characterId, entry.marketTileX, entry.marketTileY))
906 if (this.#stillAtMarketCounter(
907 characterId,
908 entry.marketTileX,
909 entry.marketTileY,
910 entry.dimensionId ?? OVERWORLD_ID
911 ))
879 { continue; }
912 { continue; }
880 entry.browsers.delete(characterId);
913 entry.browsers.delete(characterId);
881 departed.set(characterId, sessionId);
914 departed.set(characterId, sessionId);
server/src/persistence/stateDb.js +30 −0
@@ -268,6 +268,12 @@ export class StateDatabase
268 268 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
269 269 if (!characterColumns.some((column) => column.name === "cowardice_forgiven_hour"))
270 270 { this.db.exec("ALTER TABLE characters ADD COLUMN cowardice_forgiven_hour INTEGER"); }
271 if (!characterColumns.some((column) => column.name === "respawn_altar_x"))
272 {
273 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_x INTEGER");
274 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_y INTEGER");
275 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_dimension_id TEXT");
276 }
271 277 const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();
272 278 if (!marketColumns.some((column) => column.name === "listing_key"))
273 279 { this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }
@@ -700,6 +706,30 @@ export class StateDatabase
700 706 );
701 707 }
702 708
709 getCharacterRespawnAltar (characterId)
710 {
711 const row = this.db.prepare(`
712 SELECT respawn_altar_x, respawn_altar_y, respawn_altar_dimension_id
713 FROM characters WHERE character_id = ?
714 `).get(characterId | 0);
715 if (!row || row.respawn_altar_x == null || row.respawn_altar_y == null)
716 { return null; }
717 return {
718 tileX: row.respawn_altar_x | 0,
719 tileY: row.respawn_altar_y | 0,
720 dimensionId: String(row.respawn_altar_dimension_id ?? "overworld")
721 };
722 }
723
724 setCharacterRespawnAltar (characterId, tileX, tileY, dimensionId = "overworld")
725 {
726 this.db.prepare(`
727 UPDATE characters
728 SET respawn_altar_x = ?, respawn_altar_y = ?, respawn_altar_dimension_id = ?
729 WHERE character_id = ?
730 `).run(tileX | 0, tileY | 0, String(dimensionId ?? "overworld"), characterId | 0);
731 }
732
703 733 markDimensionVisited (characterId, dimensionId, now = Date.now())
704 734 {
705 735 const dim = String(dimensionId ?? "overworld");
@@ -268,6 +268,12 @@ export class StateDatabase
268 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
268 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
269 if (!characterColumns.some((column) => column.name === "cowardice_forgiven_hour"))
269 if (!characterColumns.some((column) => column.name === "cowardice_forgiven_hour"))
270 { this.db.exec("ALTER TABLE characters ADD COLUMN cowardice_forgiven_hour INTEGER"); }
270 { this.db.exec("ALTER TABLE characters ADD COLUMN cowardice_forgiven_hour INTEGER"); }
271 if (!characterColumns.some((column) => column.name === "respawn_altar_x"))
272 {
273 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_x INTEGER");
274 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_y INTEGER");
275 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_dimension_id TEXT");
276 }
271 const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();
277 const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();
272 if (!marketColumns.some((column) => column.name === "listing_key"))
278 if (!marketColumns.some((column) => column.name === "listing_key"))
273 { this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }
279 { this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }
@@ -700,6 +706,30 @@ export class StateDatabase
700 );
706 );
701 }
707 }
702
708
709 getCharacterRespawnAltar (characterId)
710 {
711 const row = this.db.prepare(`
712 SELECT respawn_altar_x, respawn_altar_y, respawn_altar_dimension_id
713 FROM characters WHERE character_id = ?
714 `).get(characterId | 0);
715 if (!row || row.respawn_altar_x == null || row.respawn_altar_y == null)
716 { return null; }
717 return {
718 tileX: row.respawn_altar_x | 0,
719 tileY: row.respawn_altar_y | 0,
720 dimensionId: String(row.respawn_altar_dimension_id ?? "overworld")
721 };
722 }
723
724 setCharacterRespawnAltar (characterId, tileX, tileY, dimensionId = "overworld")
725 {
726 this.db.prepare(`
727 UPDATE characters
728 SET respawn_altar_x = ?, respawn_altar_y = ?, respawn_altar_dimension_id = ?
729 WHERE character_id = ?
730 `).run(tileX | 0, tileY | 0, String(dimensionId ?? "overworld"), characterId | 0);
731 }
732
703 markDimensionVisited (characterId, dimensionId, now = Date.now())
733 markDimensionVisited (characterId, dimensionId, now = Date.now())
704 {
734 {
705 const dim = String(dimensionId ?? "overworld");
735 const dim = String(dimensionId ?? "overworld");
server/src/simulation/simulation.js +224 −42
@@ -1241,15 +1241,17 @@ export class Simulation
1241 1241 /**
1242 1242 * Path an idle CE clerk to a staff-side station tile.
1243 1243 */
1244 stationExchangeClerk (stationTileX, stationTileY)
1244 stationExchangeClerk (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
1245 1245 {
1246 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
1246 const dim = normalizeDimensionId(dimensionId);
1247 const owner = this.#ownerOfTile(stationTileX, stationTileY, dim);
1247 1248 if (owner == null)
1248 1249 { return { ok: false, reason: "unowned" }; }
1249 1250 return this.workers[owner].call({
1250 1251 type: WorkerMessage.stationExchangeClerk,
1251 1252 stationTileX,
1252 stationTileY
1253 stationTileY,
1254 dimensionId: dim
1253 1255 });
1254 1256 }
1255 1257
@@ -1257,11 +1259,14 @@ export class Simulation
1257 1259 * When a player uses a marketplace counter, path idle CE clerks to the
1258 1260 * opposite side of each adjacent counter (staff side).
1259 1261 */
1260 stationExchangeClerks (playerTileX, playerTileY)
1262 stationExchangeClerks (playerTileX, playerTileY, dimensionId = OVERWORLD_ID)
1261 1263 {
1264 const dim = normalizeDimensionId(dimensionId);
1262 1265 const results = [];
1263 1266 for (const tile of this.market?.marketTiles ?? [])
1264 1267 {
1268 if (normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
1269 { continue; }
1265 1270 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
1266 1271 { continue; }
1267 1272 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
@@ -1270,21 +1275,23 @@ export class Simulation
1270 1275 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
1271 1276 if (stationTileX === playerTileX && stationTileY === playerTileY)
1272 1277 { continue; }
1273 results.push(this.stationExchangeClerk(stationTileX, stationTileY));
1278 results.push(this.stationExchangeClerk(stationTileX, stationTileY, dim));
1274 1279 }
1275 1280 return results;
1276 1281 }
1277 1282
1278 1283 /** Release a CE clerk stationed at the given staff-side tile. */
1279 releaseExchangeClerk (stationTileX, stationTileY)
1284 releaseExchangeClerk (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
1280 1285 {
1281 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
1286 const dim = normalizeDimensionId(dimensionId);
1287 const owner = this.#ownerOfTile(stationTileX, stationTileY, dim);
1282 1288 if (owner == null)
1283 1289 { return { ok: false, reason: "unowned" }; }
1284 1290 return this.workers[owner].call({
1285 1291 type: WorkerMessage.releaseExchangeClerk,
1286 1292 stationTileX,
1287 stationTileY
1293 stationTileY,
1294 dimensionId: dim
1288 1295 });
1289 1296 }
1290 1297
@@ -1552,6 +1559,15 @@ export class Simulation
1552 1559 // Queued intents after death (drop/use/send/craft/…) are discarded.
1553 1560 return [];
1554 1561 }
1562 if (item.command.type === "pray-at-altar")
1563 {
1564 return this.#prayAtAltar(
1565 item.sessionId,
1566 item.command.characterId,
1567 item.command.tileX,
1568 item.command.tileY
1569 );
1570 }
1555 1571 if (item.command.type === "enter-doorway")
1556 1572 {
1557 1573 return this.#relocateCharacterThroughDoorway(
@@ -2499,6 +2515,42 @@ export class Simulation
2499 2515 return events;
2500 2516 }
2501 2517
2518 #prayAtAltar (sessionId, characterId, altarTileX, altarTileY)
2519 {
2520 const entityId = this.characterEntities.get(characterId);
2521 const record = entityId ? this.directory.get(entityId) : null;
2522 if (!record)
2523 {
2524 const error = new Error("Character is not in the world.");
2525 error.userFacing = true;
2526 throw error;
2527 }
2528 const tileX = altarTileX | 0;
2529 const tileY = altarTileY | 0;
2530 if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY))
2531 {
2532 const error = new Error("You are too far from that altar.");
2533 error.userFacing = true;
2534 throw error;
2535 }
2536 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2537 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2538 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
2539 if (block?.typeId !== BlockType.churchAltar)
2540 {
2541 const error = new Error("There is no altar there.");
2542 error.userFacing = true;
2543 throw error;
2544 }
2545 this.stateDb.setCharacterRespawnAltar(characterId, tileX, tileY, dimensionId);
2546 return [{
2547 type: "toast",
2548 sessionId,
2549 characterId,
2550 message: "Altar set as respawn point."
2551 }];
2552 }
2553
2502 2554 #respawnCharacter (sessionId, characterId)
2503 2555 {
2504 2556 const row = this.stateDb.getCharacter(characterId);
@@ -2516,22 +2568,25 @@ export class Simulation
2516 2568 error.userFacing = true;
2517 2569 throw error;
2518 2570 }
2519 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
2571 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2572 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId, characterId);
2520 2573 if (!destination)
2521 2574 {
2522 2575 const error = new Error("No open tile is available for respawn.");
2523 2576 error.userFacing = true;
2524 2577 throw error;
2525 2578 }
2579 const destDimensionId = normalizeDimensionId(destination.dimensionId ?? fromDimensionId);
2526 2580 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
2527 2581 const loader = { ...DEFAULT_CHUNK_LOADER };
2528 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID);
2582 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destDimensionId);
2529 2583 const result = this.workers[record.workerId].call({
2530 2584 type: WorkerMessage.applyRespawn,
2531 2585 entityId,
2532 2586 sessionId,
2533 2587 tileX: destination.tileX,
2534 2588 tileY: destination.tileY,
2589 dimensionId: destDimensionId,
2535 2590 maxHealth: playerMaxHealth(skills),
2536 2591 maxStamina: playerMaxStamina(skills)
2537 2592 });
@@ -2569,20 +2624,33 @@ export class Simulation
2569 2624 destination.tileX,
2570 2625 destination.tileY,
2571 2626 record.gait ?? GAIT.walk,
2572 destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
2627 destDimensionId
2573 2628 );
2629 if (destination.altar)
2630 {
2631 this.stateDb.setCharacterRespawnAltar(
2632 characterId,
2633 destination.altar.tileX,
2634 destination.altar.tileY,
2635 destination.altar.dimensionId
2636 );
2637 }
2638 this.stateDb.markDimensionVisited(characterId, destDimensionId);
2639 this.syncCharacterConditionAccess(characterId);
2574 2640 this.#recalculateActivation(this.now);
2575 2641 this.#syncGhosts();
2576 2642 const skullEvent = this.refreshCharacterSkull(characterId, { force: true });
2577 2643 const skullPoints = this.directory.get(entityId)?.skullValue | 0;
2578 const spawnView = this.workers[record.workerId].call({
2644 const after = this.directory.get(entityId);
2645 const inspectWorkerId = after?.workerId ?? record.workerId;
2646 const spawnView = this.workers[inspectWorkerId].call({
2579 2647 type: WorkerMessage.inspect,
2580 2648 entityId
2581 2649 });
2582 2650 const spawn = spawnView
2583 2651 ? replicationSpawn({ ...spawnView, skullValue: skullPoints })
2584 2652 : null;
2585 return [
2653 const events = [
2586 2654 ...moveEvents,
2587 2655 ...(spawn ? [spawn] : []),
2588 2656 ...(skullEvent ? [skullEvent] : []),
@@ -2593,6 +2661,7 @@ export class Simulation
2593 2661 sessionId,
2594 2662 tileX: destination.tileX,
2595 2663 tileY: destination.tileY,
2664 dimensionId: destDimensionId,
2596 2665 health: playerMaxHealth(skills),
2597 2666 maxHealth: playerMaxHealth(skills),
2598 2667 stamina: playerMaxStamina(skills),
@@ -2600,6 +2669,22 @@ export class Simulation
2600 2669 skullValue: skullPoints
2601 2670 }
2602 2671 ];
2672 if (destDimensionId !== fromDimensionId)
2673 {
2674 const dimRecord = this.getDimensionRecord(destDimensionId);
2675 events.push({
2676 type: "dimension-changed",
2677 sessionId,
2678 characterId,
2679 entityId,
2680 dimensionId: destDimensionId,
2681 tileX: destination.tileX,
2682 tileY: destination.tileY,
2683 lightingMode: dimRecord?.lightingMode ?? "dayNight",
2684 seasonMode: dimRecord?.seasonMode ?? "auto"
2685 });
2686 }
2687 return events;
2603 2688 }
2604 2689
2605 2690 #refreshAltarIndex ()
@@ -2627,37 +2712,98 @@ export class Simulation
2627 2712 this.altarTiles = altars;
2628 2713 }
2629 2714
2630 #findRespawnDestination (originX, originY, entityId)
2715 #chebyshevDistance (originX, originY, tileX, tileY)
2631 2716 {
2632 const record = this.directory.get(entityId);
2633 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2634 const ordered = [...this.altarTiles].sort((left, right) =>
2635 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2636 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2717 return Math.max(Math.abs(tileX - originX), Math.abs(tileY - originY));
2718 }
2719
2720 #sortAltarsByDistance (altars, originX, originY)
2721 {
2722 return [...altars].sort((left, right) =>
2723 this.#chebyshevDistance(originX, originY, left.tileX, left.tileY)
2724 - this.#chebyshevDistance(originX, originY, right.tileX, right.tileY)
2637 2725 );
2638 for (const altar of ordered)
2726 }
2727
2728 #findAdjacentOpenToAltar (altar, originX, originY, entityId)
2729 {
2730 const dimensionId = normalizeDimensionId(altar.dimensionId ?? OVERWORLD_ID);
2731 const adjacent = [];
2732 for (let dy = -1; dy <= 1; dy++)
2639 2733 {
2640 const adjacent = [];
2641 for (let dy = -1; dy <= 1; dy++)
2734 for (let dx = -1; dx <= 1; dx++)
2642 2735 {
2643 for (let dx = -1; dx <= 1; dx++)
2644 {
2645 if (dx === 0 && dy === 0)
2646 { continue; }
2647 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId });
2648 }
2736 if (dx === 0 && dy === 0)
2737 { continue; }
2738 adjacent.push({
2739 tileX: altar.tileX + dx,
2740 tileY: altar.tileY + dy,
2741 dimensionId,
2742 altar: {
2743 tileX: altar.tileX | 0,
2744 tileY: altar.tileY | 0,
2745 dimensionId
2746 }
2747 });
2649 2748 }
2650 adjacent.sort((left, right) =>
2651 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2652 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2653 );
2654 const tile = adjacent.find((entry) =>
2655 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2656 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2657 );
2749 }
2750 adjacent.sort((left, right) =>
2751 this.#chebyshevDistance(originX, originY, left.tileX, left.tileY)
2752 - this.#chebyshevDistance(originX, originY, right.tileX, right.tileY)
2753 );
2754 return adjacent.find((entry) =>
2755 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2756 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2757 ) ?? null;
2758 }
2759
2760 #findNearestAltarDestination (originX, originY, entityId, preferredDimensionId = null)
2761 {
2762 const preferred = preferredDimensionId != null
2763 ? normalizeDimensionId(preferredDimensionId)
2764 : null;
2765 const preferredAltars = preferred
2766 ? this.altarTiles.filter((altar) =>
2767 normalizeDimensionId(altar.dimensionId) === preferred)
2768 : [];
2769 const otherAltars = preferred
2770 ? this.altarTiles.filter((altar) =>
2771 normalizeDimensionId(altar.dimensionId) !== preferred)
2772 : this.altarTiles;
2773 for (const altar of this.#sortAltarsByDistance(preferredAltars, originX, originY))
2774 {
2775 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2658 2776 if (tile)
2659 2777 { return tile; }
2660 2778 }
2779 for (const altar of this.#sortAltarsByDistance(otherAltars, originX, originY))
2780 {
2781 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2782 if (tile)
2783 { return tile; }
2784 }
2785 return null;
2786 }
2787
2788 #findSavedAltarDestination (characterId, originX, originY, entityId)
2789 {
2790 const saved = this.stateDb.getCharacterRespawnAltar(characterId);
2791 if (!saved)
2792 { return null; }
2793 const dimensionId = normalizeDimensionId(saved.dimensionId ?? OVERWORLD_ID);
2794 const altar = this.altarTiles.find((entry) =>
2795 (entry.tileX | 0) === (saved.tileX | 0)
2796 && (entry.tileY | 0) === (saved.tileY | 0)
2797 && normalizeDimensionId(entry.dimensionId) === dimensionId
2798 );
2799 if (!altar)
2800 { return null; }
2801 return this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2802 }
2803
2804 #findDeathTileFallback (originX, originY, entityId, dimensionId)
2805 {
2806 const dim = normalizeDimensionId(dimensionId);
2661 2807 for (let radius = 0; radius <= 24; radius++)
2662 2808 {
2663 2809 for (let dy = -radius; dy <= radius; dy++)
@@ -2668,13 +2814,45 @@ export class Simulation
2668 2814 { continue; }
2669 2815 const tileX = originX + dx;
2670 2816 const tileY = originY + dy;
2671 if (this.isEnterable(tileX, tileY, dimensionId)
2672 && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId))
2673 { return { tileX, tileY, dimensionId }; }
2817 if (this.isEnterable(tileX, tileY, dim)
2818 && !this.#occupiedByOther(tileX, tileY, entityId, dim))
2819 { return { tileX, tileY, dimensionId: dim }; }
2674 2820 }
2675 2821 }
2676 2822 }
2677 return this.findOpenSpawn();
2823 return null;
2824 }
2825
2826 #findRespawnDestination (originX, originY, entityId, characterId = null)
2827 {
2828 const record = this.directory.get(entityId);
2829 const deathDimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2830 const deathAltars = this.altarTiles.filter((altar) =>
2831 normalizeDimensionId(altar.dimensionId) === deathDimensionId
2832 );
2833 for (const altar of this.#sortAltarsByDistance(deathAltars, originX, originY))
2834 {
2835 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2836 if (tile)
2837 { return tile; }
2838 }
2839 if (characterId != null)
2840 {
2841 const saved = this.#findSavedAltarDestination(characterId, originX, originY, entityId);
2842 if (saved)
2843 { return saved; }
2844 }
2845 const otherAltars = this.altarTiles.filter((altar) =>
2846 normalizeDimensionId(altar.dimensionId) !== deathDimensionId
2847 );
2848 for (const altar of this.#sortAltarsByDistance(otherAltars, originX, originY))
2849 {
2850 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2851 if (tile)
2852 { return tile; }
2853 }
2854 return this.#findDeathTileFallback(originX, originY, entityId, deathDimensionId)
2855 ?? this.findOpenSpawn();
2678 2856 }
2679 2857
2680 2858 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
@@ -3402,12 +3580,16 @@ export class Simulation
3402 3580 #findJewelryTeleportDestination (originX, originY, entityId, destination)
3403 3581 {
3404 3582 if (destination === "church")
3405 { return this.#findRespawnDestination(originX, originY, entityId); }
3583 {
3584 const record = this.directory.get(entityId);
3585 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3586 return this.#findNearestAltarDestination(originX, originY, entityId, dimensionId);
3587 }
3406 3588 if (destination !== "bank")
3407 3589 { return null; }
3408 3590 const record = this.directory.get(entityId);
3409 3591 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3410 const bank = this.courier?.nearestBank(originX, originY);
3592 const bank = this.courier?.nearestBank(originX, originY, dimensionId);
3411 3593 if (!bank)
3412 3594 { return null; }
3413 3595 const adjacent = [];
@@ -1241,15 +1241,17 @@ export class Simulation
1241 /**
1241 /**
1242 * Path an idle CE clerk to a staff-side station tile.
1242 * Path an idle CE clerk to a staff-side station tile.
1243 */
1243 */
1244 stationExchangeClerk (stationTileX, stationTileY)
1244 stationExchangeClerk (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
1245 {
1245 {
1246 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
1246 const dim = normalizeDimensionId(dimensionId);
1247 const owner = this.#ownerOfTile(stationTileX, stationTileY, dim);
1247 if (owner == null)
1248 if (owner == null)
1248 { return { ok: false, reason: "unowned" }; }
1249 { return { ok: false, reason: "unowned" }; }
1249 return this.workers[owner].call({
1250 return this.workers[owner].call({
1250 type: WorkerMessage.stationExchangeClerk,
1251 type: WorkerMessage.stationExchangeClerk,
1251 stationTileX,
1252 stationTileX,
1252 stationTileY
1253 stationTileY,
1254 dimensionId: dim
1253 });
1255 });
1254 }
1256 }
1255
1257
@@ -1257,11 +1259,14 @@ export class Simulation
1257 * When a player uses a marketplace counter, path idle CE clerks to the
1259 * When a player uses a marketplace counter, path idle CE clerks to the
1258 * opposite side of each adjacent counter (staff side).
1260 * opposite side of each adjacent counter (staff side).
1259 */
1261 */
1260 stationExchangeClerks (playerTileX, playerTileY)
1262 stationExchangeClerks (playerTileX, playerTileY, dimensionId = OVERWORLD_ID)
1261 {
1263 {
1264 const dim = normalizeDimensionId(dimensionId);
1262 const results = [];
1265 const results = [];
1263 for (const tile of this.market?.marketTiles ?? [])
1266 for (const tile of this.market?.marketTiles ?? [])
1264 {
1267 {
1268 if (normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
1269 { continue; }
1265 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
1270 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
1266 { continue; }
1271 { continue; }
1267 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
1272 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
@@ -1270,21 +1275,23 @@ export class Simulation
1270 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
1275 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
1271 if (stationTileX === playerTileX && stationTileY === playerTileY)
1276 if (stationTileX === playerTileX && stationTileY === playerTileY)
1272 { continue; }
1277 { continue; }
1273 results.push(this.stationExchangeClerk(stationTileX, stationTileY));
1278 results.push(this.stationExchangeClerk(stationTileX, stationTileY, dim));
1274 }
1279 }
1275 return results;
1280 return results;
1276 }
1281 }
1277
1282
1278 /** Release a CE clerk stationed at the given staff-side tile. */
1283 /** Release a CE clerk stationed at the given staff-side tile. */
1279 releaseExchangeClerk (stationTileX, stationTileY)
1284 releaseExchangeClerk (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
1280 {
1285 {
1281 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
1286 const dim = normalizeDimensionId(dimensionId);
1287 const owner = this.#ownerOfTile(stationTileX, stationTileY, dim);
1282 if (owner == null)
1288 if (owner == null)
1283 { return { ok: false, reason: "unowned" }; }
1289 { return { ok: false, reason: "unowned" }; }
1284 return this.workers[owner].call({
1290 return this.workers[owner].call({
1285 type: WorkerMessage.releaseExchangeClerk,
1291 type: WorkerMessage.releaseExchangeClerk,
1286 stationTileX,
1292 stationTileX,
1287 stationTileY
1293 stationTileY,
1294 dimensionId: dim
1288 });
1295 });
1289 }
1296 }
1290
1297
@@ -1552,6 +1559,15 @@ export class Simulation
1552 // Queued intents after death (drop/use/send/craft/…) are discarded.
1559 // Queued intents after death (drop/use/send/craft/…) are discarded.
1553 return [];
1560 return [];
1554 }
1561 }
1562 if (item.command.type === "pray-at-altar")
1563 {
1564 return this.#prayAtAltar(
1565 item.sessionId,
1566 item.command.characterId,
1567 item.command.tileX,
1568 item.command.tileY
1569 );
1570 }
1555 if (item.command.type === "enter-doorway")
1571 if (item.command.type === "enter-doorway")
1556 {
1572 {
1557 return this.#relocateCharacterThroughDoorway(
1573 return this.#relocateCharacterThroughDoorway(
@@ -2499,6 +2515,42 @@ export class Simulation
2499 return events;
2515 return events;
2500 }
2516 }
2501
2517
2518 #prayAtAltar (sessionId, characterId, altarTileX, altarTileY)
2519 {
2520 const entityId = this.characterEntities.get(characterId);
2521 const record = entityId ? this.directory.get(entityId) : null;
2522 if (!record)
2523 {
2524 const error = new Error("Character is not in the world.");
2525 error.userFacing = true;
2526 throw error;
2527 }
2528 const tileX = altarTileX | 0;
2529 const tileY = altarTileY | 0;
2530 if (!isAdjacentTile(record.tileX, record.tileY, tileX, tileY))
2531 {
2532 const error = new Error("You are too far from that altar.");
2533 error.userFacing = true;
2534 throw error;
2535 }
2536 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2537 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2538 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
2539 if (block?.typeId !== BlockType.churchAltar)
2540 {
2541 const error = new Error("There is no altar there.");
2542 error.userFacing = true;
2543 throw error;
2544 }
2545 this.stateDb.setCharacterRespawnAltar(characterId, tileX, tileY, dimensionId);
2546 return [{
2547 type: "toast",
2548 sessionId,
2549 characterId,
2550 message: "Altar set as respawn point."
2551 }];
2552 }
2553
2502 #respawnCharacter (sessionId, characterId)
2554 #respawnCharacter (sessionId, characterId)
2503 {
2555 {
2504 const row = this.stateDb.getCharacter(characterId);
2556 const row = this.stateDb.getCharacter(characterId);
@@ -2516,22 +2568,25 @@ export class Simulation
2516 error.userFacing = true;
2568 error.userFacing = true;
2517 throw error;
2569 throw error;
2518 }
2570 }
2519 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
2571 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2572 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId, characterId);
2520 if (!destination)
2573 if (!destination)
2521 {
2574 {
2522 const error = new Error("No open tile is available for respawn.");
2575 const error = new Error("No open tile is available for respawn.");
2523 error.userFacing = true;
2576 error.userFacing = true;
2524 throw error;
2577 throw error;
2525 }
2578 }
2579 const destDimensionId = normalizeDimensionId(destination.dimensionId ?? fromDimensionId);
2526 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
2580 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
2527 const loader = { ...DEFAULT_CHUNK_LOADER };
2581 const loader = { ...DEFAULT_CHUNK_LOADER };
2528 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID);
2582 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destDimensionId);
2529 const result = this.workers[record.workerId].call({
2583 const result = this.workers[record.workerId].call({
2530 type: WorkerMessage.applyRespawn,
2584 type: WorkerMessage.applyRespawn,
2531 entityId,
2585 entityId,
2532 sessionId,
2586 sessionId,
2533 tileX: destination.tileX,
2587 tileX: destination.tileX,
2534 tileY: destination.tileY,
2588 tileY: destination.tileY,
2589 dimensionId: destDimensionId,
2535 maxHealth: playerMaxHealth(skills),
2590 maxHealth: playerMaxHealth(skills),
2536 maxStamina: playerMaxStamina(skills)
2591 maxStamina: playerMaxStamina(skills)
2537 });
2592 });
@@ -2569,20 +2624,33 @@ export class Simulation
2569 destination.tileX,
2624 destination.tileX,
2570 destination.tileY,
2625 destination.tileY,
2571 record.gait ?? GAIT.walk,
2626 record.gait ?? GAIT.walk,
2572 destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
2627 destDimensionId
2573 );
2628 );
2629 if (destination.altar)
2630 {
2631 this.stateDb.setCharacterRespawnAltar(
2632 characterId,
2633 destination.altar.tileX,
2634 destination.altar.tileY,
2635 destination.altar.dimensionId
2636 );
2637 }
2638 this.stateDb.markDimensionVisited(characterId, destDimensionId);
2639 this.syncCharacterConditionAccess(characterId);
2574 this.#recalculateActivation(this.now);
2640 this.#recalculateActivation(this.now);
2575 this.#syncGhosts();
2641 this.#syncGhosts();
2576 const skullEvent = this.refreshCharacterSkull(characterId, { force: true });
2642 const skullEvent = this.refreshCharacterSkull(characterId, { force: true });
2577 const skullPoints = this.directory.get(entityId)?.skullValue | 0;
2643 const skullPoints = this.directory.get(entityId)?.skullValue | 0;
2578 const spawnView = this.workers[record.workerId].call({
2644 const after = this.directory.get(entityId);
2645 const inspectWorkerId = after?.workerId ?? record.workerId;
2646 const spawnView = this.workers[inspectWorkerId].call({
2579 type: WorkerMessage.inspect,
2647 type: WorkerMessage.inspect,
2580 entityId
2648 entityId
2581 });
2649 });
2582 const spawn = spawnView
2650 const spawn = spawnView
2583 ? replicationSpawn({ ...spawnView, skullValue: skullPoints })
2651 ? replicationSpawn({ ...spawnView, skullValue: skullPoints })
2584 : null;
2652 : null;
2585 return [
2653 const events = [
2586 ...moveEvents,
2654 ...moveEvents,
2587 ...(spawn ? [spawn] : []),
2655 ...(spawn ? [spawn] : []),
2588 ...(skullEvent ? [skullEvent] : []),
2656 ...(skullEvent ? [skullEvent] : []),
@@ -2593,6 +2661,7 @@ export class Simulation
2593 sessionId,
2661 sessionId,
2594 tileX: destination.tileX,
2662 tileX: destination.tileX,
2595 tileY: destination.tileY,
2663 tileY: destination.tileY,
2664 dimensionId: destDimensionId,
2596 health: playerMaxHealth(skills),
2665 health: playerMaxHealth(skills),
2597 maxHealth: playerMaxHealth(skills),
2666 maxHealth: playerMaxHealth(skills),
2598 stamina: playerMaxStamina(skills),
2667 stamina: playerMaxStamina(skills),
@@ -2600,6 +2669,22 @@ export class Simulation
2600 skullValue: skullPoints
2669 skullValue: skullPoints
2601 }
2670 }
2602 ];
2671 ];
2672 if (destDimensionId !== fromDimensionId)
2673 {
2674 const dimRecord = this.getDimensionRecord(destDimensionId);
2675 events.push({
2676 type: "dimension-changed",
2677 sessionId,
2678 characterId,
2679 entityId,
2680 dimensionId: destDimensionId,
2681 tileX: destination.tileX,
2682 tileY: destination.tileY,
2683 lightingMode: dimRecord?.lightingMode ?? "dayNight",
2684 seasonMode: dimRecord?.seasonMode ?? "auto"
2685 });
2686 }
2687 return events;
2603 }
2688 }
2604
2689
2605 #refreshAltarIndex ()
2690 #refreshAltarIndex ()
@@ -2627,37 +2712,98 @@ export class Simulation
2627 this.altarTiles = altars;
2712 this.altarTiles = altars;
2628 }
2713 }
2629
2714
2630 #findRespawnDestination (originX, originY, entityId)
2715 #chebyshevDistance (originX, originY, tileX, tileY)
2631 {
2716 {
2632 const record = this.directory.get(entityId);
2717 return Math.max(Math.abs(tileX - originX), Math.abs(tileY - originY));
2633 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2718 }
2634 const ordered = [...this.altarTiles].sort((left, right) =>
2719
2635 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2720 #sortAltarsByDistance (altars, originX, originY)
2636 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2721 {
2722 return [...altars].sort((left, right) =>
2723 this.#chebyshevDistance(originX, originY, left.tileX, left.tileY)
2724 - this.#chebyshevDistance(originX, originY, right.tileX, right.tileY)
2637 );
2725 );
2638 for (const altar of ordered)
2726 }
2727
2728 #findAdjacentOpenToAltar (altar, originX, originY, entityId)
2729 {
2730 const dimensionId = normalizeDimensionId(altar.dimensionId ?? OVERWORLD_ID);
2731 const adjacent = [];
2732 for (let dy = -1; dy <= 1; dy++)
2639 {
2733 {
2640 const adjacent = [];
2734 for (let dx = -1; dx <= 1; dx++)
2641 for (let dy = -1; dy <= 1; dy++)
2642 {
2735 {
2643 for (let dx = -1; dx <= 1; dx++)
2736 if (dx === 0 && dy === 0)
2644 {
2737 { continue; }
2645 if (dx === 0 && dy === 0)
2738 adjacent.push({
2646 { continue; }
2739 tileX: altar.tileX + dx,
2647 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId });
2740 tileY: altar.tileY + dy,
2648 }
2741 dimensionId,
2742 altar: {
2743 tileX: altar.tileX | 0,
2744 tileY: altar.tileY | 0,
2745 dimensionId
2746 }
2747 });
2649 }
2748 }
2650 adjacent.sort((left, right) =>
2749 }
2651 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
2750 adjacent.sort((left, right) =>
2652 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
2751 this.#chebyshevDistance(originX, originY, left.tileX, left.tileY)
2653 );
2752 - this.#chebyshevDistance(originX, originY, right.tileX, right.tileY)
2654 const tile = adjacent.find((entry) =>
2753 );
2655 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2754 return adjacent.find((entry) =>
2656 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2755 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
2657 );
2756 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
2757 ) ?? null;
2758 }
2759
2760 #findNearestAltarDestination (originX, originY, entityId, preferredDimensionId = null)
2761 {
2762 const preferred = preferredDimensionId != null
2763 ? normalizeDimensionId(preferredDimensionId)
2764 : null;
2765 const preferredAltars = preferred
2766 ? this.altarTiles.filter((altar) =>
2767 normalizeDimensionId(altar.dimensionId) === preferred)
2768 : [];
2769 const otherAltars = preferred
2770 ? this.altarTiles.filter((altar) =>
2771 normalizeDimensionId(altar.dimensionId) !== preferred)
2772 : this.altarTiles;
2773 for (const altar of this.#sortAltarsByDistance(preferredAltars, originX, originY))
2774 {
2775 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2658 if (tile)
2776 if (tile)
2659 { return tile; }
2777 { return tile; }
2660 }
2778 }
2779 for (const altar of this.#sortAltarsByDistance(otherAltars, originX, originY))
2780 {
2781 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2782 if (tile)
2783 { return tile; }
2784 }
2785 return null;
2786 }
2787
2788 #findSavedAltarDestination (characterId, originX, originY, entityId)
2789 {
2790 const saved = this.stateDb.getCharacterRespawnAltar(characterId);
2791 if (!saved)
2792 { return null; }
2793 const dimensionId = normalizeDimensionId(saved.dimensionId ?? OVERWORLD_ID);
2794 const altar = this.altarTiles.find((entry) =>
2795 (entry.tileX | 0) === (saved.tileX | 0)
2796 && (entry.tileY | 0) === (saved.tileY | 0)
2797 && normalizeDimensionId(entry.dimensionId) === dimensionId
2798 );
2799 if (!altar)
2800 { return null; }
2801 return this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2802 }
2803
2804 #findDeathTileFallback (originX, originY, entityId, dimensionId)
2805 {
2806 const dim = normalizeDimensionId(dimensionId);
2661 for (let radius = 0; radius <= 24; radius++)
2807 for (let radius = 0; radius <= 24; radius++)
2662 {
2808 {
2663 for (let dy = -radius; dy <= radius; dy++)
2809 for (let dy = -radius; dy <= radius; dy++)
@@ -2668,13 +2814,45 @@ export class Simulation
2668 { continue; }
2814 { continue; }
2669 const tileX = originX + dx;
2815 const tileX = originX + dx;
2670 const tileY = originY + dy;
2816 const tileY = originY + dy;
2671 if (this.isEnterable(tileX, tileY, dimensionId)
2817 if (this.isEnterable(tileX, tileY, dim)
2672 && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId))
2818 && !this.#occupiedByOther(tileX, tileY, entityId, dim))
2673 { return { tileX, tileY, dimensionId }; }
2819 { return { tileX, tileY, dimensionId: dim }; }
2674 }
2820 }
2675 }
2821 }
2676 }
2822 }
2677 return this.findOpenSpawn();
2823 return null;
2824 }
2825
2826 #findRespawnDestination (originX, originY, entityId, characterId = null)
2827 {
2828 const record = this.directory.get(entityId);
2829 const deathDimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
2830 const deathAltars = this.altarTiles.filter((altar) =>
2831 normalizeDimensionId(altar.dimensionId) === deathDimensionId
2832 );
2833 for (const altar of this.#sortAltarsByDistance(deathAltars, originX, originY))
2834 {
2835 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2836 if (tile)
2837 { return tile; }
2838 }
2839 if (characterId != null)
2840 {
2841 const saved = this.#findSavedAltarDestination(characterId, originX, originY, entityId);
2842 if (saved)
2843 { return saved; }
2844 }
2845 const otherAltars = this.altarTiles.filter((altar) =>
2846 normalizeDimensionId(altar.dimensionId) !== deathDimensionId
2847 );
2848 for (const altar of this.#sortAltarsByDistance(otherAltars, originX, originY))
2849 {
2850 const tile = this.#findAdjacentOpenToAltar(altar, originX, originY, entityId);
2851 if (tile)
2852 { return tile; }
2853 }
2854 return this.#findDeathTileFallback(originX, originY, entityId, deathDimensionId)
2855 ?? this.findOpenSpawn();
2678 }
2856 }
2679
2857
2680 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
2858 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
@@ -3402,12 +3580,16 @@ export class Simulation
3402 #findJewelryTeleportDestination (originX, originY, entityId, destination)
3580 #findJewelryTeleportDestination (originX, originY, entityId, destination)
3403 {
3581 {
3404 if (destination === "church")
3582 if (destination === "church")
3405 { return this.#findRespawnDestination(originX, originY, entityId); }
3583 {
3584 const record = this.directory.get(entityId);
3585 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3586 return this.#findNearestAltarDestination(originX, originY, entityId, dimensionId);
3587 }
3406 if (destination !== "bank")
3588 if (destination !== "bank")
3407 { return null; }
3589 { return null; }
3408 const record = this.directory.get(entityId);
3590 const record = this.directory.get(entityId);
3409 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3591 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
3410 const bank = this.courier?.nearestBank(originX, originY);
3592 const bank = this.courier?.nearestBank(originX, originY, dimensionId);
3411 if (!bank)
3593 if (!bank)
3412 { return null; }
3594 { return null; }
3413 const adjacent = [];
3595 const adjacent = [];
server/src/simulation/tileInteract.js +6 −3
@@ -1,10 +1,12 @@
1 1 import { Component } from "../ecs/components.js";
2 2 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
3 3 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
4 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
4 5
5 6 /** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */
6 export function findAdjacentBlockTile (world, tileX, tileY, blockType)
7 export function findAdjacentBlockTile (world, tileX, tileY, blockType, dimensionId = OVERWORLD_ID)
7 8 {
9 const dim = normalizeDimensionId(dimensionId);
8 10 let fallback = null;
9 11 for (let dy = -1; dy <= 1; dy++)
10 12 {
@@ -12,7 +14,7 @@ export function findAdjacentBlockTile (world, tileX, tileY, blockType)
12 14 {
13 15 const x = tileX + dx;
14 16 const y = tileY + dy;
15 const data = world.chunkData(tileToChunk(x), tileToChunk(y));
17 const data = world.chunkData(tileToChunk(x), tileToChunk(y), dim);
16 18 const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x);
17 19 if (data.blocks[index]?.typeId !== blockType)
18 20 { continue; }
@@ -42,7 +44,8 @@ export function tileShoveTowardBlock (world, handle, entityId, blockType)
42 44 const position = world.ecs.get(handle, Component.position);
43 45 if (!position)
44 46 { return null; }
45 const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType);
47 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
48 const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType, dim);
46 49 if (!target)
47 50 { return null; }
48 51 return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY);
@@ -1,10 +1,12 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { tileToChunk, tileToLocal } from "../world/coordinates.js";
2import { tileToChunk, tileToLocal } from "../world/coordinates.js";
3import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
4import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
4
5
5/** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */
6/** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */
6export function findAdjacentBlockTile (world, tileX, tileY, blockType)
7export function findAdjacentBlockTile (world, tileX, tileY, blockType, dimensionId = OVERWORLD_ID)
7{
8{
9 const dim = normalizeDimensionId(dimensionId);
8 let fallback = null;
10 let fallback = null;
9 for (let dy = -1; dy <= 1; dy++)
11 for (let dy = -1; dy <= 1; dy++)
10 {
12 {
@@ -12,7 +14,7 @@ export function findAdjacentBlockTile (world, tileX, tileY, blockType)
12 {
14 {
13 const x = tileX + dx;
15 const x = tileX + dx;
14 const y = tileY + dy;
16 const y = tileY + dy;
15 const data = world.chunkData(tileToChunk(x), tileToChunk(y));
17 const data = world.chunkData(tileToChunk(x), tileToChunk(y), dim);
16 const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x);
18 const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x);
17 if (data.blocks[index]?.typeId !== blockType)
19 if (data.blocks[index]?.typeId !== blockType)
18 { continue; }
20 { continue; }
@@ -42,7 +44,8 @@ export function tileShoveTowardBlock (world, handle, entityId, blockType)
42 const position = world.ecs.get(handle, Component.position);
44 const position = world.ecs.get(handle, Component.position);
43 if (!position)
45 if (!position)
44 { return null; }
46 { return null; }
45 const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType);
47 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
48 const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType, dim);
46 if (!target)
49 if (!target)
47 { return null; }
50 { return null; }
48 return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY);
51 return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY);
server/src/simulation/workerWorld.js +25 −13
@@ -298,9 +298,9 @@ export class WorkerWorld
298 298 for (const chunk of message.chunks ?? [])
299 299 {
300 300 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
301 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
302 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
303 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
301 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
302 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
303 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
304 304 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
305 305 data: cloneChunkData(chunk.data),
306 306 simulating: false,
@@ -319,9 +319,9 @@ export class WorkerWorld
319 319 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
320 320 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
321 321 const existing = this.chunks.get(key);
322 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
323 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
324 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
322 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
323 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
324 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
325 325 this.chunks.set(key, {
326 326 data: cloneChunkData(chunk.data),
327 327 simulating: existing?.simulating ?? false,
@@ -356,9 +356,9 @@ export class WorkerWorld
356 356 { continue; }
357 357 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
358 358 {
359 clearOreRespawnsForChunk(this, chunkX, chunkY);
360 clearTreeRespawnsForChunk(this, chunkX, chunkY);
361 clearPlantRespawnsForChunk(this, chunkX, chunkY);
359 clearOreRespawnsForChunk(this, chunkX, chunkY, dimensionId);
360 clearTreeRespawnsForChunk(this, chunkX, chunkY, dimensionId);
361 clearPlantRespawnsForChunk(this, chunkX, chunkY, dimensionId);
362 362 this.chunks.delete(key);
363 363 }
364 364 }
@@ -639,6 +639,8 @@ export class WorkerWorld
639 639 const position = this.ecs.get(handle, Component.position);
640 640 const fromTileX = position.tileX;
641 641 const fromTileY = position.tileY;
642 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
643 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
642 644 const health = this.ecs.get(handle, Component.health);
643 645 const stamina = this.ecs.get(handle, Component.stamina);
644 646 if (health)
@@ -662,22 +664,26 @@ export class WorkerWorld
662 664
663 665 const destRegionX = tileToRegion(message.tileX);
664 666 const destRegionY = tileToRegion(message.tileY);
665 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
666 667 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
667 668 {
668 669 this.frozen.add(message.entityId);
670 const payload = serializeEntity(this.ecs, message.entityId);
671 payload.components.position.tileX = message.tileX | 0;
672 payload.components.position.tileY = message.tileY | 0;
673 payload.components.position.dimensionId = dimensionId;
669 674 return {
670 675 accepted: true,
671 676 transferRequest: {
672 677 entityId: message.entityId,
673 678 fromTileX,
674 679 fromTileY,
680 fromDimensionId,
675 681 destTileX: message.tileX,
676 682 destTileY: message.tileY,
677 683 toRegionX: destRegionX,
678 684 toRegionY: destRegionY,
679 685 dimensionId,
680 payload: serializeEntity(this.ecs, message.entityId)
686 payload
681 687 }
682 688 };
683 689 }
@@ -686,6 +692,7 @@ export class WorkerWorld
686 692 this.#vacate(message.entityId, fromTileX, fromTileY);
687 693 position.tileX = message.tileX;
688 694 position.tileY = message.tileY;
695 position.dimensionId = dimensionId;
689 696 syncCharacterChunkPresence(this.ecs, handle, Date.now());
690 697 this.#occupy(message.entityId, position.tileX, position.tileY);
691 698 return {
@@ -695,6 +702,7 @@ export class WorkerWorld
695 702 entityId: message.entityId,
696 703 fromTileX,
697 704 fromTileY,
705 fromDimensionId,
698 706 tileX: position.tileX,
699 707 tileY: position.tileY,
700 708 dimensionId,
@@ -1923,13 +1931,14 @@ export class WorkerWorld
1923 1931
1924 1932 /**
1925 1933 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1926 * message: { stationTileX, stationTileY }
1934 * message: { stationTileX, stationTileY, dimensionId? }
1927 1935 */
1928 1936 #stationExchangeClerk (message)
1929 1937 {
1930 1938 const stationTileX = message.stationTileX | 0;
1931 1939 const stationTileY = message.stationTileY | 0;
1932 if (!this.isEnterable(stationTileX, stationTileY))
1940 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1941 if (!this.isEnterable(stationTileX, stationTileY, dim))
1933 1942 { return { ok: false, reason: "blocked" }; }
1934 1943
1935 1944 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
@@ -1952,6 +1961,9 @@ export class WorkerWorld
1952 1961 { continue; }
1953 1962 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1954 1963 { continue; }
1964 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1965 if (entityDim !== dim)
1966 { continue; }
1955 1967 const dist = Math.max(
1956 1968 Math.abs(entity.position.tileX - stationTileX),
1957 1969 Math.abs(entity.position.tileY - stationTileY)
@@ -298,9 +298,9 @@ export class WorkerWorld
298 for (const chunk of message.chunks ?? [])
298 for (const chunk of message.chunks ?? [])
299 {
299 {
300 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
300 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
301 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
301 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
302 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
302 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
303 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
303 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
304 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
304 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
305 data: cloneChunkData(chunk.data),
305 data: cloneChunkData(chunk.data),
306 simulating: false,
306 simulating: false,
@@ -319,9 +319,9 @@ export class WorkerWorld
319 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
319 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
320 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
320 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
321 const existing = this.chunks.get(key);
321 const existing = this.chunks.get(key);
322 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
322 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
323 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
323 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
324 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
324 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY, chunkDim);
325 this.chunks.set(key, {
325 this.chunks.set(key, {
326 data: cloneChunkData(chunk.data),
326 data: cloneChunkData(chunk.data),
327 simulating: existing?.simulating ?? false,
327 simulating: existing?.simulating ?? false,
@@ -356,9 +356,9 @@ export class WorkerWorld
356 { continue; }
356 { continue; }
357 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
357 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
358 {
358 {
359 clearOreRespawnsForChunk(this, chunkX, chunkY);
359 clearOreRespawnsForChunk(this, chunkX, chunkY, dimensionId);
360 clearTreeRespawnsForChunk(this, chunkX, chunkY);
360 clearTreeRespawnsForChunk(this, chunkX, chunkY, dimensionId);
361 clearPlantRespawnsForChunk(this, chunkX, chunkY);
361 clearPlantRespawnsForChunk(this, chunkX, chunkY, dimensionId);
362 this.chunks.delete(key);
362 this.chunks.delete(key);
363 }
363 }
364 }
364 }
@@ -639,6 +639,8 @@ export class WorkerWorld
639 const position = this.ecs.get(handle, Component.position);
639 const position = this.ecs.get(handle, Component.position);
640 const fromTileX = position.tileX;
640 const fromTileX = position.tileX;
641 const fromTileY = position.tileY;
641 const fromTileY = position.tileY;
642 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
643 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
642 const health = this.ecs.get(handle, Component.health);
644 const health = this.ecs.get(handle, Component.health);
643 const stamina = this.ecs.get(handle, Component.stamina);
645 const stamina = this.ecs.get(handle, Component.stamina);
644 if (health)
646 if (health)
@@ -662,22 +664,26 @@ export class WorkerWorld
662
664
663 const destRegionX = tileToRegion(message.tileX);
665 const destRegionX = tileToRegion(message.tileX);
664 const destRegionY = tileToRegion(message.tileY);
666 const destRegionY = tileToRegion(message.tileY);
665 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
666 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
667 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
667 {
668 {
668 this.frozen.add(message.entityId);
669 this.frozen.add(message.entityId);
670 const payload = serializeEntity(this.ecs, message.entityId);
671 payload.components.position.tileX = message.tileX | 0;
672 payload.components.position.tileY = message.tileY | 0;
673 payload.components.position.dimensionId = dimensionId;
669 return {
674 return {
670 accepted: true,
675 accepted: true,
671 transferRequest: {
676 transferRequest: {
672 entityId: message.entityId,
677 entityId: message.entityId,
673 fromTileX,
678 fromTileX,
674 fromTileY,
679 fromTileY,
680 fromDimensionId,
675 destTileX: message.tileX,
681 destTileX: message.tileX,
676 destTileY: message.tileY,
682 destTileY: message.tileY,
677 toRegionX: destRegionX,
683 toRegionX: destRegionX,
678 toRegionY: destRegionY,
684 toRegionY: destRegionY,
679 dimensionId,
685 dimensionId,
680 payload: serializeEntity(this.ecs, message.entityId)
686 payload
681 }
687 }
682 };
688 };
683 }
689 }
@@ -686,6 +692,7 @@ export class WorkerWorld
686 this.#vacate(message.entityId, fromTileX, fromTileY);
692 this.#vacate(message.entityId, fromTileX, fromTileY);
687 position.tileX = message.tileX;
693 position.tileX = message.tileX;
688 position.tileY = message.tileY;
694 position.tileY = message.tileY;
695 position.dimensionId = dimensionId;
689 syncCharacterChunkPresence(this.ecs, handle, Date.now());
696 syncCharacterChunkPresence(this.ecs, handle, Date.now());
690 this.#occupy(message.entityId, position.tileX, position.tileY);
697 this.#occupy(message.entityId, position.tileX, position.tileY);
691 return {
698 return {
@@ -695,6 +702,7 @@ export class WorkerWorld
695 entityId: message.entityId,
702 entityId: message.entityId,
696 fromTileX,
703 fromTileX,
697 fromTileY,
704 fromTileY,
705 fromDimensionId,
698 tileX: position.tileX,
706 tileX: position.tileX,
699 tileY: position.tileY,
707 tileY: position.tileY,
700 dimensionId,
708 dimensionId,
@@ -1923,13 +1931,14 @@ export class WorkerWorld
1923
1931
1924 /**
1932 /**
1925 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1933 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1926 * message: { stationTileX, stationTileY }
1934 * message: { stationTileX, stationTileY, dimensionId? }
1927 */
1935 */
1928 #stationExchangeClerk (message)
1936 #stationExchangeClerk (message)
1929 {
1937 {
1930 const stationTileX = message.stationTileX | 0;
1938 const stationTileX = message.stationTileX | 0;
1931 const stationTileY = message.stationTileY | 0;
1939 const stationTileY = message.stationTileY | 0;
1932 if (!this.isEnterable(stationTileX, stationTileY))
1940 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1941 if (!this.isEnterable(stationTileX, stationTileY, dim))
1933 { return { ok: false, reason: "blocked" }; }
1942 { return { ok: false, reason: "blocked" }; }
1934
1943
1935 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1944 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
@@ -1952,6 +1961,9 @@ export class WorkerWorld
1952 { continue; }
1961 { continue; }
1953 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1962 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1954 { continue; }
1963 { continue; }
1964 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1965 if (entityDim !== dim)
1966 { continue; }
1955 const dist = Math.max(
1967 const dist = Math.max(
1956 Math.abs(entity.position.tileX - stationTileX),
1968 Math.abs(entity.position.tileX - stationTileX),
1957 Math.abs(entity.position.tileY - stationTileY)
1969 Math.abs(entity.position.tileY - stationTileY)
server/src/spells/tinders.js +22 −10
@@ -19,6 +19,7 @@ import
19 19 } from "../items/bags.js";
20 20 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
21 21 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
22 23
23 24 const TINDERS_COOK_BURN_CHANCE = 0.4;
24 25 const COOK_DIFFICULTY = 1;
@@ -42,24 +43,26 @@ function groundItemsAt (world, tileX, tileY)
42 43 return out;
43 44 }
44 45
45 function blockAt (world, tileX, tileY)
46 function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
46 47 {
48 const dim = normalizeDimensionId(dimensionId);
47 49 const chunkX = tileToChunk(tileX);
48 50 const chunkY = tileToChunk(tileY);
49 const data = world.chunkData?.(chunkX, chunkY);
51 const data = world.chunkData?.(chunkX, chunkY, dim);
50 52 if (!data)
51 53 { return null; }
52 54 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
53 55 return data.blocks?.[index] ?? null;
54 56 }
55 57
56 function placeCampfire (world, tileX, tileY, woodTier, litByName, now)
58 function placeCampfire (world, tileX, tileY, woodTier, litByName, now, dimensionId = OVERWORLD_ID)
57 59 {
60 const dim = normalizeDimensionId(dimensionId);
58 61 const chunkX = tileToChunk(tileX);
59 62 const chunkY = tileToChunk(tileY);
60 63 const localX = tileToLocal(tileX);
61 64 const localY = tileToLocal(tileY);
62 const data = world.chunkData(chunkX, chunkY);
65 const data = world.chunkData(chunkX, chunkY, dim);
63 66 const index = localY * CHUNK_SIZE + localX;
64 67 const expiresAt = now + campfireDurationMs(woodTier);
65 68 const block = {
@@ -70,9 +73,10 @@ function placeCampfire (world, tileX, tileY, woodTier, litByName, now)
70 73 data.blocks[index] = block;
71 74 if (!world.campfireExpires)
72 75 { world.campfireExpires = new Map(); }
73 world.campfireExpires.set(`${tileX},${tileY}`, {
76 world.campfireExpires.set(`${dim}:${tileX},${tileY}`, {
74 77 tileX,
75 78 tileY,
79 dimensionId: dim,
76 80 woodTier,
77 81 expiresAt,
78 82 litByName
@@ -81,6 +85,7 @@ function placeCampfire (world, tileX, tileY, woodTier, litByName, now)
81 85 type: "chunk-delta",
82 86 chunkX,
83 87 chunkY,
88 dimensionId: dim,
84 89 tileX,
85 90 tileY,
86 91 localX,
@@ -148,9 +153,10 @@ function spawnGroundStack (world, tileX, tileY, stack, now, events)
148 153 * True while Tinders still has work on this tile (unlit logs or raw food).
149 154 * Used to stop auto-cast once a campfire is lit or nothing remains.
150 155 */
151 export function tindersTileStillNeedsCast (world, tileX, tileY)
156 export function tindersTileStillNeedsCast (world, tileX, tileY, dimensionId = OVERWORLD_ID)
152 157 {
153 if (blockAt(world, tileX, tileY)?.typeId === BlockType.campfire)
158 const dim = normalizeDimensionId(dimensionId);
159 if (blockAt(world, tileX, tileY, dim)?.typeId === BlockType.campfire)
154 160 { return false; }
155 161 const items = groundItemsAt(world, tileX, tileY);
156 162 if (items.some((item) => woodTierFromLogItemId(item.stack?.itemId)))
@@ -168,6 +174,13 @@ export function applyTindersAtTile (world, impact, now)
168 174 const events = [];
169 175 const tileX = impact.targetTileX | 0;
170 176 const tileY = impact.targetTileY | 0;
177 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
178 const casterPos = casterHandle != null
179 ? world.ecs.get(casterHandle, Component.position)
180 : null;
181 const dim = normalizeDimensionId(
182 impact.dimensionId ?? casterPos?.dimensionId ?? OVERWORLD_ID
183 );
171 184 const mind = impact.levels?.mind | 0 || 0;
172 185 const rng = world.rng ?? Math.random;
173 186 const items = groundItemsAt(world, tileX, tileY);
@@ -187,7 +200,7 @@ export function applyTindersAtTile (world, impact, now)
187 200 });
188 201 return events;
189 202 }
190 if (blockAt(world, tileX, tileY))
203 if (blockAt(world, tileX, tileY, dim))
191 204 {
192 205 events.push({
193 206 type: "command-error",
@@ -207,7 +220,6 @@ export function applyTindersAtTile (world, impact, now)
207 220 return events;
208 221 }
209 222 consumeOneGroundStack(world, logItem, events);
210 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
211 223 const appearance = casterHandle != null
212 224 ? world.ecs.get(casterHandle, Component.appearance)
213 225 : null;
@@ -215,7 +227,7 @@ export function applyTindersAtTile (world, impact, now)
215 227 .filter(Boolean)
216 228 .join(" ")
217 229 .trim() || "someone";
218 events.push(placeCampfire(world, tileX, tileY, woodTier, litByName, now));
230 events.push(placeCampfire(world, tileX, tileY, woodTier, litByName, now, dim));
219 231 return events;
220 232 }
221 233
@@ -19,6 +19,7 @@ import
19} from "../items/bags.js";
19} from "../items/bags.js";
20import { tileToChunk, tileToLocal } from "../world/coordinates.js";
20import { tileToChunk, tileToLocal } from "../world/coordinates.js";
21import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
21import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
22
23
23const TINDERS_COOK_BURN_CHANCE = 0.4;
24const TINDERS_COOK_BURN_CHANCE = 0.4;
24const COOK_DIFFICULTY = 1;
25const COOK_DIFFICULTY = 1;
@@ -42,24 +43,26 @@ function groundItemsAt (world, tileX, tileY)
42 return out;
43 return out;
43}
44}
44
45
45function blockAt (world, tileX, tileY)
46function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
46{
47{
48 const dim = normalizeDimensionId(dimensionId);
47 const chunkX = tileToChunk(tileX);
49 const chunkX = tileToChunk(tileX);
48 const chunkY = tileToChunk(tileY);
50 const chunkY = tileToChunk(tileY);
49 const data = world.chunkData?.(chunkX, chunkY);
51 const data = world.chunkData?.(chunkX, chunkY, dim);
50 if (!data)
52 if (!data)
51 { return null; }
53 { return null; }
52 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
54 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
53 return data.blocks?.[index] ?? null;
55 return data.blocks?.[index] ?? null;
54}
56}
55
57
56function placeCampfire (world, tileX, tileY, woodTier, litByName, now)
58function placeCampfire (world, tileX, tileY, woodTier, litByName, now, dimensionId = OVERWORLD_ID)
57{
59{
60 const dim = normalizeDimensionId(dimensionId);
58 const chunkX = tileToChunk(tileX);
61 const chunkX = tileToChunk(tileX);
59 const chunkY = tileToChunk(tileY);
62 const chunkY = tileToChunk(tileY);
60 const localX = tileToLocal(tileX);
63 const localX = tileToLocal(tileX);
61 const localY = tileToLocal(tileY);
64 const localY = tileToLocal(tileY);
62 const data = world.chunkData(chunkX, chunkY);
65 const data = world.chunkData(chunkX, chunkY, dim);
63 const index = localY * CHUNK_SIZE + localX;
66 const index = localY * CHUNK_SIZE + localX;
64 const expiresAt = now + campfireDurationMs(woodTier);
67 const expiresAt = now + campfireDurationMs(woodTier);
65 const block = {
68 const block = {
@@ -70,9 +73,10 @@ function placeCampfire (world, tileX, tileY, woodTier, litByName, now)
70 data.blocks[index] = block;
73 data.blocks[index] = block;
71 if (!world.campfireExpires)
74 if (!world.campfireExpires)
72 { world.campfireExpires = new Map(); }
75 { world.campfireExpires = new Map(); }
73 world.campfireExpires.set(`${tileX},${tileY}`, {
76 world.campfireExpires.set(`${dim}:${tileX},${tileY}`, {
74 tileX,
77 tileX,
75 tileY,
78 tileY,
79 dimensionId: dim,
76 woodTier,
80 woodTier,
77 expiresAt,
81 expiresAt,
78 litByName
82 litByName
@@ -81,6 +85,7 @@ function placeCampfire (world, tileX, tileY, woodTier, litByName, now)
81 type: "chunk-delta",
85 type: "chunk-delta",
82 chunkX,
86 chunkX,
83 chunkY,
87 chunkY,
88 dimensionId: dim,
84 tileX,
89 tileX,
85 tileY,
90 tileY,
86 localX,
91 localX,
@@ -148,9 +153,10 @@ function spawnGroundStack (world, tileX, tileY, stack, now, events)
148 * True while Tinders still has work on this tile (unlit logs or raw food).
153 * True while Tinders still has work on this tile (unlit logs or raw food).
149 * Used to stop auto-cast once a campfire is lit or nothing remains.
154 * Used to stop auto-cast once a campfire is lit or nothing remains.
150 */
155 */
151export function tindersTileStillNeedsCast (world, tileX, tileY)
156export function tindersTileStillNeedsCast (world, tileX, tileY, dimensionId = OVERWORLD_ID)
152{
157{
153 if (blockAt(world, tileX, tileY)?.typeId === BlockType.campfire)
158 const dim = normalizeDimensionId(dimensionId);
159 if (blockAt(world, tileX, tileY, dim)?.typeId === BlockType.campfire)
154 { return false; }
160 { return false; }
155 const items = groundItemsAt(world, tileX, tileY);
161 const items = groundItemsAt(world, tileX, tileY);
156 if (items.some((item) => woodTierFromLogItemId(item.stack?.itemId)))
162 if (items.some((item) => woodTierFromLogItemId(item.stack?.itemId)))
@@ -168,6 +174,13 @@ export function applyTindersAtTile (world, impact, now)
168 const events = [];
174 const events = [];
169 const tileX = impact.targetTileX | 0;
175 const tileX = impact.targetTileX | 0;
170 const tileY = impact.targetTileY | 0;
176 const tileY = impact.targetTileY | 0;
177 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
178 const casterPos = casterHandle != null
179 ? world.ecs.get(casterHandle, Component.position)
180 : null;
181 const dim = normalizeDimensionId(
182 impact.dimensionId ?? casterPos?.dimensionId ?? OVERWORLD_ID
183 );
171 const mind = impact.levels?.mind | 0 || 0;
184 const mind = impact.levels?.mind | 0 || 0;
172 const rng = world.rng ?? Math.random;
185 const rng = world.rng ?? Math.random;
173 const items = groundItemsAt(world, tileX, tileY);
186 const items = groundItemsAt(world, tileX, tileY);
@@ -187,7 +200,7 @@ export function applyTindersAtTile (world, impact, now)
187 });
200 });
188 return events;
201 return events;
189 }
202 }
190 if (blockAt(world, tileX, tileY))
203 if (blockAt(world, tileX, tileY, dim))
191 {
204 {
192 events.push({
205 events.push({
193 type: "command-error",
206 type: "command-error",
@@ -207,7 +220,6 @@ export function applyTindersAtTile (world, impact, now)
207 return events;
220 return events;
208 }
221 }
209 consumeOneGroundStack(world, logItem, events);
222 consumeOneGroundStack(world, logItem, events);
210 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
211 const appearance = casterHandle != null
223 const appearance = casterHandle != null
212 ? world.ecs.get(casterHandle, Component.appearance)
224 ? world.ecs.get(casterHandle, Component.appearance)
213 : null;
225 : null;
@@ -215,7 +227,7 @@ export function applyTindersAtTile (world, impact, now)
215 .filter(Boolean)
227 .filter(Boolean)
216 .join(" ")
228 .join(" ")
217 .trim() || "someone";
229 .trim() || "someone";
218 events.push(placeCampfire(world, tileX, tileY, woodTier, litByName, now));
230 events.push(placeCampfire(world, tileX, tileY, woodTier, litByName, now, dim));
219 return events;
231 return events;
220 }
232 }
221
233
server/src/world/chunkData.js +3 −1
@@ -6,6 +6,7 @@ import {
6 6 blockLightOcclusionForBlock,
7 7 LightOcclusion,
8 8 isGroundPassable,
9 isWaterGround,
9 10 blockBlocksRangedAttacks,
10 11 normalizeGround,
11 12 normalizeBlock
@@ -203,7 +204,8 @@ export function isChunkTileClearForRangedAttacks (data, localX, localY)
203 204 {
204 205 const index = tileIndex(localX, localY);
205 206 const ground = normalizeGround(data.grounds[index]);
206 if (!isGroundPassable(ground.typeId))
207 // Deep (and shallow) water blocks walking but not projectiles / spell rays.
208 if (!isGroundPassable(ground.typeId) && !isWaterGround(ground.typeId))
207 209 { return false; }
208 210 const block = data.blocks[index];
209 211 return !blockBlocksRangedAttacks(block?.typeId ?? null, block?.state ?? null, block);
@@ -6,6 +6,7 @@ import {
6 blockLightOcclusionForBlock,
6 blockLightOcclusionForBlock,
7 LightOcclusion,
7 LightOcclusion,
8 isGroundPassable,
8 isGroundPassable,
9 isWaterGround,
9 blockBlocksRangedAttacks,
10 blockBlocksRangedAttacks,
10 normalizeGround,
11 normalizeGround,
11 normalizeBlock
12 normalizeBlock
@@ -203,7 +204,8 @@ export function isChunkTileClearForRangedAttacks (data, localX, localY)
203{
204{
204 const index = tileIndex(localX, localY);
205 const index = tileIndex(localX, localY);
205 const ground = normalizeGround(data.grounds[index]);
206 const ground = normalizeGround(data.grounds[index]);
206 if (!isGroundPassable(ground.typeId))
207 // Deep (and shallow) water blocks walking but not projectiles / spell rays.
208 if (!isGroundPassable(ground.typeId) && !isWaterGround(ground.typeId))
207 { return false; }
209 { return false; }
208 const block = data.blocks[index];
210 const block = data.blocks[index];
209 return !blockBlocksRangedAttacks(block?.typeId ?? null, block?.state ?? null, block);
211 return !blockBlocksRangedAttacks(block?.typeId ?? null, block?.state ?? null, block);
server/tests/altar-respawn.test.js added +177 −0
@@ -0,0 +1,177 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { BlockType } from "../../shared/definitions/tiles.js";
7 import { OVERWORLD_ID, DimensionLightingMode, DimensionSeasonMode } from "../../shared/world/dimensions.js";
8 import { WorldDatabase } from "../src/persistence/worldDb.js";
9 import { StateDatabase } from "../src/persistence/stateDb.js";
10 import { Simulation } from "../src/simulation/simulation.js";
11 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
12 import { Component } from "../src/ecs/components.js";
13 import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
14
15 const CAVE_ID = "altar-cave";
16
17 function placeAltar (worldDb, tileX, tileY, dimensionId = OVERWORLD_ID)
18 {
19 const chunkX = Math.floor(tileX / 16);
20 const chunkY = Math.floor(tileY / 16);
21 const data = createEmptyChunkData();
22 data.open = true;
23 data.blocks[(tileY - chunkY * 16) * 16 + (tileX - chunkX * 16)] = {
24 typeId: BlockType.churchAltar,
25 state: 0
26 };
27 worldDb.saveChunkVersion(
28 chunkX,
29 chunkY,
30 worldDb.getActiveRevisionId(),
31 true,
32 encodeChunkBlob(data),
33 dimensionId
34 );
35 }
36
37 function makeAltarHarness ()
38 {
39 const dir = mkdtempSync(join(tmpdir(), "mmo-altar-respawn-"));
40 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
41 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
42 openChunkStrip(worldDb, 2);
43 const rev = worldDb.getActiveRevisionId();
44 worldDb.saveDimension(rev, {
45 dimensionId: CAVE_ID,
46 displayName: "Altar Cave",
47 lightingMode: DimensionLightingMode.alwaysLit,
48 seasonMode: DimensionSeasonMode.summer,
49 defaultGroundTypeId: 1
50 });
51 writeOpenChunk(worldDb, 0, 0);
52 const cave = createEmptyChunkData();
53 cave.open = true;
54 worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(cave), CAVE_ID);
55 placeAltar(worldDb, 20, 8, OVERWORLD_ID);
56 let now = 1_000;
57 const simulation = new Simulation(worldDb, stateDb, {
58 workerCount: 1,
59 workerMode: "inprocess",
60 now: () => now
61 });
62 return {
63 simulation,
64 worldDb,
65 stateDb,
66 advance (ms)
67 {
68 now += ms;
69 },
70 close ()
71 {
72 simulation.forceUnloadAll();
73 worldDb.close();
74 stateDb.close();
75 }
76 };
77 }
78
79 function markDead (simulation, stateDb, characterId, playerId)
80 {
81 const record = simulation.entityRecord(playerId);
82 const worker = simulation.workers[record.workerId];
83 const handle = worker.world.ecs.handleOf(playerId);
84 if (!worker.world.ecs.has(handle, Component.dead))
85 { worker.world.ecs.add(handle, Component.dead, {}); }
86 stateDb.setCharacterDead(characterId, true);
87 }
88
89 function componentsOf (simulation, entityId)
90 {
91 const record = simulation.entityRecord(entityId);
92 const worker = simulation.workers[record.workerId];
93 const handle = worker.world.ecs.handleOf(entityId);
94 return worker.world.ecs.componentsOf(handle);
95 }
96
97 test("pray at altar sets the bound respawn point and toasts", () =>
98 {
99 const harness = makeAltarHarness();
100 try
101 {
102 const character = makeCharacter(harness.stateDb, { tileX: 19, tileY: 8 });
103 harness.simulation.spawnCharacter(1, character);
104 harness.simulation.enqueue(1, {
105 type: "pray-at-altar",
106 characterId: character.character_id,
107 tileX: 20,
108 tileY: 8
109 });
110 const result = harness.simulation.step();
111 assert.ok(result.events.some((event) =>
112 event.type === "toast"
113 && event.message === "Altar set as respawn point."
114 ));
115 assert.deepEqual(harness.stateDb.getCharacterRespawnAltar(character.character_id), {
116 tileX: 20,
117 tileY: 8,
118 dimensionId: OVERWORLD_ID
119 });
120 }
121 finally
122 { harness.close(); }
123 });
124
125 test("death in a dimension without altars respawns at the bound altar", () =>
126 {
127 const harness = makeAltarHarness();
128 try
129 {
130 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
131 harness.stateDb.setCharacterRespawnAltar(character.character_id, 20, 8, OVERWORLD_ID);
132 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
133 const playerId = harness.simulation.spawnCharacter(1, character);
134 assert.equal(harness.simulation.positionOf(playerId).dimensionId, CAVE_ID);
135 markDead(harness.simulation, harness.stateDb, character.character_id, playerId);
136
137 harness.simulation.enqueue(1, { type: "respawn", characterId: character.character_id });
138 const result = harness.simulation.step();
139 assert.ok(result.events.some((event) => event.type === "player-respawned"));
140 assert.ok(result.events.some((event) =>
141 event.type === "dimension-changed" && event.dimensionId === OVERWORLD_ID
142 ));
143 const player = componentsOf(harness.simulation, playerId);
144 assert.equal(player.position.dimensionId, OVERWORLD_ID);
145 assert.equal(
146 Math.max(Math.abs(player.position.tileX - 20), Math.abs(player.position.tileY - 8)),
147 1
148 );
149 assert.deepEqual(harness.stateDb.getCharacterRespawnAltar(character.character_id), {
150 tileX: 20,
151 tileY: 8,
152 dimensionId: OVERWORLD_ID
153 });
154 }
155 finally
156 { harness.close(); }
157 });
158
159 test("respawn beside an altar remembers that altar for later deaths", () =>
160 {
161 const harness = makeAltarHarness();
162 try
163 {
164 const character = makeCharacter(harness.stateDb, { tileX: 19, tileY: 8 });
165 const playerId = harness.simulation.spawnCharacter(1, character);
166 markDead(harness.simulation, harness.stateDb, character.character_id, playerId);
167 harness.simulation.enqueue(1, { type: "respawn", characterId: character.character_id });
168 harness.simulation.step();
169 assert.deepEqual(harness.stateDb.getCharacterRespawnAltar(character.character_id), {
170 tileX: 20,
171 tileY: 8,
172 dimensionId: OVERWORLD_ID
173 });
174 }
175 finally
176 { harness.close(); }
177 });
@@ -0,0 +1,177 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { BlockType } from "../../shared/definitions/tiles.js";
7import { OVERWORLD_ID, DimensionLightingMode, DimensionSeasonMode } from "../../shared/world/dimensions.js";
8import { WorldDatabase } from "../src/persistence/worldDb.js";
9import { StateDatabase } from "../src/persistence/stateDb.js";
10import { Simulation } from "../src/simulation/simulation.js";
11import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
12import { Component } from "../src/ecs/components.js";
13import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
14
15const CAVE_ID = "altar-cave";
16
17function placeAltar (worldDb, tileX, tileY, dimensionId = OVERWORLD_ID)
18{
19 const chunkX = Math.floor(tileX / 16);
20 const chunkY = Math.floor(tileY / 16);
21 const data = createEmptyChunkData();
22 data.open = true;
23 data.blocks[(tileY - chunkY * 16) * 16 + (tileX - chunkX * 16)] = {
24 typeId: BlockType.churchAltar,
25 state: 0
26 };
27 worldDb.saveChunkVersion(
28 chunkX,
29 chunkY,
30 worldDb.getActiveRevisionId(),
31 true,
32 encodeChunkBlob(data),
33 dimensionId
34 );
35}
36
37function makeAltarHarness ()
38{
39 const dir = mkdtempSync(join(tmpdir(), "mmo-altar-respawn-"));
40 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
41 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
42 openChunkStrip(worldDb, 2);
43 const rev = worldDb.getActiveRevisionId();
44 worldDb.saveDimension(rev, {
45 dimensionId: CAVE_ID,
46 displayName: "Altar Cave",
47 lightingMode: DimensionLightingMode.alwaysLit,
48 seasonMode: DimensionSeasonMode.summer,
49 defaultGroundTypeId: 1
50 });
51 writeOpenChunk(worldDb, 0, 0);
52 const cave = createEmptyChunkData();
53 cave.open = true;
54 worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(cave), CAVE_ID);
55 placeAltar(worldDb, 20, 8, OVERWORLD_ID);
56 let now = 1_000;
57 const simulation = new Simulation(worldDb, stateDb, {
58 workerCount: 1,
59 workerMode: "inprocess",
60 now: () => now
61 });
62 return {
63 simulation,
64 worldDb,
65 stateDb,
66 advance (ms)
67 {
68 now += ms;
69 },
70 close ()
71 {
72 simulation.forceUnloadAll();
73 worldDb.close();
74 stateDb.close();
75 }
76 };
77}
78
79function markDead (simulation, stateDb, characterId, playerId)
80{
81 const record = simulation.entityRecord(playerId);
82 const worker = simulation.workers[record.workerId];
83 const handle = worker.world.ecs.handleOf(playerId);
84 if (!worker.world.ecs.has(handle, Component.dead))
85 { worker.world.ecs.add(handle, Component.dead, {}); }
86 stateDb.setCharacterDead(characterId, true);
87}
88
89function componentsOf (simulation, entityId)
90{
91 const record = simulation.entityRecord(entityId);
92 const worker = simulation.workers[record.workerId];
93 const handle = worker.world.ecs.handleOf(entityId);
94 return worker.world.ecs.componentsOf(handle);
95}
96
97test("pray at altar sets the bound respawn point and toasts", () =>
98{
99 const harness = makeAltarHarness();
100 try
101 {
102 const character = makeCharacter(harness.stateDb, { tileX: 19, tileY: 8 });
103 harness.simulation.spawnCharacter(1, character);
104 harness.simulation.enqueue(1, {
105 type: "pray-at-altar",
106 characterId: character.character_id,
107 tileX: 20,
108 tileY: 8
109 });
110 const result = harness.simulation.step();
111 assert.ok(result.events.some((event) =>
112 event.type === "toast"
113 && event.message === "Altar set as respawn point."
114 ));
115 assert.deepEqual(harness.stateDb.getCharacterRespawnAltar(character.character_id), {
116 tileX: 20,
117 tileY: 8,
118 dimensionId: OVERWORLD_ID
119 });
120 }
121 finally
122 { harness.close(); }
123});
124
125test("death in a dimension without altars respawns at the bound altar", () =>
126{
127 const harness = makeAltarHarness();
128 try
129 {
130 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
131 harness.stateDb.setCharacterRespawnAltar(character.character_id, 20, 8, OVERWORLD_ID);
132 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
133 const playerId = harness.simulation.spawnCharacter(1, character);
134 assert.equal(harness.simulation.positionOf(playerId).dimensionId, CAVE_ID);
135 markDead(harness.simulation, harness.stateDb, character.character_id, playerId);
136
137 harness.simulation.enqueue(1, { type: "respawn", characterId: character.character_id });
138 const result = harness.simulation.step();
139 assert.ok(result.events.some((event) => event.type === "player-respawned"));
140 assert.ok(result.events.some((event) =>
141 event.type === "dimension-changed" && event.dimensionId === OVERWORLD_ID
142 ));
143 const player = componentsOf(harness.simulation, playerId);
144 assert.equal(player.position.dimensionId, OVERWORLD_ID);
145 assert.equal(
146 Math.max(Math.abs(player.position.tileX - 20), Math.abs(player.position.tileY - 8)),
147 1
148 );
149 assert.deepEqual(harness.stateDb.getCharacterRespawnAltar(character.character_id), {
150 tileX: 20,
151 tileY: 8,
152 dimensionId: OVERWORLD_ID
153 });
154 }
155 finally
156 { harness.close(); }
157});
158
159test("respawn beside an altar remembers that altar for later deaths", () =>
160{
161 const harness = makeAltarHarness();
162 try
163 {
164 const character = makeCharacter(harness.stateDb, { tileX: 19, tileY: 8 });
165 const playerId = harness.simulation.spawnCharacter(1, character);
166 markDead(harness.simulation, harness.stateDb, character.character_id, playerId);
167 harness.simulation.enqueue(1, { type: "respawn", characterId: character.character_id });
168 harness.simulation.step();
169 assert.deepEqual(harness.stateDb.getCharacterRespawnAltar(character.character_id), {
170 tileX: 20,
171 tileY: 8,
172 dimensionId: OVERWORLD_ID
173 });
174 }
175 finally
176 { harness.close(); }
177});
server/tests/dimension-interactions.test.js added +145 −0
@@ -0,0 +1,145 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { BlockType } from "../../shared/definitions/tiles.js";
7 import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
8 import { MobId } from "../../shared/definitions/mobs.js";
9 import { OVERWORLD_ID, DimensionLightingMode, DimensionSeasonMode } from "../../shared/world/dimensions.js";
10 import { WorldDatabase } from "../src/persistence/worldDb.js";
11 import { StateDatabase } from "../src/persistence/stateDb.js";
12 import { Simulation } from "../src/simulation/simulation.js";
13 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
14 import { mobComponents } from "../src/simulation/spawners.js";
15 import { engageTarget, ensureMobCombat, stepCombat, stepAggression } from "../src/combat/service.js";
16 import { Component } from "../src/ecs/components.js";
17 import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
18
19 const CAVE_ID = "test-cave";
20
21 function makeCaveHarness ()
22 {
23 const dir = mkdtempSync(join(tmpdir(), "mmo-dim-interact-"));
24 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
25 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
26 openChunkStrip(worldDb, 2);
27 const rev = worldDb.getActiveRevisionId();
28 worldDb.saveDimension(rev, {
29 dimensionId: CAVE_ID,
30 displayName: "Test Cave",
31 lightingMode: DimensionLightingMode.alwaysLit,
32 seasonMode: DimensionSeasonMode.summer,
33 defaultGroundTypeId: 1
34 });
35 const cave = createEmptyChunkData();
36 cave.open = true;
37 cave.blocks[8 * 16 + 9] = {
38 typeId: BlockType.furnace,
39 state: "furnace",
40 config: null
41 };
42 worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(cave), CAVE_ID);
43 writeOpenChunk(worldDb, 0, 0);
44 let now = 1_000;
45 const simulation = new Simulation(worldDb, stateDb, {
46 workerCount: 1,
47 workerMode: "inprocess",
48 now: () => now
49 });
50 return {
51 simulation,
52 worldDb,
53 stateDb,
54 now ()
55 {
56 return now;
57 },
58 advance (ms)
59 {
60 now += ms;
61 },
62 close ()
63 {
64 simulation.forceUnloadAll();
65 worldDb.close();
66 stateDb.close();
67 }
68 };
69 }
70
71 function workerOf (simulation, entityId)
72 {
73 const record = simulation.entityRecord(entityId);
74 assert.ok(record, "entity record");
75 return simulation.workers[record.workerId];
76 }
77
78 test("open furnace works in a non-overworld dimension", () =>
79 {
80 const harness = makeCaveHarness();
81 try
82 {
83 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
84 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
85 const playerId = harness.simulation.spawnCharacter(1, character);
86 const position = harness.simulation.positionOf(playerId);
87 assert.equal(position.dimensionId, CAVE_ID);
88
89 harness.simulation.enqueue(1, {
90 type: "open-station",
91 characterId: character.character_id,
92 stationId: CraftingStationId.furnace
93 });
94 const result = harness.simulation.step();
95 assert.ok(
96 result.events.some((event) =>
97 event.type === "station-open" && event.stationId === CraftingStationId.furnace),
98 "expected station-open in cave"
99 );
100 }
101 finally
102 { harness.close(); }
103 });
104
105 test("melee combat ticks in a non-overworld dimension", () =>
106 {
107 const harness = makeCaveHarness();
108 try
109 {
110 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
111 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
112 const playerId = harness.simulation.spawnCharacter(1, character);
113 assert.equal(harness.simulation.positionOf(playerId).dimensionId, CAVE_ID);
114
115 const ratId = harness.simulation.spawnEntity(mobComponents({
116 tileX: 8,
117 tileY: 9,
118 mobTypeId: MobId.rat,
119 spawnerId: null,
120 dimensionId: CAVE_ID
121 }));
122 assert.equal(harness.simulation.positionOf(ratId).dimensionId, CAVE_ID);
123
124 const worker = workerOf(harness.simulation, ratId);
125 const world = worker.world;
126 assert.ok(world.chunkIsSimulating(8, 9, CAVE_ID));
127 assert.equal(world.chunkIsSimulating(8, 9, OVERWORLD_ID), false);
128
129 assert.ok(ensureMobCombat(world.ecs, ratId));
130 engageTarget(world.ecs, ratId, playerId, harness.now());
131 const combat = world.ecs.get(world.ecs.handleOf(ratId), Component.combat);
132 combat.nextSwingAt = harness.now();
133
134 const events = stepCombat(world, harness.now());
135 assert.ok(
136 events.some((event) => event.type === "combat-swing" || event.type === "combat-hit"
137 || event.type === "combat-miss" || event.type === "combat-block"),
138 `expected combat resolution in cave, got ${events.map((e) => e.type).join(",") || "none"}`
139 );
140
141 stepAggression(world, harness.now());
142 }
143 finally
144 { harness.close(); }
145 });
@@ -0,0 +1,145 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { BlockType } from "../../shared/definitions/tiles.js";
7import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
8import { MobId } from "../../shared/definitions/mobs.js";
9import { OVERWORLD_ID, DimensionLightingMode, DimensionSeasonMode } from "../../shared/world/dimensions.js";
10import { WorldDatabase } from "../src/persistence/worldDb.js";
11import { StateDatabase } from "../src/persistence/stateDb.js";
12import { Simulation } from "../src/simulation/simulation.js";
13import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
14import { mobComponents } from "../src/simulation/spawners.js";
15import { engageTarget, ensureMobCombat, stepCombat, stepAggression } from "../src/combat/service.js";
16import { Component } from "../src/ecs/components.js";
17import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
18
19const CAVE_ID = "test-cave";
20
21function makeCaveHarness ()
22{
23 const dir = mkdtempSync(join(tmpdir(), "mmo-dim-interact-"));
24 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
25 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
26 openChunkStrip(worldDb, 2);
27 const rev = worldDb.getActiveRevisionId();
28 worldDb.saveDimension(rev, {
29 dimensionId: CAVE_ID,
30 displayName: "Test Cave",
31 lightingMode: DimensionLightingMode.alwaysLit,
32 seasonMode: DimensionSeasonMode.summer,
33 defaultGroundTypeId: 1
34 });
35 const cave = createEmptyChunkData();
36 cave.open = true;
37 cave.blocks[8 * 16 + 9] = {
38 typeId: BlockType.furnace,
39 state: "furnace",
40 config: null
41 };
42 worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(cave), CAVE_ID);
43 writeOpenChunk(worldDb, 0, 0);
44 let now = 1_000;
45 const simulation = new Simulation(worldDb, stateDb, {
46 workerCount: 1,
47 workerMode: "inprocess",
48 now: () => now
49 });
50 return {
51 simulation,
52 worldDb,
53 stateDb,
54 now ()
55 {
56 return now;
57 },
58 advance (ms)
59 {
60 now += ms;
61 },
62 close ()
63 {
64 simulation.forceUnloadAll();
65 worldDb.close();
66 stateDb.close();
67 }
68 };
69}
70
71function workerOf (simulation, entityId)
72{
73 const record = simulation.entityRecord(entityId);
74 assert.ok(record, "entity record");
75 return simulation.workers[record.workerId];
76}
77
78test("open furnace works in a non-overworld dimension", () =>
79{
80 const harness = makeCaveHarness();
81 try
82 {
83 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
84 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
85 const playerId = harness.simulation.spawnCharacter(1, character);
86 const position = harness.simulation.positionOf(playerId);
87 assert.equal(position.dimensionId, CAVE_ID);
88
89 harness.simulation.enqueue(1, {
90 type: "open-station",
91 characterId: character.character_id,
92 stationId: CraftingStationId.furnace
93 });
94 const result = harness.simulation.step();
95 assert.ok(
96 result.events.some((event) =>
97 event.type === "station-open" && event.stationId === CraftingStationId.furnace),
98 "expected station-open in cave"
99 );
100 }
101 finally
102 { harness.close(); }
103});
104
105test("melee combat ticks in a non-overworld dimension", () =>
106{
107 const harness = makeCaveHarness();
108 try
109 {
110 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
111 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
112 const playerId = harness.simulation.spawnCharacter(1, character);
113 assert.equal(harness.simulation.positionOf(playerId).dimensionId, CAVE_ID);
114
115 const ratId = harness.simulation.spawnEntity(mobComponents({
116 tileX: 8,
117 tileY: 9,
118 mobTypeId: MobId.rat,
119 spawnerId: null,
120 dimensionId: CAVE_ID
121 }));
122 assert.equal(harness.simulation.positionOf(ratId).dimensionId, CAVE_ID);
123
124 const worker = workerOf(harness.simulation, ratId);
125 const world = worker.world;
126 assert.ok(world.chunkIsSimulating(8, 9, CAVE_ID));
127 assert.equal(world.chunkIsSimulating(8, 9, OVERWORLD_ID), false);
128
129 assert.ok(ensureMobCombat(world.ecs, ratId));
130 engageTarget(world.ecs, ratId, playerId, harness.now());
131 const combat = world.ecs.get(world.ecs.handleOf(ratId), Component.combat);
132 combat.nextSwingAt = harness.now();
133
134 const events = stepCombat(world, harness.now());
135 assert.ok(
136 events.some((event) => event.type === "combat-swing" || event.type === "combat-hit"
137 || event.type === "combat-miss" || event.type === "combat-block"),
138 `expected combat resolution in cave, got ${events.map((e) => e.type).join(",") || "none"}`
139 );
140
141 stepAggression(world, harness.now());
142 }
143 finally
144 { harness.close(); }
145});
server/tests/firestarting-cooking.test.js +11 −10
@@ -1,14 +1,15 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import {
5 CraftingStationId,
6 firestartingDifficulty,
7 campfireDurationMs,
8 COOK_BURN_CHANCE_OVEN,
9 COOK_BURN_CHANCE_CAMPFIRE,
10 CRAFT_DURATION_MS
11 } from "../../shared/definitions/craftingStations.js";
4 import
5 {
6 CraftingStationId,
7 firestartingDifficulty,
8 campfireDurationMs,
9 COOK_BURN_CHANCE_OVEN,
10 COOK_BURN_CHANCE_CAMPFIRE,
11 CRAFT_DURATION_MS
12 } from "../../shared/definitions/craftingStations.js";
12 13 import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
13 14 import { MobId, mobDefinition } from "../../shared/definitions/mobs.js";
14 15 import { WoodItemId, ashItemIdForWood } from "../../shared/definitions/woodItems.js";
@@ -233,13 +234,13 @@ test("start-fire places campfire and expiry drops ash", () =>
233 234 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
234 235 assert.equal(block?.typeId, BlockType.campfire);
235 236 assert.equal(block?.state, WoodTier.pine);
236 assert.ok(worker.world.campfireExpires.has("9,8"));
237 assert.ok(worker.world.campfireExpires.has("overworld:9,8"));
237 238
238 239 const bag = harness.simulation.bagOf(playerId);
239 240 const tinder = bag.inventory.find((s) => s?.itemId === CraftingItemId.tinderbox);
240 241 assert.equal(tinder?.instance?.charges, 5);
241 242
242 const entry = worker.world.campfireExpires.get("9,8");
243 const entry = worker.world.campfireExpires.get("overworld:9,8");
243 244 entry.expiresAt = 0;
244 245 advanceMs(harness, 200);
245 246 assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
@@ -1,14 +1,15 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import {
4import
5 CraftingStationId,
5 {
6 firestartingDifficulty,
6 CraftingStationId,
7 campfireDurationMs,
7 firestartingDifficulty,
8 COOK_BURN_CHANCE_OVEN,
8 campfireDurationMs,
9 COOK_BURN_CHANCE_CAMPFIRE,
9 COOK_BURN_CHANCE_OVEN,
10 CRAFT_DURATION_MS
10 COOK_BURN_CHANCE_CAMPFIRE,
11} from "../../shared/definitions/craftingStations.js";
11 CRAFT_DURATION_MS
12 } from "../../shared/definitions/craftingStations.js";
12import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
13import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
13import { MobId, mobDefinition } from "../../shared/definitions/mobs.js";
14import { MobId, mobDefinition } from "../../shared/definitions/mobs.js";
14import { WoodItemId, ashItemIdForWood } from "../../shared/definitions/woodItems.js";
15import { WoodItemId, ashItemIdForWood } from "../../shared/definitions/woodItems.js";
@@ -233,13 +234,13 @@ test("start-fire places campfire and expiry drops ash", () =>
233 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
234 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
234 assert.equal(block?.typeId, BlockType.campfire);
235 assert.equal(block?.typeId, BlockType.campfire);
235 assert.equal(block?.state, WoodTier.pine);
236 assert.equal(block?.state, WoodTier.pine);
236 assert.ok(worker.world.campfireExpires.has("9,8"));
237 assert.ok(worker.world.campfireExpires.has("overworld:9,8"));
237
238
238 const bag = harness.simulation.bagOf(playerId);
239 const bag = harness.simulation.bagOf(playerId);
239 const tinder = bag.inventory.find((s) => s?.itemId === CraftingItemId.tinderbox);
240 const tinder = bag.inventory.find((s) => s?.itemId === CraftingItemId.tinderbox);
240 assert.equal(tinder?.instance?.charges, 5);
241 assert.equal(tinder?.instance?.charges, 5);
241
242
242 const entry = worker.world.campfireExpires.get("9,8");
243 const entry = worker.world.campfireExpires.get("overworld:9,8");
243 entry.expiresAt = 0;
244 entry.expiresAt = 0;
244 advanceMs(harness, 200);
245 advanceMs(harness, 200);
245 assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
246 assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
server/tests/fishing.test.js +11 −10
@@ -1,15 +1,16 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { BlockType, GroundType } from "../../shared/definitions/tiles.js";
4 import {
5 rawFishItemId,
6 cookedFishItemId,
7 baitItemIdForCloth,
8 FishingToolItemId,
9 fishingDifficulty,
10 fishingExhaustDurationMs,
11 normalizeFishingSpotConfig
12 } from "../../shared/definitions/fishItems.js";
4 import
5 {
6 rawFishItemId,
7 cookedFishItemId,
8 baitItemIdForCloth,
9 FishingToolItemId,
10 fishingDifficulty,
11 fishingExhaustDurationMs,
12 normalizeFishingSpotConfig
13 } from "../../shared/definitions/fishItems.js";
13 14 import { ClothTier } from "../../shared/definitions/materialTiers.js";
14 15 import { yarnItemId } from "../../shared/definitions/clothItems.js";
15 16 import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
@@ -115,7 +116,7 @@ test("net catches tier-1 fish without bait and exhausts spot", () =>
115 116 assert.equal(bag.inventory.some((s) => s?.itemId === trout), false);
116 117 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
117 118 assert.equal(block.state, "exhausted");
118 assert.ok(worker.world.fishingSpotRespawns.has("9,8"));
119 assert.ok(worker.world.fishingSpotRespawns.has("overworld:9,8"));
119 120 }
120 121 finally
121 122 { harness.close(); }
@@ -1,15 +1,16 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { BlockType, GroundType } from "../../shared/definitions/tiles.js";
3import { BlockType, GroundType } from "../../shared/definitions/tiles.js";
4import {
4import
5 rawFishItemId,
5 {
6 cookedFishItemId,
6 rawFishItemId,
7 baitItemIdForCloth,
7 cookedFishItemId,
8 FishingToolItemId,
8 baitItemIdForCloth,
9 fishingDifficulty,
9 FishingToolItemId,
10 fishingExhaustDurationMs,
10 fishingDifficulty,
11 normalizeFishingSpotConfig
11 fishingExhaustDurationMs,
12} from "../../shared/definitions/fishItems.js";
12 normalizeFishingSpotConfig
13 } from "../../shared/definitions/fishItems.js";
13import { ClothTier } from "../../shared/definitions/materialTiers.js";
14import { ClothTier } from "../../shared/definitions/materialTiers.js";
14import { yarnItemId } from "../../shared/definitions/clothItems.js";
15import { yarnItemId } from "../../shared/definitions/clothItems.js";
15import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
16import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
@@ -115,7 +116,7 @@ test("net catches tier-1 fish without bait and exhausts spot", () =>
115 assert.equal(bag.inventory.some((s) => s?.itemId === trout), false);
116 assert.equal(bag.inventory.some((s) => s?.itemId === trout), false);
116 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
117 const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
117 assert.equal(block.state, "exhausted");
118 assert.equal(block.state, "exhausted");
118 assert.ok(worker.world.fishingSpotRespawns.has("9,8"));
119 assert.ok(worker.world.fishingSpotRespawns.has("overworld:9,8"));
119 }
120 }
120 finally
121 finally
121 { harness.close(); }
122 { harness.close(); }
server/tests/water-grounds.test.js +12 −1
@@ -2,7 +2,7 @@ import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { GroundType, BlockType, isGroundPassable, isWadeGround, isWaterGround, isLiquidWaterGround, isWadeGroundInSeason, groundLightOcclusion, groundLightRange, blockLightRange, LightOcclusion, fluidCoastContinues, isLavaGround } from "../../shared/definitions/tiles.js";
4 4 import { SeasonId, resolveSeasonalVisualState } from "../../shared/world/season.js";
5 import { createEmptyChunkData, isChunkTilePassable, isChunkTileClearForLight, setGround } from "../src/world/chunkData.js";
5 import { createEmptyChunkData, isChunkTilePassable, isChunkTileClearForLight, isChunkTileClearForRangedAttacks, setGround } from "../src/world/chunkData.js";
6 6
7 7 test("deep water ground is impassable; shallow water is passable and wadeable", () =>
8 8 {
@@ -30,6 +30,17 @@ test("deep water does not occlude light rays", () =>
30 30 assert.equal(isChunkTilePassable(data, 3, 3), false);
31 31 });
32 32
33 test("deep water does not block ranged / spell line of sight", () =>
34 {
35 const data = createEmptyChunkData();
36 setGround(data, 5, 5, GroundType.deepWater);
37 setGround(data, 6, 6, GroundType.water);
38 assert.equal(isChunkTileClearForRangedAttacks(data, 5, 5), true);
39 assert.equal(isChunkTileClearForRangedAttacks(data, 6, 6), true);
40 assert.equal(isChunkTilePassable(data, 5, 5), false);
41 assert.equal(isChunkTilePassable(data, 6, 6), true);
42 });
43
33 44 test("lava is impassable, clear for light, and emits half-torch light", () =>
34 45 {
35 46 assert.equal(isGroundPassable(GroundType.lava), false);
@@ -2,7 +2,7 @@ import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { GroundType, BlockType, isGroundPassable, isWadeGround, isWaterGround, isLiquidWaterGround, isWadeGroundInSeason, groundLightOcclusion, groundLightRange, blockLightRange, LightOcclusion, fluidCoastContinues, isLavaGround } from "../../shared/definitions/tiles.js";
3import { GroundType, BlockType, isGroundPassable, isWadeGround, isWaterGround, isLiquidWaterGround, isWadeGroundInSeason, groundLightOcclusion, groundLightRange, blockLightRange, LightOcclusion, fluidCoastContinues, isLavaGround } from "../../shared/definitions/tiles.js";
4import { SeasonId, resolveSeasonalVisualState } from "../../shared/world/season.js";
4import { SeasonId, resolveSeasonalVisualState } from "../../shared/world/season.js";
5import { createEmptyChunkData, isChunkTilePassable, isChunkTileClearForLight, setGround } from "../src/world/chunkData.js";
5import { createEmptyChunkData, isChunkTilePassable, isChunkTileClearForLight, isChunkTileClearForRangedAttacks, setGround } from "../src/world/chunkData.js";
6
6
7test("deep water ground is impassable; shallow water is passable and wadeable", () =>
7test("deep water ground is impassable; shallow water is passable and wadeable", () =>
8{
8{
@@ -30,6 +30,17 @@ test("deep water does not occlude light rays", () =>
30 assert.equal(isChunkTilePassable(data, 3, 3), false);
30 assert.equal(isChunkTilePassable(data, 3, 3), false);
31});
31});
32
32
33test("deep water does not block ranged / spell line of sight", () =>
34{
35 const data = createEmptyChunkData();
36 setGround(data, 5, 5, GroundType.deepWater);
37 setGround(data, 6, 6, GroundType.water);
38 assert.equal(isChunkTileClearForRangedAttacks(data, 5, 5), true);
39 assert.equal(isChunkTileClearForRangedAttacks(data, 6, 6), true);
40 assert.equal(isChunkTilePassable(data, 5, 5), false);
41 assert.equal(isChunkTilePassable(data, 6, 6), true);
42});
43
33test("lava is impassable, clear for light, and emits half-torch light", () =>
44test("lava is impassable, clear for light, and emits half-torch light", () =>
34{
45{
35 assert.equal(isGroundPassable(GroundType.lava), false);
46 assert.equal(isGroundPassable(GroundType.lava), false);
shared/protocol/constants.js +1 −0
@@ -297,6 +297,7 @@ export const MessageType = Object.freeze({
297 297 questObjectiveComplete: "QUEST_OBJECTIVE_COMPLETE",
298 298 questComplete: "QUEST_COMPLETE",
299 299 jewelryTeleport: "JEWELRY_TELEPORT",
300 prayAtAltar: "PRAY_AT_ALTAR",
300 301 tradeRequest: "TRADE_REQUEST",
301 302 tradeRespondInvite: "TRADE_RESPOND_INVITE",
302 303 tradeInvite: "TRADE_INVITE",
@@ -297,6 +297,7 @@ export const MessageType = Object.freeze({
297 questObjectiveComplete: "QUEST_OBJECTIVE_COMPLETE",
297 questObjectiveComplete: "QUEST_OBJECTIVE_COMPLETE",
298 questComplete: "QUEST_COMPLETE",
298 questComplete: "QUEST_COMPLETE",
299 jewelryTeleport: "JEWELRY_TELEPORT",
299 jewelryTeleport: "JEWELRY_TELEPORT",
300 prayAtAltar: "PRAY_AT_ALTAR",
300 tradeRequest: "TRADE_REQUEST",
301 tradeRequest: "TRADE_REQUEST",
301 tradeRespondInvite: "TRADE_RESPOND_INVITE",
302 tradeRespondInvite: "TRADE_RESPOND_INVITE",
302 tradeInvite: "TRADE_INVITE",
303 tradeInvite: "TRADE_INVITE",