Add carrier pigeons with phased flight speeds and graceful shutdown.
Durable courier transit delivers money or one stack to bank or player; takeoff/cruise/landing speeds are world settings; shutdown leaves clients and unloads chunks cleanly.
@@ -24,7 +24,19 @@
24
24
<button id="bag-drop" type="button">Drop</button>
25
25
<button id="bag-equip" type="button">Equip</button>
26
26
<button id="bag-bank" type="button">Deposit selected</button>
27
<button id="bag-pigeon-bank" type="button">Pigeon → bank</button>
28
<button id="bag-pigeon-player" type="button">Pigeon → player</button>
27
29
</div>
30
<label class="pigeon-row">Coins to send
31
<input id="bag-pigeon-coins" type="number" min="1" step="1" value="1">
32
</label>
33
<label class="pigeon-row">Player first
34
<input id="bag-pigeon-first" type="text" autocomplete="off">
35
</label>
36
<label class="pigeon-row">Player last
37
<input id="bag-pigeon-last" type="text" autocomplete="off">
38
</label>
39
<p id="bag-pigeon-status" class="hint"></p>
28
40
</aside>
29
41
<aside id="bank-panel" hidden>
30
42
<header>
@@ -46,7 +58,7 @@
46
58
<div id="incoming-list"></div>
47
59
<h3>Outgoing</h3>
48
60
<div id="outgoing-list"></div>
49
<p class="hint">Later, sending a pigeon can type a first and last name or pick a friend to fill those fields.</p>
61
<p class="hint">Use Bag → Pigeon to send coins or an item to a bank vault or another player (type a name, or pick a friend to fill the fields).</p>
50
62
</aside>
51
63
<div id="nametag" hidden></div>
52
64
<div id="chat-bubbles"></div>
@@ -24,7 +24,19 @@24
<button id="bag-drop" type="button">Drop</button>24
<button id="bag-drop" type="button">Drop</button>25
<button id="bag-equip" type="button">Equip</button>25
<button id="bag-equip" type="button">Equip</button>26
<button id="bag-bank" type="button">Deposit selected</button>26
<button id="bag-bank" type="button">Deposit selected</button>27
<button id="bag-pigeon-bank" type="button">Pigeon → bank</button>28
<button id="bag-pigeon-player" type="button">Pigeon → player</button>27
</div>29
</div>30
<label class="pigeon-row">Coins to send31
<input id="bag-pigeon-coins" type="number" min="1" step="1" value="1">32
</label>33
<label class="pigeon-row">Player first34
<input id="bag-pigeon-first" type="text" autocomplete="off">35
</label>36
<label class="pigeon-row">Player last37
<input id="bag-pigeon-last" type="text" autocomplete="off">38
</label>39
<p id="bag-pigeon-status" class="hint"></p>28
</aside>40
</aside>29
<aside id="bank-panel" hidden>41
<aside id="bank-panel" hidden>30
<header>42
<header>@@ -46,7 +58,7 @@46
<div id="incoming-list"></div>58
<div id="incoming-list"></div>47
<h3>Outgoing</h3>59
<h3>Outgoing</h3>48
<div id="outgoing-list"></div>60
<div id="outgoing-list"></div>49
<p class="hint">Later, sending a pigeon can type a first and last name or pick a friend to fill those fields.</p>61
<p class="hint">Use Bag → Pigeon to send coins or an item to a bank vault or another player (type a name, or pick a friend to fill the fields).</p>50
</aside>62
</aside>51
<div id="nametag" hidden></div>63
<div id="nametag" hidden></div>52
<div id="chat-bubbles"></div>64
<div id="chat-bubbles"></div>@@ -50,6 +50,50 @@ export function initInventory ({ socket, MessageType, game })
50
50
{
51
51
socket.send({ type: MessageType.claimInheritance });
52
52
});
53
document.getElementById("bag-pigeon-bank").addEventListener("click", () => sendPigeon({ kind: "bank" }));
54
document.getElementById("bag-pigeon-player").addEventListener("click", () =>
55
{
56
const firstName = document.getElementById("bag-pigeon-first").value.trim();
57
const lastName = document.getElementById("bag-pigeon-last").value.trim();
58
if (!firstName || !lastName)
59
{
60
setPigeonStatus("Enter a first and last name, or pick a friend.");
61
return;
62
}
63
sendPigeon({ kind: "player", firstName, lastName });
64
});
65
66
function cargoPayload ()
67
{
68
if (selected != null && bag.inventory?.[selected])
69
{
70
return { kind: "item", slotIndex: selected };
71
}
72
const amount = Math.max(1, Number(document.getElementById("bag-pigeon-coins").value) | 0);
73
return { kind: "money", amount };
74
}
75
76
function sendPigeon (destination)
77
{
78
const cargo = cargoPayload();
79
if (cargo.kind === "money" && (bag.currency | 0) < cargo.amount)
80
{
81
setPigeonStatus("Not enough coins.");
82
return;
83
}
84
if (cargo.kind === "item" && selected == null)
85
{
86
setPigeonStatus("Select an item slot, or clear selection to send coins.");
87
return;
88
}
89
socket.send({ type: MessageType.sendPigeon, destination, cargo });
90
setPigeonStatus("Pigeon dispatched…");
91
}
92
93
function setPigeonStatus (text)
94
{
95
document.getElementById("bag-pigeon-status").textContent = text;
96
}
53
97
54
98
function render ()
55
99
{
@@ -162,12 +206,29 @@ export function initInventory ({ socket, MessageType, game })
162
206
{ return; }
163
207
socket.send({ type: MessageType.bankDeposit, slotIndex: selected });
164
208
},
209
fillPigeonRecipient (firstName, lastName)
210
{
211
document.getElementById("bag-pigeon-first").value = firstName ?? "";
212
document.getElementById("bag-pigeon-last").value = lastName ?? "";
213
bagPanel.hidden = false;
214
setPigeonStatus(`Recipient set to ${firstName} ${lastName}.`);
215
},
216
handlePigeonDispatched ()
217
{
218
setPigeonStatus("Pigeon is in flight.");
219
},
220
handlePigeonDelivered (message)
221
{
222
const kind = message.destinationKind === "bank" ? "bank vault" : "recipient";
223
setPigeonStatus(`Pigeon delivered to ${kind}.`);
224
},
165
225
reset ()
166
226
{
167
227
bagPanel.hidden = true;
168
228
bankPanel.hidden = true;
169
229
bankOpen = false;
170
230
selected = null;
231
setPigeonStatus("");
171
232
}
172
233
};
173
234
}
@@ -50,6 +50,50 @@ export function initInventory ({ socket, MessageType, game })50
{50
{51
socket.send({ type: MessageType.claimInheritance });51
socket.send({ type: MessageType.claimInheritance });52
});52
});53
document.getElementById("bag-pigeon-bank").addEventListener("click", () => sendPigeon({ kind: "bank" }));54
document.getElementById("bag-pigeon-player").addEventListener("click", () =>55
{56
const firstName = document.getElementById("bag-pigeon-first").value.trim();57
const lastName = document.getElementById("bag-pigeon-last").value.trim();58
if (!firstName || !lastName)59
{60
setPigeonStatus("Enter a first and last name, or pick a friend.");61
return;62
}63
sendPigeon({ kind: "player", firstName, lastName });64
});65
66
function cargoPayload ()67
{68
if (selected != null && bag.inventory?.[selected])69
{70
return { kind: "item", slotIndex: selected };71
}72
const amount = Math.max(1, Number(document.getElementById("bag-pigeon-coins").value) | 0);73
return { kind: "money", amount };74
}75
76
function sendPigeon (destination)77
{78
const cargo = cargoPayload();79
if (cargo.kind === "money" && (bag.currency | 0) < cargo.amount)80
{81
setPigeonStatus("Not enough coins.");82
return;83
}84
if (cargo.kind === "item" && selected == null)85
{86
setPigeonStatus("Select an item slot, or clear selection to send coins.");87
return;88
}89
socket.send({ type: MessageType.sendPigeon, destination, cargo });90
setPigeonStatus("Pigeon dispatched…");91
}92
93
function setPigeonStatus (text)94
{95
document.getElementById("bag-pigeon-status").textContent = text;96
}53
97
54
function render ()98
function render ()55
{99
{@@ -162,12 +206,29 @@ export function initInventory ({ socket, MessageType, game })162
{ return; }206
{ return; }163
socket.send({ type: MessageType.bankDeposit, slotIndex: selected });207
socket.send({ type: MessageType.bankDeposit, slotIndex: selected });164
},208
},209
fillPigeonRecipient (firstName, lastName)210
{211
document.getElementById("bag-pigeon-first").value = firstName ?? "";212
document.getElementById("bag-pigeon-last").value = lastName ?? "";213
bagPanel.hidden = false;214
setPigeonStatus(`Recipient set to ${firstName} ${lastName}.`);215
},216
handlePigeonDispatched ()217
{218
setPigeonStatus("Pigeon is in flight.");219
},220
handlePigeonDelivered (message)221
{222
const kind = message.destinationKind === "bank" ? "bank vault" : "recipient";223
setPigeonStatus(`Pigeon delivered to ${kind}.`);224
},165
reset ()225
reset ()166
{226
{167
bagPanel.hidden = true;227
bagPanel.hidden = true;168
bankPanel.hidden = true;228
bankPanel.hidden = true;169
bankOpen = false;229
bankOpen = false;170
selected = null;230
selected = null;231
setPigeonStatus("");171
}232
}172
};233
};173
}234
}@@ -240,7 +240,14 @@ async function main ()
240
240
catalog = await loadSpriteCatalog();
241
241
await preloadCatalogImages(game, catalog);
242
242
applySpriteSheets(game.images, catalog);
243
social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
243
social = initSocial({
244
socket: { send (payload) { socket.send(payload); } },
245
MessageType,
246
onPickPigeonRecipient (firstName, lastName)
247
{
248
inventory?.fillPigeonRecipient(firstName, lastName);
249
}
250
});
244
251
inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });
245
252
contextMenu = initContextMenu();
246
253
document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
@@ -303,6 +310,12 @@ async function main ()
303
310
case MessageType.bankSnapshot:
304
311
inventory?.handleBank(message);
305
312
break;
313
case MessageType.pigeonDispatched:
314
inventory?.handlePigeonDispatched(message);
315
break;
316
case MessageType.pigeonDelivered:
317
inventory?.handlePigeonDelivered(message);
318
break;
306
319
case MessageType.worldStatus:
307
320
if (view)
308
321
{
@@ -240,7 +240,14 @@ async function main ()240
catalog = await loadSpriteCatalog();240
catalog = await loadSpriteCatalog();241
await preloadCatalogImages(game, catalog);241
await preloadCatalogImages(game, catalog);242
applySpriteSheets(game.images, catalog);242
applySpriteSheets(game.images, catalog);243
social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });243
social = initSocial({244
socket: { send (payload) { socket.send(payload); } },245
MessageType,246
onPickPigeonRecipient (firstName, lastName)247
{248
inventory?.fillPigeonRecipient(firstName, lastName);249
}250
});244
inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });251
inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });245
contextMenu = initContextMenu();252
contextMenu = initContextMenu();246
document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());253
document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());@@ -303,6 +310,12 @@ async function main ()303
case MessageType.bankSnapshot:310
case MessageType.bankSnapshot:304
inventory?.handleBank(message);311
inventory?.handleBank(message);305
break;312
break;313
case MessageType.pigeonDispatched:314
inventory?.handlePigeonDispatched(message);315
break;316
case MessageType.pigeonDelivered:317
inventory?.handlePigeonDelivered(message);318
break;306
case MessageType.worldStatus:319
case MessageType.worldStatus:307
if (view)320
if (view)308
{321
{@@ -1,4 +1,4 @@
1
export function initSocial ({ socket, MessageType })
1
export function initSocial ({ socket, MessageType, onPickPigeonRecipient })
2
2
{
3
3
const nametag = document.getElementById("nametag");
4
4
const inspect = document.getElementById("inspect-modal");
@@ -95,6 +95,10 @@ export function initSocial ({ socket, MessageType })
95
95
fillList(friendsList, social.friends, "No friends yet.", (entry) =>
96
96
{
97
97
const row = namedRow(entry);
98
row.append(actionButton("Pigeon", () =>
99
{
100
onPickPigeonRecipient?.(entry.firstName, entry.lastName);
101
}));
98
102
row.append(actionButton("Remove", () =>
99
103
{
100
104
socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });
@@ -1,4 +1,4 @@1
export function initSocial ({ socket, MessageType })1
export function initSocial ({ socket, MessageType, onPickPigeonRecipient })2
{2
{3
const nametag = document.getElementById("nametag");3
const nametag = document.getElementById("nametag");4
const inspect = document.getElementById("inspect-modal");4
const inspect = document.getElementById("inspect-modal");@@ -95,6 +95,10 @@ export function initSocial ({ socket, MessageType })95
fillList(friendsList, social.friends, "No friends yet.", (entry) =>95
fillList(friendsList, social.friends, "No friends yet.", (entry) =>96
{96
{97
const row = namedRow(entry);97
const row = namedRow(entry);98
row.append(actionButton("Pigeon", () =>99
{100
onPickPigeonRecipient?.(entry.firstName, entry.lastName);101
}));98
row.append(actionButton("Remove", () =>102
row.append(actionButton("Remove", () =>99
{103
{100
socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });104
socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });@@ -222,6 +222,18 @@ a { color: #d4c48a; }
222
222
gap: 0.35rem;
223
223
}
224
224
225
.pigeon-row {
226
display: flex;
227
flex-direction: column;
228
gap: 0.2rem;
229
margin: 0.35rem 0;
230
font-size: 0.85rem;
231
}
232
233
.pigeon-row input {
234
padding: 0.25rem 0.4rem;
235
}
236
225
237
#friends-panel h2, #friends-panel h3 {
226
238
margin: 0.4rem 0;
227
239
font-size: 0.95rem;
@@ -222,6 +222,18 @@ a { color: #d4c48a; }222
gap: 0.35rem;222
gap: 0.35rem;223
}223
}224
224
225
.pigeon-row {226
display: flex;227
flex-direction: column;228
gap: 0.2rem;229
margin: 0.35rem 0;230
font-size: 0.85rem;231
}232
233
.pigeon-row input {234
padding: 0.25rem 0.4rem;235
}236
225
#friends-panel h2, #friends-panel h3 {237
#friends-panel h2, #friends-panel h3 {226
margin: 0.4rem 0;238
margin: 0.4rem 0;227
font-size: 0.95rem;239
font-size: 0.95rem;@@ -196,8 +196,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
196
196
## Combat, skills, groups, pigeons
197
197
198
198
**Status:** partial
199
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, and client dynamic-light hooks. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. Ranged/spells/groups/pigeon dispatch remain design-only.
200
**Code:** `shared/definitions/skills.js`, `server/src/simulation/follow.js`, combat tick, `client/src/play/` context menu + swipe, tests in `server/tests/combat.test.js` / `server/tests/follow.test.js`
199
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, and client dynamic-light hooks. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank (nearest bank → sender vault) or Player (online inventory / offline money→vault / full inventory→reroute to bank). Flight speeds are world settings: takeoff / cruise / landing over the first and last `pigeonPhaseTiles` (defaults 3 / 8 / 3 tiles/s, phase 5). Durable `courier_transits`; ECS pigeon only in already-simulating chunks. Ranged/spells/groups remain design-only.
200
**Code:** `shared/courier/flight.js`, `server/src/courier/service.js`, bag pigeon UI, tests in `server/tests/courier.test.js` (+ combat/follow tests)
201
201
202
202
## Proximity chat
203
203
@@ -196,8 +196,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi196
## Combat, skills, groups, pigeons196
## Combat, skills, groups, pigeons197
197
198
**Status:** partial 198
**Status:** partial 199
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, and client dynamic-light hooks. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. Ranged/spells/groups/pigeon dispatch remain design-only. 199
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, and client dynamic-light hooks. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank (nearest bank → sender vault) or Player (online inventory / offline money→vault / full inventory→reroute to bank). Flight speeds are world settings: takeoff / cruise / landing over the first and last `pigeonPhaseTiles` (defaults 3 / 8 / 3 tiles/s, phase 5). Durable `courier_transits`; ECS pigeon only in already-simulating chunks. Ranged/spells/groups remain design-only. 200
**Code:** `shared/definitions/skills.js`, `server/src/simulation/follow.js`, combat tick, `client/src/play/` context menu + swipe, tests in `server/tests/combat.test.js` / `server/tests/follow.test.js`200
**Code:** `shared/courier/flight.js`, `server/src/courier/service.js`, bag pigeon UI, tests in `server/tests/courier.test.js` (+ combat/follow tests)201
201
202
## Proximity chat202
## Proximity chat203
203
@@ -0,0 +1,439 @@
1
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2
import { BlockType } from "../../../shared/definitions/tiles.js";
3
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4
import { itemDefinition } from "../../../shared/definitions/items.js";
5
import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";
6
import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7
import { GAIT } from "../../../shared/protocol/constants.js";
8
import { decodeChunkBlob } from "../world/chunkData.js";
9
10
export class CourierService
11
{
12
constructor ({ stateDb, worldDb, simulation })
13
{
14
this.stateDb = stateDb;
15
this.worldDb = worldDb;
16
this.simulation = simulation;
17
this.bankTiles = [];
18
this.refreshBankIndex();
19
}
20
21
refreshBankIndex ()
22
{
23
const revisionId = this.worldDb.getActiveRevisionId();
24
const banks = [];
25
for (const coord of this.worldDb.listChunkCoords(revisionId))
26
{
27
const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
28
if (!row)
29
{ continue; }
30
const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
31
for (let localY = 0; localY < CHUNK_SIZE; localY++)
32
{
33
for (let localX = 0; localX < CHUNK_SIZE; localX++)
34
{
35
const block = data.blocks[localY * CHUNK_SIZE + localX];
36
if (block?.typeId !== BlockType.bank)
37
{ continue; }
38
banks.push({
39
tileX: coord.chunk_x * CHUNK_SIZE + localX,
40
tileY: coord.chunk_y * CHUNK_SIZE + localY
41
});
42
}
43
}
44
}
45
this.bankTiles = banks;
46
}
47
48
nearestBank (tileX, tileY)
49
{
50
if (!this.bankTiles.length)
51
{ return null; }
52
let best = null;
53
let bestDist = Infinity;
54
for (const bank of this.bankTiles)
55
{
56
const dist = Math.hypot(bank.tileX - tileX, bank.tileY - tileY);
57
if (dist < bestDist)
58
{
59
bestDist = dist;
60
best = bank;
61
}
62
}
63
return best;
64
}
65
66
/**
67
* Player dispatch: cargo is money or one inventory stack.
68
* destination: { kind: "bank" } | { kind: "player", firstName, lastName }
69
*/
70
dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo })
71
{
72
const onlineId = this.simulation.characterEntities.get(characterId);
73
const bag = onlineId
74
? this.simulation.bagOf(onlineId)
75
: this.stateDb.getBag(characterId);
76
if (!bag)
77
{
78
const error = new Error("No bag.");
79
error.userFacing = true;
80
throw error;
81
}
82
83
let takenCargo;
84
if (cargo?.kind === "money")
85
{
86
const amount = Math.max(0, cargo.amount | 0);
87
if (amount <= 0 || amount > (bag.currency | 0))
88
{
89
const error = new Error("Not enough coins.");
90
error.userFacing = true;
91
throw error;
92
}
93
bag.currency -= amount;
94
takenCargo = { kind: "money", amount };
95
}
96
else if (cargo?.kind === "item")
97
{
98
const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);
99
if (!taken.ok || !taken.taken)
100
{
101
const error = new Error("That item is not available.");
102
error.userFacing = true;
103
throw error;
104
}
105
bag.inventory = taken.slots;
106
takenCargo = { kind: "item", stack: taken.taken };
107
}
108
else
109
{
110
const error = new Error("Pigeon cargo must be money or one item stack.");
111
error.userFacing = true;
112
throw error;
113
}
114
115
const dest = this.#resolveDestination(destination, originTileX, originTileY);
116
this.#persistBag(characterId, bag);
117
const transit = this.stateDb.insertCourierTransit({
118
senderCharacterId: characterId,
119
destinationKind: dest.kind,
120
destinationCharacterId: dest.characterId ?? null,
121
cargo: takenCargo,
122
originX: originTileX + 0.5,
123
originY: originTileY + 0.5,
124
destX: dest.tileX + 0.5,
125
destY: dest.tileY + 0.5,
126
traveled: 0,
127
status: "in_transit",
128
entityId: null
129
});
130
return { transit, bag };
131
}
132
133
/** Market / system dispatch already holding cargo (no bag take). */
134
dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo })
135
{
136
const dest = this.#resolveDestination(destination, originTileX, originTileY);
137
return this.stateDb.insertCourierTransit({
138
senderCharacterId,
139
destinationKind: dest.kind,
140
destinationCharacterId: dest.characterId ?? null,
141
cargo,
142
originX: originTileX + 0.5,
143
originY: originTileY + 0.5,
144
destX: dest.tileX + 0.5,
145
destY: dest.tileY + 0.5,
146
traveled: 0,
147
status: "in_transit",
148
entityId: null
149
});
150
}
151
152
step (now, dt)
153
{
154
const events = [];
155
const settings = this.simulation.settings;
156
for (const transit of this.stateDb.listActiveCourierTransits())
157
{
158
this.#retargetPlayerDest(transit);
159
const advanced = advanceCourierFlight({
160
originX: transit.originX,
161
originY: transit.originY,
162
destX: transit.destX,
163
destY: transit.destY,
164
traveled: transit.traveled,
165
dt,
166
settings
167
});
168
transit.traveled = advanced.traveled;
169
transit.updatedAt = now;
170
171
if (advanced.arrived)
172
{
173
events.push(...this.#deliver(transit, now));
174
continue;
175
}
176
177
events.push(...this.#syncVisiblePigeon(transit, advanced, now));
178
this.stateDb.updateCourierTransit(transit);
179
}
180
return events;
181
}
182
183
#retargetPlayerDest (transit)
184
{
185
if (transit.destinationKind !== "player" || !transit.destinationCharacterId)
186
{ return; }
187
const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId);
188
if (onlineId)
189
{
190
const pos = this.simulation.positionOf(onlineId);
191
if (pos)
192
{
193
transit.destX = pos.tileX + 0.5;
194
transit.destY = pos.tileY + 0.5;
195
}
196
return;
197
}
198
const character = this.stateDb.getCharacter(transit.destinationCharacterId);
199
if (character)
200
{
201
transit.destX = character.tile_x + 0.5;
202
transit.destY = character.tile_y + 0.5;
203
}
204
}
205
206
#resolveDestination (destination, originTileX, originTileY)
207
{
208
if (destination?.kind === "player")
209
{
210
const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);
211
if (!character)
212
{
213
const error = new Error("No character with that name.");
214
error.userFacing = true;
215
throw error;
216
}
217
const onlineId = this.simulation.characterEntities.get(character.character_id);
218
const pos = onlineId ? this.simulation.positionOf(onlineId) : null;
219
return {
220
kind: "player",
221
characterId: character.character_id,
222
tileX: pos?.tileX ?? character.tile_x,
223
tileY: pos?.tileY ?? character.tile_y
224
};
225
}
226
if (destination?.kind === "bank")
227
{
228
const bank = this.nearestBank(originTileX, originTileY);
229
if (!bank)
230
{
231
const error = new Error("No bank exists in the world yet.");
232
error.userFacing = true;
233
throw error;
234
}
235
return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY };
236
}
237
const error = new Error("Pigeon destination must be bank or player.");
238
error.userFacing = true;
239
throw error;
240
}
241
242
#syncVisiblePigeon (transit, advanced, now)
243
{
244
const events = [];
245
const tileX = Math.floor(advanced.x);
246
const tileY = Math.floor(advanced.y);
247
if (!this.simulation.chunkIsSimulating(tileX, tileY))
248
{
249
if (transit.entityId)
250
{
251
this.simulation.despawnEntity(transit.entityId);
252
events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY });
253
transit.entityId = null;
254
}
255
return events;
256
}
257
258
if (!transit.entityId || !this.simulation.entityRecord(transit.entityId))
259
{
260
transit.entityId = null;
261
const def = mobDefinition(MobId.pigeon);
262
const entityId = this.simulation.spawnEntity({
263
position: { tileX, tileY },
264
movement: { gait: GAIT.walk, walkCarry: 0 },
265
path: { tiles: [] },
266
flight: {
267
x: advanced.x,
268
y: advanced.y,
269
targetX: transit.destX,
270
targetY: transit.destY,
271
speed: advanced.speed,
272
nextPickAt: now + 60_000,
273
lastAt: now,
274
courierId: transit.courierId
275
},
276
appearance: {
277
sex: def.sex,
278
firstName: def.displayName,
279
lastName: "",
280
sprite: mobSpriteName(MobId.pigeon)
281
},
282
creature: { mobTypeId: MobId.pigeon },
283
health: { current: 1, max: 1 }
284
}, { requireResident: true });
285
if (entityId != null)
286
{ transit.entityId = entityId; }
287
return events;
288
}
289
290
const moved = this.simulation.updateCourierFlight(transit.entityId, {
291
x: advanced.x,
292
y: advanced.y,
293
targetX: transit.destX,
294
targetY: transit.destY,
295
speed: advanced.speed,
296
lastAt: now,
297
courierId: transit.courierId
298
}, now);
299
if (moved?.despawned)
300
{
301
transit.entityId = null;
302
events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY });
303
}
304
else if (moved?.event)
305
{ events.push(moved.event); }
306
return events;
307
}
308
309
#deliver (transit, now)
310
{
311
const events = [];
312
if (transit.entityId)
313
{
314
this.simulation.despawnEntity(transit.entityId);
315
events.push({
316
type: "entity-despawn",
317
entityId: transit.entityId,
318
tileX: Math.floor(transit.destX),
319
tileY: Math.floor(transit.destY)
320
});
321
transit.entityId = null;
322
}
323
324
if (transit.destinationKind === "bank")
325
{ this.#creditVault(transit.senderCharacterId, transit.cargo); }
326
else if (transit.destinationKind === "player")
327
{
328
const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
329
if (!delivered)
330
{
331
const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
332
?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
333
if (bank)
334
{
335
transit.originX = transit.destX;
336
transit.originY = transit.destY;
337
transit.destX = bank.tileX + 0.5;
338
transit.destY = bank.tileY + 0.5;
339
transit.traveled = 0;
340
transit.destinationKind = "bank";
341
transit.updatedAt = now;
342
this.stateDb.updateCourierTransit(transit);
343
events.push({
344
type: "pigeon-reroute-bank",
345
courierId: transit.courierId,
346
characterId: transit.destinationCharacterId
347
});
348
return events;
349
}
350
this.#creditVault(transit.destinationCharacterId, transit.cargo);
351
}
352
}
353
354
transit.status = "delivered";
355
transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY);
356
transit.updatedAt = now;
357
this.stateDb.updateCourierTransit(transit);
358
events.push({
359
type: "pigeon-delivered",
360
courierId: transit.courierId,
361
senderCharacterId: transit.senderCharacterId,
362
destinationKind: transit.destinationKind,
363
destinationCharacterId: transit.destinationCharacterId,
364
cargo: transit.cargo
365
});
366
return events;
367
}
368
369
#tryDeliverToPlayer (characterId, cargo)
370
{
371
const onlineId = this.simulation.characterEntities.get(characterId);
372
if (onlineId)
373
{
374
if (cargo.kind === "money")
375
{
376
const bag = this.simulation.bagOf(onlineId);
377
if (!bag)
378
{ return false; }
379
bag.currency = (bag.currency | 0) + (cargo.amount | 0);
380
this.#persistBag(characterId, bag);
381
return true;
382
}
383
if (cargo.kind === "item")
384
{
385
const bag = this.simulation.bagOf(onlineId);
386
if (!bag)
387
{ return false; }
388
const def = itemDefinition(cargo.stack.itemId);
389
const result = insertStack(bag.inventory, cargo.stack, def);
390
if (!result.ok || result.remainder)
391
{ return false; }
392
bag.inventory = result.slots;
393
this.#persistBag(characterId, bag);
394
return true;
395
}
396
}
397
398
if (cargo.kind === "money")
399
{
400
this.#creditVault(characterId, cargo);
401
return true;
402
}
403
return false;
404
}
405
406
#creditVault (characterId, cargo)
407
{
408
const onlineId = this.simulation.characterEntities.get(characterId);
409
const bag = onlineId
410
? this.simulation.bagOf(onlineId)
411
: this.stateDb.getBag(characterId);
412
if (!bag)
413
{ return; }
414
if (cargo.kind === "money")
415
{
416
bag.vaultCurrency = (bag.vaultCurrency | 0) + (cargo.amount | 0);
417
this.#persistBag(characterId, bag);
418
return;
419
}
420
if (cargo.kind === "item")
421
{
422
const def = itemDefinition(cargo.stack.itemId);
423
const result = insertStack(bag.vault ?? emptySlots(), cargo.stack, def);
424
bag.vault = result.ok ? result.slots : [...(bag.vault ?? []), cargo.stack];
425
this.#persistBag(characterId, bag);
426
}
427
}
428
429
#persistBag (characterId, bag)
430
{
431
this.stateDb.saveBag(characterId, bag);
432
const onlineId = this.simulation.characterEntities.get(characterId);
433
if (onlineId)
434
{
435
this.simulation.applyBag(onlineId, bag);
436
this.simulation.pushInventory(characterId, bag);
437
}
438
}
439
}
@@ -0,0 +1,439 @@1
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";4
import { itemDefinition } from "../../../shared/definitions/items.js";5
import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";6
import { advanceCourierFlight } from "../../../shared/courier/flight.js";7
import { GAIT } from "../../../shared/protocol/constants.js";8
import { decodeChunkBlob } from "../world/chunkData.js";9
10
export class CourierService11
{12
constructor ({ stateDb, worldDb, simulation })13
{14
this.stateDb = stateDb;15
this.worldDb = worldDb;16
this.simulation = simulation;17
this.bankTiles = [];18
this.refreshBankIndex();19
}20
21
refreshBankIndex ()22
{23
const revisionId = this.worldDb.getActiveRevisionId();24
const banks = [];25
for (const coord of this.worldDb.listChunkCoords(revisionId))26
{27
const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);28
if (!row)29
{ continue; }30
const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);31
for (let localY = 0; localY < CHUNK_SIZE; localY++)32
{33
for (let localX = 0; localX < CHUNK_SIZE; localX++)34
{35
const block = data.blocks[localY * CHUNK_SIZE + localX];36
if (block?.typeId !== BlockType.bank)37
{ continue; }38
banks.push({39
tileX: coord.chunk_x * CHUNK_SIZE + localX,40
tileY: coord.chunk_y * CHUNK_SIZE + localY41
});42
}43
}44
}45
this.bankTiles = banks;46
}47
48
nearestBank (tileX, tileY)49
{50
if (!this.bankTiles.length)51
{ return null; }52
let best = null;53
let bestDist = Infinity;54
for (const bank of this.bankTiles)55
{56
const dist = Math.hypot(bank.tileX - tileX, bank.tileY - tileY);57
if (dist < bestDist)58
{59
bestDist = dist;60
best = bank;61
}62
}63
return best;64
}65
66
/**67
* Player dispatch: cargo is money or one inventory stack.68
* destination: { kind: "bank" } | { kind: "player", firstName, lastName }69
*/70
dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo })71
{72
const onlineId = this.simulation.characterEntities.get(characterId);73
const bag = onlineId74
? this.simulation.bagOf(onlineId)75
: this.stateDb.getBag(characterId);76
if (!bag)77
{78
const error = new Error("No bag.");79
error.userFacing = true;80
throw error;81
}82
83
let takenCargo;84
if (cargo?.kind === "money")85
{86
const amount = Math.max(0, cargo.amount | 0);87
if (amount <= 0 || amount > (bag.currency | 0))88
{89
const error = new Error("Not enough coins.");90
error.userFacing = true;91
throw error;92
}93
bag.currency -= amount;94
takenCargo = { kind: "money", amount };95
}96
else if (cargo?.kind === "item")97
{98
const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);99
if (!taken.ok || !taken.taken)100
{101
const error = new Error("That item is not available.");102
error.userFacing = true;103
throw error;104
}105
bag.inventory = taken.slots;106
takenCargo = { kind: "item", stack: taken.taken };107
}108
else109
{110
const error = new Error("Pigeon cargo must be money or one item stack.");111
error.userFacing = true;112
throw error;113
}114
115
const dest = this.#resolveDestination(destination, originTileX, originTileY);116
this.#persistBag(characterId, bag);117
const transit = this.stateDb.insertCourierTransit({118
senderCharacterId: characterId,119
destinationKind: dest.kind,120
destinationCharacterId: dest.characterId ?? null,121
cargo: takenCargo,122
originX: originTileX + 0.5,123
originY: originTileY + 0.5,124
destX: dest.tileX + 0.5,125
destY: dest.tileY + 0.5,126
traveled: 0,127
status: "in_transit",128
entityId: null129
});130
return { transit, bag };131
}132
133
/** Market / system dispatch already holding cargo (no bag take). */134
dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo })135
{136
const dest = this.#resolveDestination(destination, originTileX, originTileY);137
return this.stateDb.insertCourierTransit({138
senderCharacterId,139
destinationKind: dest.kind,140
destinationCharacterId: dest.characterId ?? null,141
cargo,142
originX: originTileX + 0.5,143
originY: originTileY + 0.5,144
destX: dest.tileX + 0.5,145
destY: dest.tileY + 0.5,146
traveled: 0,147
status: "in_transit",148
entityId: null149
});150
}151
152
step (now, dt)153
{154
const events = [];155
const settings = this.simulation.settings;156
for (const transit of this.stateDb.listActiveCourierTransits())157
{158
this.#retargetPlayerDest(transit);159
const advanced = advanceCourierFlight({160
originX: transit.originX,161
originY: transit.originY,162
destX: transit.destX,163
destY: transit.destY,164
traveled: transit.traveled,165
dt,166
settings167
});168
transit.traveled = advanced.traveled;169
transit.updatedAt = now;170
171
if (advanced.arrived)172
{173
events.push(...this.#deliver(transit, now));174
continue;175
}176
177
events.push(...this.#syncVisiblePigeon(transit, advanced, now));178
this.stateDb.updateCourierTransit(transit);179
}180
return events;181
}182
183
#retargetPlayerDest (transit)184
{185
if (transit.destinationKind !== "player" || !transit.destinationCharacterId)186
{ return; }187
const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId);188
if (onlineId)189
{190
const pos = this.simulation.positionOf(onlineId);191
if (pos)192
{193
transit.destX = pos.tileX + 0.5;194
transit.destY = pos.tileY + 0.5;195
}196
return;197
}198
const character = this.stateDb.getCharacter(transit.destinationCharacterId);199
if (character)200
{201
transit.destX = character.tile_x + 0.5;202
transit.destY = character.tile_y + 0.5;203
}204
}205
206
#resolveDestination (destination, originTileX, originTileY)207
{208
if (destination?.kind === "player")209
{210
const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);211
if (!character)212
{213
const error = new Error("No character with that name.");214
error.userFacing = true;215
throw error;216
}217
const onlineId = this.simulation.characterEntities.get(character.character_id);218
const pos = onlineId ? this.simulation.positionOf(onlineId) : null;219
return {220
kind: "player",221
characterId: character.character_id,222
tileX: pos?.tileX ?? character.tile_x,223
tileY: pos?.tileY ?? character.tile_y224
};225
}226
if (destination?.kind === "bank")227
{228
const bank = this.nearestBank(originTileX, originTileY);229
if (!bank)230
{231
const error = new Error("No bank exists in the world yet.");232
error.userFacing = true;233
throw error;234
}235
return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY };236
}237
const error = new Error("Pigeon destination must be bank or player.");238
error.userFacing = true;239
throw error;240
}241
242
#syncVisiblePigeon (transit, advanced, now)243
{244
const events = [];245
const tileX = Math.floor(advanced.x);246
const tileY = Math.floor(advanced.y);247
if (!this.simulation.chunkIsSimulating(tileX, tileY))248
{249
if (transit.entityId)250
{251
this.simulation.despawnEntity(transit.entityId);252
events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY });253
transit.entityId = null;254
}255
return events;256
}257
258
if (!transit.entityId || !this.simulation.entityRecord(transit.entityId))259
{260
transit.entityId = null;261
const def = mobDefinition(MobId.pigeon);262
const entityId = this.simulation.spawnEntity({263
position: { tileX, tileY },264
movement: { gait: GAIT.walk, walkCarry: 0 },265
path: { tiles: [] },266
flight: {267
x: advanced.x,268
y: advanced.y,269
targetX: transit.destX,270
targetY: transit.destY,271
speed: advanced.speed,272
nextPickAt: now + 60_000,273
lastAt: now,274
courierId: transit.courierId275
},276
appearance: {277
sex: def.sex,278
firstName: def.displayName,279
lastName: "",280
sprite: mobSpriteName(MobId.pigeon)281
},282
creature: { mobTypeId: MobId.pigeon },283
health: { current: 1, max: 1 }284
}, { requireResident: true });285
if (entityId != null)286
{ transit.entityId = entityId; }287
return events;288
}289
290
const moved = this.simulation.updateCourierFlight(transit.entityId, {291
x: advanced.x,292
y: advanced.y,293
targetX: transit.destX,294
targetY: transit.destY,295
speed: advanced.speed,296
lastAt: now,297
courierId: transit.courierId298
}, now);299
if (moved?.despawned)300
{301
transit.entityId = null;302
events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY });303
}304
else if (moved?.event)305
{ events.push(moved.event); }306
return events;307
}308
309
#deliver (transit, now)310
{311
const events = [];312
if (transit.entityId)313
{314
this.simulation.despawnEntity(transit.entityId);315
events.push({316
type: "entity-despawn",317
entityId: transit.entityId,318
tileX: Math.floor(transit.destX),319
tileY: Math.floor(transit.destY)320
});321
transit.entityId = null;322
}323
324
if (transit.destinationKind === "bank")325
{ this.#creditVault(transit.senderCharacterId, transit.cargo); }326
else if (transit.destinationKind === "player")327
{328
const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);329
if (!delivered)330
{331
const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))332
?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));333
if (bank)334
{335
transit.originX = transit.destX;336
transit.originY = transit.destY;337
transit.destX = bank.tileX + 0.5;338
transit.destY = bank.tileY + 0.5;339
transit.traveled = 0;340
transit.destinationKind = "bank";341
transit.updatedAt = now;342
this.stateDb.updateCourierTransit(transit);343
events.push({344
type: "pigeon-reroute-bank",345
courierId: transit.courierId,346
characterId: transit.destinationCharacterId347
});348
return events;349
}350
this.#creditVault(transit.destinationCharacterId, transit.cargo);351
}352
}353
354
transit.status = "delivered";355
transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY);356
transit.updatedAt = now;357
this.stateDb.updateCourierTransit(transit);358
events.push({359
type: "pigeon-delivered",360
courierId: transit.courierId,361
senderCharacterId: transit.senderCharacterId,362
destinationKind: transit.destinationKind,363
destinationCharacterId: transit.destinationCharacterId,364
cargo: transit.cargo365
});366
return events;367
}368
369
#tryDeliverToPlayer (characterId, cargo)370
{371
const onlineId = this.simulation.characterEntities.get(characterId);372
if (onlineId)373
{374
if (cargo.kind === "money")375
{376
const bag = this.simulation.bagOf(onlineId);377
if (!bag)378
{ return false; }379
bag.currency = (bag.currency | 0) + (cargo.amount | 0);380
this.#persistBag(characterId, bag);381
return true;382
}383
if (cargo.kind === "item")384
{385
const bag = this.simulation.bagOf(onlineId);386
if (!bag)387
{ return false; }388
const def = itemDefinition(cargo.stack.itemId);389
const result = insertStack(bag.inventory, cargo.stack, def);390
if (!result.ok || result.remainder)391
{ return false; }392
bag.inventory = result.slots;393
this.#persistBag(characterId, bag);394
return true;395
}396
}397
398
if (cargo.kind === "money")399
{400
this.#creditVault(characterId, cargo);401
return true;402
}403
return false;404
}405
406
#creditVault (characterId, cargo)407
{408
const onlineId = this.simulation.characterEntities.get(characterId);409
const bag = onlineId410
? this.simulation.bagOf(onlineId)411
: this.stateDb.getBag(characterId);412
if (!bag)413
{ return; }414
if (cargo.kind === "money")415
{416
bag.vaultCurrency = (bag.vaultCurrency | 0) + (cargo.amount | 0);417
this.#persistBag(characterId, bag);418
return;419
}420
if (cargo.kind === "item")421
{422
const def = itemDefinition(cargo.stack.itemId);423
const result = insertStack(bag.vault ?? emptySlots(), cargo.stack, def);424
bag.vault = result.ok ? result.slots : [...(bag.vault ?? []), cargo.stack];425
this.#persistBag(characterId, bag);426
}427
}428
429
#persistBag (characterId, bag)430
{431
this.stateDb.saveBag(characterId, bag);432
const onlineId = this.simulation.characterEntities.get(characterId);433
if (onlineId)434
{435
this.simulation.applyBag(onlineId, bag);436
this.simulation.pushInventory(characterId, bag);437
}438
}439
}@@ -237,6 +237,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
237
237
characterId: session.characterId
238
238
});
239
239
break;
240
case MessageType.sendPigeon:
241
requirePlaying(session);
242
{
243
const result = simulation.dispatchPigeon({
244
characterId: session.characterId,
245
destination: message.destination,
246
cargo: message.cargo
247
});
248
send(session, {
249
type: MessageType.pigeonDispatched,
250
courierId: result.transit.courierId,
251
destinationKind: result.transit.destinationKind,
252
destinationCharacterId: result.transit.destinationCharacterId
253
});
254
send(session, { type: MessageType.inventory, ...result.bag });
255
}
256
break;
240
257
case MessageType.editorLoadChunk:
241
258
requireAdmin(session);
242
259
send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
@@ -439,7 +456,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
439
456
}
440
457
if (event.type === "inventory")
441
458
{
442
const session = sessions.get(event.sessionId);
459
const session = event.sessionId != null
460
? sessions.get(event.sessionId)
461
: [...sessions.values()].find((entry) => entry.characterId === event.characterId);
443
462
if (!session)
444
463
{ continue; }
445
464
send(session, {
@@ -462,7 +481,24 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
462
481
}
463
482
continue;
464
483
}
465
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
484
if (event.type === "pigeon-delivered")
485
{
486
for (const session of sessions.values())
487
{
488
if (session.characterId === event.senderCharacterId
489
|| session.characterId === event.destinationCharacterId)
490
{
491
send(session, {
492
type: MessageType.pigeonDelivered,
493
courierId: event.courierId,
494
destinationKind: event.destinationKind,
495
cargo: event.cargo
496
});
497
}
498
}
499
continue;
500
}
501
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
466
502
{ publishEntity(event); }
467
503
}
468
504
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -602,7 +638,24 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
602
638
};
603
639
}
604
640
605
return { sessions, onTickResult, wss };
641
return {
642
sessions,
643
onTickResult,
644
wss,
645
async shutdown ()
646
{
647
for (const session of [...sessions.values()])
648
{
649
leaveWorld(session);
650
try
651
{ session.socket.close(1001, "Server shutting down"); }
652
catch
653
{ /* ignore */ }
654
}
655
sessions.clear();
656
await simulation.shutdown();
657
}
658
};
606
659
}
607
660
608
661
function send (session, payload)
@@ -237,6 +237,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,237
characterId: session.characterId237
characterId: session.characterId238
});238
});239
break;239
break;240
case MessageType.sendPigeon:241
requirePlaying(session);242
{243
const result = simulation.dispatchPigeon({244
characterId: session.characterId,245
destination: message.destination,246
cargo: message.cargo247
});248
send(session, {249
type: MessageType.pigeonDispatched,250
courierId: result.transit.courierId,251
destinationKind: result.transit.destinationKind,252
destinationCharacterId: result.transit.destinationCharacterId253
});254
send(session, { type: MessageType.inventory, ...result.bag });255
}256
break;240
case MessageType.editorLoadChunk:257
case MessageType.editorLoadChunk:241
requireAdmin(session);258
requireAdmin(session);242
send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });259
send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });@@ -439,7 +456,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,439
}456
}440
if (event.type === "inventory")457
if (event.type === "inventory")441
{458
{442
const session = sessions.get(event.sessionId);459
const session = event.sessionId != null460
? sessions.get(event.sessionId)461
: [...sessions.values()].find((entry) => entry.characterId === event.characterId);443
if (!session)462
if (!session)444
{ continue; }463
{ continue; }445
send(session, {464
send(session, {@@ -462,7 +481,24 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,462
}481
}463
continue;482
continue;464
}483
}465
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")484
if (event.type === "pigeon-delivered")485
{486
for (const session of sessions.values())487
{488
if (session.characterId === event.senderCharacterId489
|| session.characterId === event.destinationCharacterId)490
{491
send(session, {492
type: MessageType.pigeonDelivered,493
courierId: event.courierId,494
destinationKind: event.destinationKind,495
cargo: event.cargo496
});497
}498
}499
continue;500
}501
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")466
{ publishEntity(event); }502
{ publishEntity(event); }467
}503
}468
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)504
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)@@ -602,7 +638,24 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,602
};638
};603
}639
}604
640
605
return { sessions, onTickResult, wss };641
return {642
sessions,643
onTickResult,644
wss,645
async shutdown ()646
{647
for (const session of [...sessions.values()])648
{649
leaveWorld(session);650
try651
{ session.socket.close(1001, "Server shutting down"); }652
catch653
{ /* ignore */ }654
}655
sessions.clear();656
await simulation.shutdown();657
}658
};606
}659
}607
660
608
function send (session, payload)661
function send (session, payload)@@ -24,8 +24,12 @@ const httpServer = createHttpServer(rootDir);
24
24
const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation });
25
25
26
26
let tickTimer = null;
27
let shuttingDown = false;
28
27
29
function scheduleTick ()
28
30
{
31
if (shuttingDown)
32
{ return; }
29
33
const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));
30
34
tickTimer = setTimeout(() =>
31
35
{
@@ -43,17 +47,22 @@ httpServer.listen(port, () =>
43
47
console.log(`World editor: http://localhost:${port}/editor`);
44
48
});
45
49
46
function shutdown ()
50
async function shutdown (signal)
47
51
{
52
if (shuttingDown)
53
{ return; }
54
shuttingDown = true;
55
console.log(`Shutting down (${signal})…`);
48
56
clearTimeout(tickTimer);
49
simulation.shutdown().finally(() =>
50
{
51
worldDb.close();
52
stateDb.close();
53
httpServer.close();
54
process.exit(0);
55
});
57
try
58
{ await gateway.shutdown(); }
59
catch (error)
60
{ console.error("Graceful shutdown error:", error); }
61
worldDb.close();
62
stateDb.close();
63
await new Promise((resolve) => httpServer.close(resolve));
64
process.exit(0);
56
65
}
57
66
58
process.on("SIGINT", shutdown);
59
process.on("SIGTERM", shutdown);
67
process.on("SIGINT", () => { void shutdown("SIGINT"); });
68
process.on("SIGTERM", () => { void shutdown("SIGTERM"); });
@@ -24,8 +24,12 @@ const httpServer = createHttpServer(rootDir);24
const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation });24
const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation });25
25
26
let tickTimer = null;26
let tickTimer = null;27
let shuttingDown = false;28
27
function scheduleTick ()29
function scheduleTick ()28
{30
{31
if (shuttingDown)32
{ return; }29
const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));33
const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));30
tickTimer = setTimeout(() =>34
tickTimer = setTimeout(() =>31
{35
{@@ -43,17 +47,22 @@ httpServer.listen(port, () =>43
console.log(`World editor: http://localhost:${port}/editor`);47
console.log(`World editor: http://localhost:${port}/editor`);44
});48
});45
49
46
function shutdown ()50
async function shutdown (signal)47
{51
{52
if (shuttingDown)53
{ return; }54
shuttingDown = true;55
console.log(`Shutting down (${signal})…`);48
clearTimeout(tickTimer);56
clearTimeout(tickTimer);49
simulation.shutdown().finally(() =>57
try50
{58
{ await gateway.shutdown(); }51
worldDb.close();59
catch (error)52
stateDb.close();60
{ console.error("Graceful shutdown error:", error); }53
httpServer.close();61
worldDb.close();54
process.exit(0);62
stateDb.close();55
});63
await new Promise((resolve) => httpServer.close(resolve));64
process.exit(0);56
}65
}57
66
58
process.on("SIGINT", shutdown);67
process.on("SIGINT", () => { void shutdown("SIGINT"); });59
process.on("SIGTERM", shutdown);68
process.on("SIGTERM", () => { void shutdown("SIGTERM"); });@@ -38,6 +38,23 @@ export function bagView (ecs, handle)
38
38
};
39
39
}
40
40
41
export function applyBagView (ecs, handle, bag)
42
{
43
const inventory = ensureInventory(ecs, handle);
44
inventory.slots = publicSlots(bag.inventory ?? emptySlots());
45
const equipment = ensureEquipment(ecs, handle);
46
const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
47
equipment.slots = nextEquip.slots;
48
let currency = ecs.get(handle, Component.currency);
49
if (!currency)
50
{ currency = ecs.add(handle, Component.currency, { amount: 0 }); }
51
currency.amount = bag.currency | 0;
52
const vault = ensureVault(ecs, handle);
53
vault.slots = publicSlots(bag.vault ?? emptySlots());
54
vault.currency = bag.vaultCurrency | 0;
55
return bagView(ecs, handle);
56
}
57
41
58
export function handleItemCommand (world, sessionId, command, now)
42
59
{
43
60
switch (command.type)
@@ -38,6 +38,23 @@ export function bagView (ecs, handle)38
};38
};39
}39
}40
40
41
export function applyBagView (ecs, handle, bag)42
{43
const inventory = ensureInventory(ecs, handle);44
inventory.slots = publicSlots(bag.inventory ?? emptySlots());45
const equipment = ensureEquipment(ecs, handle);46
const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());47
equipment.slots = nextEquip.slots;48
let currency = ecs.get(handle, Component.currency);49
if (!currency)50
{ currency = ecs.add(handle, Component.currency, { amount: 0 }); }51
currency.amount = bag.currency | 0;52
const vault = ensureVault(ecs, handle);53
vault.slots = publicSlots(bag.vault ?? emptySlots());54
vault.currency = bag.vaultCurrency | 0;55
return bagView(ecs, handle);56
}57
41
export function handleItemCommand (world, sessionId, command, now)58
export function handleItemCommand (world, sessionId, command, now)42
{59
{43
switch (command.type)60
switch (command.type)@@ -75,6 +75,23 @@ CREATE TABLE IF NOT EXISTS ground_items (
75
75
source TEXT NOT NULL,
76
76
dropped_by_character_id INTEGER
77
77
);
78
79
CREATE TABLE IF NOT EXISTS courier_transits (
80
courier_id INTEGER PRIMARY KEY AUTOINCREMENT,
81
sender_character_id INTEGER NOT NULL,
82
destination_kind TEXT NOT NULL,
83
destination_character_id INTEGER,
84
cargo_blob TEXT NOT NULL,
85
origin_x REAL NOT NULL,
86
origin_y REAL NOT NULL,
87
dest_x REAL NOT NULL,
88
dest_y REAL NOT NULL,
89
traveled REAL NOT NULL DEFAULT 0,
90
status TEXT NOT NULL,
91
entity_id INTEGER,
92
updated_at INTEGER NOT NULL,
93
created_at INTEGER NOT NULL
94
);
78
95
`;
79
96
80
97
export class StateDatabase
@@ -519,6 +536,68 @@ export class StateDatabase
519
536
this.db.prepare("DELETE FROM ground_items WHERE ground_item_id = ?").run(groundItemId);
520
537
}
521
538
539
insertCourierTransit (transit)
540
{
541
const now = transit.updatedAt ?? Date.now();
542
const result = this.db.prepare(`
543
INSERT INTO courier_transits (
544
sender_character_id, destination_kind, destination_character_id, cargo_blob,
545
origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at
546
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
547
`).run(
548
transit.senderCharacterId,
549
transit.destinationKind,
550
transit.destinationCharacterId ?? null,
551
JSON.stringify(transit.cargo),
552
transit.originX,
553
transit.originY,
554
transit.destX,
555
transit.destY,
556
transit.traveled ?? 0,
557
transit.status ?? "in_transit",
558
transit.entityId ?? null,
559
now,
560
transit.createdAt ?? now
561
);
562
return this.getCourierTransit(Number(result.lastInsertRowid));
563
}
564
565
getCourierTransit (courierId)
566
{
567
const row = this.db.prepare("SELECT * FROM courier_transits WHERE courier_id = ?").get(courierId);
568
return row ? parseCourierTransit(row) : null;
569
}
570
571
listActiveCourierTransits ()
572
{
573
return this.db.prepare(`
574
SELECT * FROM courier_transits WHERE status = 'in_transit' ORDER BY courier_id ASC
575
`).all().map(parseCourierTransit);
576
}
577
578
updateCourierTransit (transit)
579
{
580
this.db.prepare(`
581
UPDATE courier_transits
582
SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
583
origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
584
destination_kind = ?, destination_character_id = ?
585
WHERE courier_id = ?
586
`).run(
587
transit.traveled ?? 0,
588
transit.status,
589
transit.entityId ?? null,
590
transit.updatedAt ?? Date.now(),
591
transit.originX,
592
transit.originY,
593
transit.destX,
594
transit.destY,
595
transit.destinationKind,
596
transit.destinationCharacterId ?? null,
597
transit.courierId
598
);
599
}
600
522
601
close ()
523
602
{
524
603
this.db.close();
@@ -560,3 +639,23 @@ function parseBag (row, characterId)
560
639
vaultCurrency: row.vault_currency
561
640
};
562
641
}
642
643
function parseCourierTransit (row)
644
{
645
return {
646
courierId: row.courier_id,
647
senderCharacterId: row.sender_character_id,
648
destinationKind: row.destination_kind,
649
destinationCharacterId: row.destination_character_id,
650
cargo: JSON.parse(row.cargo_blob),
651
originX: row.origin_x,
652
originY: row.origin_y,
653
destX: row.dest_x,
654
destY: row.dest_y,
655
traveled: row.traveled,
656
status: row.status,
657
entityId: row.entity_id,
658
updatedAt: row.updated_at,
659
createdAt: row.created_at
660
};
661
}
@@ -75,6 +75,23 @@ CREATE TABLE IF NOT EXISTS ground_items (75
source TEXT NOT NULL,75
source TEXT NOT NULL,76
dropped_by_character_id INTEGER76
dropped_by_character_id INTEGER77
);77
);78
79
CREATE TABLE IF NOT EXISTS courier_transits (80
courier_id INTEGER PRIMARY KEY AUTOINCREMENT,81
sender_character_id INTEGER NOT NULL,82
destination_kind TEXT NOT NULL,83
destination_character_id INTEGER,84
cargo_blob TEXT NOT NULL,85
origin_x REAL NOT NULL,86
origin_y REAL NOT NULL,87
dest_x REAL NOT NULL,88
dest_y REAL NOT NULL,89
traveled REAL NOT NULL DEFAULT 0,90
status TEXT NOT NULL,91
entity_id INTEGER,92
updated_at INTEGER NOT NULL,93
created_at INTEGER NOT NULL94
);78
`;95
`;79
96
80
export class StateDatabase97
export class StateDatabase@@ -519,6 +536,68 @@ export class StateDatabase519
this.db.prepare("DELETE FROM ground_items WHERE ground_item_id = ?").run(groundItemId);536
this.db.prepare("DELETE FROM ground_items WHERE ground_item_id = ?").run(groundItemId);520
}537
}521
538
539
insertCourierTransit (transit)540
{541
const now = transit.updatedAt ?? Date.now();542
const result = this.db.prepare(`543
INSERT INTO courier_transits (544
sender_character_id, destination_kind, destination_character_id, cargo_blob,545
origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at546
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)547
`).run(548
transit.senderCharacterId,549
transit.destinationKind,550
transit.destinationCharacterId ?? null,551
JSON.stringify(transit.cargo),552
transit.originX,553
transit.originY,554
transit.destX,555
transit.destY,556
transit.traveled ?? 0,557
transit.status ?? "in_transit",558
transit.entityId ?? null,559
now,560
transit.createdAt ?? now561
);562
return this.getCourierTransit(Number(result.lastInsertRowid));563
}564
565
getCourierTransit (courierId)566
{567
const row = this.db.prepare("SELECT * FROM courier_transits WHERE courier_id = ?").get(courierId);568
return row ? parseCourierTransit(row) : null;569
}570
571
listActiveCourierTransits ()572
{573
return this.db.prepare(`574
SELECT * FROM courier_transits WHERE status = 'in_transit' ORDER BY courier_id ASC575
`).all().map(parseCourierTransit);576
}577
578
updateCourierTransit (transit)579
{580
this.db.prepare(`581
UPDATE courier_transits582
SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,583
origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,584
destination_kind = ?, destination_character_id = ?585
WHERE courier_id = ?586
`).run(587
transit.traveled ?? 0,588
transit.status,589
transit.entityId ?? null,590
transit.updatedAt ?? Date.now(),591
transit.originX,592
transit.originY,593
transit.destX,594
transit.destY,595
transit.destinationKind,596
transit.destinationCharacterId ?? null,597
transit.courierId598
);599
}600
522
close ()601
close ()523
{602
{524
this.db.close();603
this.db.close();@@ -560,3 +639,23 @@ function parseBag (row, characterId)560
vaultCurrency: row.vault_currency639
vaultCurrency: row.vault_currency561
};640
};562
}641
}642
643
function parseCourierTransit (row)644
{645
return {646
courierId: row.courier_id,647
senderCharacterId: row.sender_character_id,648
destinationKind: row.destination_kind,649
destinationCharacterId: row.destination_character_id,650
cargo: JSON.parse(row.cargo_blob),651
originX: row.origin_x,652
originY: row.origin_y,653
destX: row.dest_x,654
destY: row.dest_y,655
traveled: row.traveled,656
status: row.status,657
entityId: row.entity_id,658
updatedAt: row.updated_at,659
createdAt: row.created_at660
};661
}@@ -29,6 +29,9 @@ export function stepFreeFlight (world, now = Date.now())
29
29
const def = mobDefinition(entity.creature.mobTypeId);
30
30
if (!def?.freeFlight)
31
31
{ continue; }
32
const existingFlight = world.ecs.get(entity.handle, Component.flight);
33
if (existingFlight?.courierId != null)
34
{ continue; }
32
35
if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
33
36
{ continue; }
34
37
if (world.frozen?.has?.(entity.entityId))
@@ -29,6 +29,9 @@ export function stepFreeFlight (world, now = Date.now())29
const def = mobDefinition(entity.creature.mobTypeId);29
const def = mobDefinition(entity.creature.mobTypeId);30
if (!def?.freeFlight)30
if (!def?.freeFlight)31
{ continue; }31
{ continue; }32
const existingFlight = world.ecs.get(entity.handle, Component.flight);33
if (existingFlight?.courierId != null)34
{ continue; }32
if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY))35
if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY))33
{ continue; }36
{ continue; }34
if (world.frozen?.has?.(entity.entityId))37
if (world.frozen?.has?.(entity.entityId))@@ -20,6 +20,9 @@ export const WorkerMessage = Object.freeze({
20
20
entitiesInRegion: "entitiesInRegion",
21
21
inspect: "inspect",
22
22
inspectBag: "inspectBag",
23
applyBag: "applyBag",
24
updateFlight: "updateFlight",
25
chunkIsSimulating: "chunkIsSimulating",
23
26
setGroundItems: "setGroundItems",
24
27
stepSpawners: "stepSpawners",
25
28
stepSystems: "stepSystems"
@@ -20,6 +20,9 @@ export const WorkerMessage = Object.freeze({20
entitiesInRegion: "entitiesInRegion",20
entitiesInRegion: "entitiesInRegion",21
inspect: "inspect",21
inspect: "inspect",22
inspectBag: "inspectBag",22
inspectBag: "inspectBag",23
applyBag: "applyBag",24
updateFlight: "updateFlight",25
chunkIsSimulating: "chunkIsSimulating",23
setGroundItems: "setGroundItems",26
setGroundItems: "setGroundItems",24
stepSpawners: "stepSpawners",27
stepSpawners: "stepSpawners",25
stepSystems: "stepSystems"28
stepSystems: "stepSystems"@@ -30,6 +30,7 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../
30
30
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31
31
import { mobComponents } from "./spawners.js";
32
32
import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";
33
import { CourierService } from "../courier/service.js";
33
34
34
35
export class Simulation
35
36
{
@@ -48,6 +49,8 @@ export class Simulation
48
49
this.characterEntities = new Map();
49
50
this.commandQueue = [];
50
51
this.replication = [];
52
this.pendingPrivate = [];
53
this.courier = null;
51
54
this.authoredCache = new Map();
52
55
this.nextEntityId = 1;
53
56
this.nextGroundItemId = stateDb.nextGroundItemId();
@@ -69,6 +72,11 @@ export class Simulation
69
72
});
70
73
this.workers.push(worker);
71
74
}
75
this.courier = new CourierService({
76
stateDb: this.stateDb,
77
worldDb: this.worldDb,
78
simulation: this
79
});
72
80
}
73
81
74
82
get now ()
@@ -97,6 +105,7 @@ export class Simulation
97
105
});
98
106
}
99
107
this.#syncAllReplicas();
108
this.courier?.refreshBankIndex();
100
109
}
101
110
102
111
enqueue (sessionId, command)
@@ -185,7 +194,11 @@ export class Simulation
185
194
if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
186
195
{ events.push(...this.#stepSpawners()); }
187
196
197
if (this.courier)
198
{ events.push(...this.courier.step(now, dt)); }
199
188
200
this.#syncGhosts();
201
events.push(...this.pendingPrivate.splice(0));
189
202
return { now, events, replication: this.drainReplication() };
190
203
}
191
204
@@ -280,6 +293,22 @@ export class Simulation
280
293
const position = components.position;
281
294
if (!position)
282
295
{ throw new Error("spawnEntity requires position."); }
296
if (options.requireResident)
297
{
298
const workerId = this.#ownerOfTile(position.tileX, position.tileY);
299
if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY))
300
{ return null; }
301
const view = this.workers[workerId].call({
302
type: WorkerMessage.spawn,
303
entityId,
304
components
305
});
306
this.#remember(view, workerId);
307
if (components.appearance)
308
{ this.#queueReplication(replicationSpawn(view)); }
309
this.#syncGhosts();
310
return entityId;
311
}
283
312
if (components.chunkLoader)
284
313
{ this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
285
314
else
@@ -304,6 +333,111 @@ export class Simulation
304
333
return entityId;
305
334
}
306
335
336
despawnEntity (entityId)
337
{
338
const record = this.directory.get(entityId);
339
if (!record)
340
{ return; }
341
const dropped = this.workers[record.workerId].call({
342
type: WorkerMessage.despawn,
343
entityId
344
});
345
if (dropped)
346
{ this.#queueReplication(replicationDespawn(dropped)); }
347
this.#forget(entityId);
348
}
349
350
chunkIsSimulating (tileX, tileY)
351
{
352
const loaders = this.#allLoaders();
353
const { chunkSim } = accumulateLoaderRefs(loaders);
354
return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0;
355
}
356
357
updateCourierFlight (entityId, flightPatch, now = this.now)
358
{
359
const record = this.directory.get(entityId);
360
if (!record)
361
{ return { despawned: true, entityId }; }
362
const tileX = Math.floor(flightPatch.x);
363
const tileY = Math.floor(flightPatch.y);
364
const owner = this.#ownerOfTile(tileX, tileY);
365
if (owner == null || owner !== record.workerId)
366
{
367
this.despawnEntity(entityId);
368
return { despawned: true, entityId };
369
}
370
const result = this.workers[owner].call({
371
type: WorkerMessage.updateFlight,
372
entityId,
373
flight: flightPatch,
374
now
375
});
376
if (result?.transferRequest)
377
{
378
const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);
379
this.#recalculateActivation(now);
380
const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
381
if (move)
382
{
383
this.#applyMoveToDirectory(move);
384
return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };
385
}
386
this.despawnEntity(entityId);
387
return { despawned: true, entityId };
388
}
389
if (result?.event)
390
{
391
this.#applyMoveToDirectory(result.event);
392
return { event: result.event };
393
}
394
return null;
395
}
396
397
applyBag (entityId, bag)
398
{
399
const record = this.directory.get(entityId);
400
if (!record)
401
{ return null; }
402
return this.workers[record.workerId].call({
403
type: WorkerMessage.applyBag,
404
entityId,
405
bag
406
});
407
}
408
409
pushInventory (characterId, bag)
410
{
411
this.pendingPrivate.push({
412
type: "inventory",
413
characterId,
414
inventory: bag.inventory,
415
equipment: bag.equipment,
416
currency: bag.currency,
417
vault: bag.vault,
418
vaultCurrency: bag.vaultCurrency
419
});
420
}
421
422
dispatchPigeon ({ characterId, destination, cargo })
423
{
424
const entityId = this.characterEntities.get(characterId);
425
const position = entityId ? this.positionOf(entityId) : null;
426
if (!position)
427
{
428
const error = new Error("Enter the world before sending a pigeon.");
429
error.userFacing = true;
430
throw error;
431
}
432
return this.courier.dispatchFromPlayer({
433
characterId,
434
originTileX: position.tileX,
435
originTileY: position.tileY,
436
destination,
437
cargo
438
});
439
}
440
307
441
despawnCharacter (characterId)
308
442
{
309
443
const entityId = this.characterEntities.get(characterId);
@@ -30,6 +30,7 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../30
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";30
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";31
import { mobComponents } from "./spawners.js";31
import { mobComponents } from "./spawners.js";32
import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";32
import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";33
import { CourierService } from "../courier/service.js";33
34
34
export class Simulation35
export class Simulation35
{36
{@@ -48,6 +49,8 @@ export class Simulation48
this.characterEntities = new Map();49
this.characterEntities = new Map();49
this.commandQueue = [];50
this.commandQueue = [];50
this.replication = [];51
this.replication = [];52
this.pendingPrivate = [];53
this.courier = null;51
this.authoredCache = new Map();54
this.authoredCache = new Map();52
this.nextEntityId = 1;55
this.nextEntityId = 1;53
this.nextGroundItemId = stateDb.nextGroundItemId();56
this.nextGroundItemId = stateDb.nextGroundItemId();@@ -69,6 +72,11 @@ export class Simulation69
});72
});70
this.workers.push(worker);73
this.workers.push(worker);71
}74
}75
this.courier = new CourierService({76
stateDb: this.stateDb,77
worldDb: this.worldDb,78
simulation: this79
});72
}80
}73
81
74
get now ()82
get now ()@@ -97,6 +105,7 @@ export class Simulation97
});105
});98
}106
}99
this.#syncAllReplicas();107
this.#syncAllReplicas();108
this.courier?.refreshBankIndex();100
}109
}101
110
102
enqueue (sessionId, command)111
enqueue (sessionId, command)@@ -185,7 +194,11 @@ export class Simulation185
if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)194
if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)186
{ events.push(...this.#stepSpawners()); }195
{ events.push(...this.#stepSpawners()); }187
196
197
if (this.courier)198
{ events.push(...this.courier.step(now, dt)); }199
188
this.#syncGhosts();200
this.#syncGhosts();201
events.push(...this.pendingPrivate.splice(0));189
return { now, events, replication: this.drainReplication() };202
return { now, events, replication: this.drainReplication() };190
}203
}191
204
@@ -280,6 +293,22 @@ export class Simulation280
const position = components.position;293
const position = components.position;281
if (!position)294
if (!position)282
{ throw new Error("spawnEntity requires position."); }295
{ throw new Error("spawnEntity requires position."); }296
if (options.requireResident)297
{298
const workerId = this.#ownerOfTile(position.tileX, position.tileY);299
if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY))300
{ return null; }301
const view = this.workers[workerId].call({302
type: WorkerMessage.spawn,303
entityId,304
components305
});306
this.#remember(view, workerId);307
if (components.appearance)308
{ this.#queueReplication(replicationSpawn(view)); }309
this.#syncGhosts();310
return entityId;311
}283
if (components.chunkLoader)312
if (components.chunkLoader)284
{ this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }313
{ this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }285
else314
else@@ -304,6 +333,111 @@ export class Simulation304
return entityId;333
return entityId;305
}334
}306
335
336
despawnEntity (entityId)337
{338
const record = this.directory.get(entityId);339
if (!record)340
{ return; }341
const dropped = this.workers[record.workerId].call({342
type: WorkerMessage.despawn,343
entityId344
});345
if (dropped)346
{ this.#queueReplication(replicationDespawn(dropped)); }347
this.#forget(entityId);348
}349
350
chunkIsSimulating (tileX, tileY)351
{352
const loaders = this.#allLoaders();353
const { chunkSim } = accumulateLoaderRefs(loaders);354
return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0;355
}356
357
updateCourierFlight (entityId, flightPatch, now = this.now)358
{359
const record = this.directory.get(entityId);360
if (!record)361
{ return { despawned: true, entityId }; }362
const tileX = Math.floor(flightPatch.x);363
const tileY = Math.floor(flightPatch.y);364
const owner = this.#ownerOfTile(tileX, tileY);365
if (owner == null || owner !== record.workerId)366
{367
this.despawnEntity(entityId);368
return { despawned: true, entityId };369
}370
const result = this.workers[owner].call({371
type: WorkerMessage.updateFlight,372
entityId,373
flight: flightPatch,374
now375
});376
if (result?.transferRequest)377
{378
const events = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: owner }]);379
this.#recalculateActivation(now);380
const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);381
if (move)382
{383
this.#applyMoveToDirectory(move);384
return { event: { ...move, worldX: flightPatch.x, worldY: flightPatch.y, freeFlight: true } };385
}386
this.despawnEntity(entityId);387
return { despawned: true, entityId };388
}389
if (result?.event)390
{391
this.#applyMoveToDirectory(result.event);392
return { event: result.event };393
}394
return null;395
}396
397
applyBag (entityId, bag)398
{399
const record = this.directory.get(entityId);400
if (!record)401
{ return null; }402
return this.workers[record.workerId].call({403
type: WorkerMessage.applyBag,404
entityId,405
bag406
});407
}408
409
pushInventory (characterId, bag)410
{411
this.pendingPrivate.push({412
type: "inventory",413
characterId,414
inventory: bag.inventory,415
equipment: bag.equipment,416
currency: bag.currency,417
vault: bag.vault,418
vaultCurrency: bag.vaultCurrency419
});420
}421
422
dispatchPigeon ({ characterId, destination, cargo })423
{424
const entityId = this.characterEntities.get(characterId);425
const position = entityId ? this.positionOf(entityId) : null;426
if (!position)427
{428
const error = new Error("Enter the world before sending a pigeon.");429
error.userFacing = true;430
throw error;431
}432
return this.courier.dispatchFromPlayer({433
characterId,434
originTileX: position.tileX,435
originTileY: position.tileY,436
destination,437
cargo438
});439
}440
307
despawnCharacter (characterId)441
despawnCharacter (characterId)308
{442
{309
const entityId = this.characterEntities.get(characterId);443
const entityId = this.characterEntities.get(characterId);@@ -20,6 +20,7 @@ import { collectSpawnRequests } from "./spawners.js";
20
20
import { mobDefinition } from "../../../shared/definitions/mobs.js";
21
21
import {
22
22
bagView,
23
applyBagView,
23
24
expireGroundItems,
24
25
groundItemsInChunk,
25
26
groundItemsInRegion,
@@ -92,6 +93,12 @@ export class WorkerWorld
92
93
return { ok: true };
93
94
case WorkerMessage.inspectBag:
94
95
return this.#inspectBag(message.entityId);
96
case WorkerMessage.applyBag:
97
return this.#applyBag(message.entityId, message.bag);
98
case WorkerMessage.updateFlight:
99
return this.#updateFlight(message.entityId, message.flight, message.now);
100
case WorkerMessage.chunkIsSimulating:
101
return this.chunkIsSimulating(message.tileX, message.tileY);
95
102
case WorkerMessage.applyTransfer:
96
103
return this.#applyTransfer(message);
97
104
case WorkerMessage.commitTransfer:
@@ -345,6 +352,70 @@ export class WorkerWorld
345
352
return bagView(this.ecs, handle);
346
353
}
347
354
355
#applyBag (entityId, bag)
356
{
357
const handle = this.ecs.handleOf(entityId);
358
if (handle == null)
359
{ return null; }
360
return applyBagView(this.ecs, handle, bag);
361
}
362
363
#updateFlight (entityId, flightPatch, now = Date.now())
364
{
365
const handle = this.ecs.handleOf(entityId);
366
if (handle == null)
367
{ return null; }
368
let flight = this.ecs.get(handle, Component.flight);
369
if (!flight)
370
{ flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }
371
else
372
{ Object.assign(flight, flightPatch); }
373
const position = this.ecs.get(handle, Component.position);
374
const movement = this.ecs.get(handle, Component.movement);
375
const fromTileX = position.tileX;
376
const fromTileY = position.tileY;
377
const tileX = Math.floor(flight.x);
378
const tileY = Math.floor(flight.y);
379
position.tileX = tileX;
380
position.tileY = tileY;
381
const destRegionX = tileToRegion(tileX);
382
const destRegionY = tileToRegion(tileY);
383
if (!this.ownsRegion(destRegionX, destRegionY))
384
{
385
this.frozen.add(entityId);
386
return {
387
transferRequest: {
388
type: "transfer-request",
389
entityId,
390
fromTileX,
391
fromTileY,
392
destTileX: tileX,
393
destTileY: tileY,
394
toRegionX: destRegionX,
395
toRegionY: destRegionY
396
}
397
};
398
}
399
const dt = flight.lastAt && now > flight.lastAt
400
? Math.min(0.25, (now - flight.lastAt) / 1000)
401
: 1 / 20;
402
return {
403
event: {
404
type: "entity-move",
405
entityId,
406
fromTileX,
407
fromTileY,
408
tileX,
409
tileY,
410
worldX: flight.x,
411
worldY: flight.y,
412
gait: movement?.gait ?? "walk",
413
lerpMs: Math.max(50, Math.round(dt * 1000)),
414
freeFlight: true
415
}
416
};
417
}
418
348
419
#moveTo (sessionId, characterId, tileX, tileY)
349
420
{
350
421
const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
@@ -20,6 +20,7 @@ import { collectSpawnRequests } from "./spawners.js";20
import { mobDefinition } from "../../../shared/definitions/mobs.js";20
import { mobDefinition } from "../../../shared/definitions/mobs.js";21
import {21
import {22
bagView,22
bagView,23
applyBagView,23
expireGroundItems,24
expireGroundItems,24
groundItemsInChunk,25
groundItemsInChunk,25
groundItemsInRegion,26
groundItemsInRegion,@@ -92,6 +93,12 @@ export class WorkerWorld92
return { ok: true };93
return { ok: true };93
case WorkerMessage.inspectBag:94
case WorkerMessage.inspectBag:94
return this.#inspectBag(message.entityId);95
return this.#inspectBag(message.entityId);96
case WorkerMessage.applyBag:97
return this.#applyBag(message.entityId, message.bag);98
case WorkerMessage.updateFlight:99
return this.#updateFlight(message.entityId, message.flight, message.now);100
case WorkerMessage.chunkIsSimulating:101
return this.chunkIsSimulating(message.tileX, message.tileY);95
case WorkerMessage.applyTransfer:102
case WorkerMessage.applyTransfer:96
return this.#applyTransfer(message);103
return this.#applyTransfer(message);97
case WorkerMessage.commitTransfer:104
case WorkerMessage.commitTransfer:@@ -345,6 +352,70 @@ export class WorkerWorld345
return bagView(this.ecs, handle);352
return bagView(this.ecs, handle);346
}353
}347
354
355
#applyBag (entityId, bag)356
{357
const handle = this.ecs.handleOf(entityId);358
if (handle == null)359
{ return null; }360
return applyBagView(this.ecs, handle, bag);361
}362
363
#updateFlight (entityId, flightPatch, now = Date.now())364
{365
const handle = this.ecs.handleOf(entityId);366
if (handle == null)367
{ return null; }368
let flight = this.ecs.get(handle, Component.flight);369
if (!flight)370
{ flight = this.ecs.add(handle, Component.flight, { ...flightPatch }); }371
else372
{ Object.assign(flight, flightPatch); }373
const position = this.ecs.get(handle, Component.position);374
const movement = this.ecs.get(handle, Component.movement);375
const fromTileX = position.tileX;376
const fromTileY = position.tileY;377
const tileX = Math.floor(flight.x);378
const tileY = Math.floor(flight.y);379
position.tileX = tileX;380
position.tileY = tileY;381
const destRegionX = tileToRegion(tileX);382
const destRegionY = tileToRegion(tileY);383
if (!this.ownsRegion(destRegionX, destRegionY))384
{385
this.frozen.add(entityId);386
return {387
transferRequest: {388
type: "transfer-request",389
entityId,390
fromTileX,391
fromTileY,392
destTileX: tileX,393
destTileY: tileY,394
toRegionX: destRegionX,395
toRegionY: destRegionY396
}397
};398
}399
const dt = flight.lastAt && now > flight.lastAt400
? Math.min(0.25, (now - flight.lastAt) / 1000)401
: 1 / 20;402
return {403
event: {404
type: "entity-move",405
entityId,406
fromTileX,407
fromTileY,408
tileX,409
tileY,410
worldX: flight.x,411
worldY: flight.y,412
gait: movement?.gait ?? "walk",413
lerpMs: Math.max(50, Math.round(dt * 1000)),414
freeFlight: true415
}416
};417
}418
348
#moveTo (sessionId, characterId, tileX, tileY)419
#moveTo (sessionId, characterId, tileX, tileY)349
{420
{350
const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);421
const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);@@ -0,0 +1,133 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { BlockType } from "../../shared/definitions/tiles.js";
4
import { ItemId } from "../../shared/definitions/items.js";
5
import { pigeonSpeedAtProgress, advanceCourierFlight } from "../../shared/courier/flight.js";
6
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7
import {
8
makeCharacter,
9
makeSimulation,
10
stepTimes
11
} from "./helpers/simulationHarness.js";
12
13
test("pigeon flight uses takeoff, cruise, then landing speeds", () =>
14
{
15
const settings = {
16
pigeonTakeoffTilesPerSec: 3,
17
pigeonCruiseTilesPerSec: 8,
18
pigeonLandingTilesPerSec: 3,
19
pigeonPhaseTiles: 5
20
};
21
assert.equal(pigeonSpeedAtProgress(0, 40, settings), 3);
22
assert.equal(pigeonSpeedAtProgress(4.9, 40, settings), 3);
23
assert.equal(pigeonSpeedAtProgress(10, 40, settings), 8);
24
assert.equal(pigeonSpeedAtProgress(36, 40, settings), 3);
25
26
const takeoff = advanceCourierFlight({
27
originX: 0, originY: 0, destX: 40, destY: 0, traveled: 0, dt: 1, settings
28
});
29
assert.equal(takeoff.speed, 3);
30
assert.ok(Math.abs(takeoff.traveled - 3) < 1e-6);
31
32
const cruise = advanceCourierFlight({
33
originX: 0, originY: 0, destX: 40, destY: 0, traveled: 10, dt: 1, settings
34
});
35
assert.equal(cruise.speed, 8);
36
assert.ok(Math.abs(cruise.traveled - 18) < 1e-6);
37
});
38
39
function placeBank (worldDb, tileX, tileY)
40
{
41
const chunkX = Math.floor(tileX / 16);
42
const chunkY = Math.floor(tileY / 16);
43
const data = createEmptyChunkData();
44
data.open = true;
45
const localX = tileX - chunkX * 16;
46
const localY = tileY - chunkY * 16;
47
data.blocks[localY * 16 + localX] = { typeId: BlockType.bank, state: 0 };
48
worldDb.saveChunkVersion(
49
chunkX,
50
chunkY,
51
worldDb.getActiveRevisionId(),
52
true,
53
encodeChunkBlob(data)
54
);
55
}
56
57
test("pigeon to bank deposits money into the sender vault", () =>
58
{
59
const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
60
try
61
{
62
placeBank(harness.worldDb, 20, 8);
63
harness.simulation.reloadWorld();
64
harness.simulation.applySettings({
65
pigeonTakeoffTilesPerSec: 20,
66
pigeonCruiseTilesPerSec: 20,
67
pigeonLandingTilesPerSec: 20,
68
pigeonPhaseTiles: 5,
69
simulationTickHz: 20
70
});
71
const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
72
const entityId = harness.simulation.spawnCharacter(1, character);
73
const before = harness.simulation.bagOf(entityId);
74
assert.ok((before.currency | 0) >= 5);
75
const result = harness.simulation.dispatchPigeon({
76
characterId: character.character_id,
77
destination: { kind: "bank" },
78
cargo: { kind: "money", amount: 5 }
79
});
80
assert.equal(result.transit.destinationKind, "bank");
81
assert.equal(harness.simulation.bagOf(entityId).currency, before.currency - 5);
82
83
stepTimes(harness.simulation, 80);
84
const after = harness.stateDb.getBag(character.character_id);
85
assert.equal(after.vaultCurrency, (before.vaultCurrency | 0) + 5);
86
assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
87
}
88
finally
89
{ harness.close(); }
90
});
91
92
test("pigeon delivers an item to an online player inventory", () =>
93
{
94
const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
95
try
96
{
97
harness.simulation.applySettings({
98
pigeonTakeoffTilesPerSec: 40,
99
pigeonCruiseTilesPerSec: 40,
100
pigeonLandingTilesPerSec: 40,
101
simulationTickHz: 20
102
});
103
const sender = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8, firstName: "Ada", lastName: "Sender" });
104
const receiver = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Bob", lastName: "Receiver" });
105
const senderId = harness.simulation.spawnCharacter(1, sender);
106
const receiverId = harness.simulation.spawnCharacter(2, receiver);
107
const bag = harness.simulation.bagOf(senderId);
108
const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
109
assert.ok(appleSlot >= 0);
110
const senderQty = bag.inventory[appleSlot].quantity;
111
const receiverBefore = harness.simulation.bagOf(receiverId);
112
const receiverApples = receiverBefore.inventory
113
.filter((slot) => slot?.itemId === ItemId.apple)
114
.reduce((sum, slot) => sum + slot.quantity, 0);
115
116
harness.simulation.dispatchPigeon({
117
characterId: sender.character_id,
118
destination: { kind: "player", firstName: "Bob", lastName: "Receiver" },
119
cargo: { kind: "item", slotIndex: appleSlot, quantity: 1 }
120
});
121
assert.equal(harness.simulation.bagOf(senderId).inventory[appleSlot].quantity, senderQty - 1);
122
123
stepTimes(harness.simulation, 40);
124
const receiverAfter = harness.simulation.bagOf(receiverId);
125
const receiverApplesAfter = receiverAfter.inventory
126
.filter((slot) => slot?.itemId === ItemId.apple)
127
.reduce((sum, slot) => sum + slot.quantity, 0);
128
assert.equal(receiverApplesAfter, receiverApples + 1);
129
assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
130
}
131
finally
132
{ harness.close(); }
133
});
@@ -0,0 +1,133 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { BlockType } from "../../shared/definitions/tiles.js";4
import { ItemId } from "../../shared/definitions/items.js";5
import { pigeonSpeedAtProgress, advanceCourierFlight } from "../../shared/courier/flight.js";6
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";7
import {8
makeCharacter,9
makeSimulation,10
stepTimes11
} from "./helpers/simulationHarness.js";12
13
test("pigeon flight uses takeoff, cruise, then landing speeds", () =>14
{15
const settings = {16
pigeonTakeoffTilesPerSec: 3,17
pigeonCruiseTilesPerSec: 8,18
pigeonLandingTilesPerSec: 3,19
pigeonPhaseTiles: 520
};21
assert.equal(pigeonSpeedAtProgress(0, 40, settings), 3);22
assert.equal(pigeonSpeedAtProgress(4.9, 40, settings), 3);23
assert.equal(pigeonSpeedAtProgress(10, 40, settings), 8);24
assert.equal(pigeonSpeedAtProgress(36, 40, settings), 3);25
26
const takeoff = advanceCourierFlight({27
originX: 0, originY: 0, destX: 40, destY: 0, traveled: 0, dt: 1, settings28
});29
assert.equal(takeoff.speed, 3);30
assert.ok(Math.abs(takeoff.traveled - 3) < 1e-6);31
32
const cruise = advanceCourierFlight({33
originX: 0, originY: 0, destX: 40, destY: 0, traveled: 10, dt: 1, settings34
});35
assert.equal(cruise.speed, 8);36
assert.ok(Math.abs(cruise.traveled - 18) < 1e-6);37
});38
39
function placeBank (worldDb, tileX, tileY)40
{41
const chunkX = Math.floor(tileX / 16);42
const chunkY = Math.floor(tileY / 16);43
const data = createEmptyChunkData();44
data.open = true;45
const localX = tileX - chunkX * 16;46
const localY = tileY - chunkY * 16;47
data.blocks[localY * 16 + localX] = { typeId: BlockType.bank, state: 0 };48
worldDb.saveChunkVersion(49
chunkX,50
chunkY,51
worldDb.getActiveRevisionId(),52
true,53
encodeChunkBlob(data)54
);55
}56
57
test("pigeon to bank deposits money into the sender vault", () =>58
{59
const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });60
try61
{62
placeBank(harness.worldDb, 20, 8);63
harness.simulation.reloadWorld();64
harness.simulation.applySettings({65
pigeonTakeoffTilesPerSec: 20,66
pigeonCruiseTilesPerSec: 20,67
pigeonLandingTilesPerSec: 20,68
pigeonPhaseTiles: 5,69
simulationTickHz: 2070
});71
const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });72
const entityId = harness.simulation.spawnCharacter(1, character);73
const before = harness.simulation.bagOf(entityId);74
assert.ok((before.currency | 0) >= 5);75
const result = harness.simulation.dispatchPigeon({76
characterId: character.character_id,77
destination: { kind: "bank" },78
cargo: { kind: "money", amount: 5 }79
});80
assert.equal(result.transit.destinationKind, "bank");81
assert.equal(harness.simulation.bagOf(entityId).currency, before.currency - 5);82
83
stepTimes(harness.simulation, 80);84
const after = harness.stateDb.getBag(character.character_id);85
assert.equal(after.vaultCurrency, (before.vaultCurrency | 0) + 5);86
assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);87
}88
finally89
{ harness.close(); }90
});91
92
test("pigeon delivers an item to an online player inventory", () =>93
{94
const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });95
try96
{97
harness.simulation.applySettings({98
pigeonTakeoffTilesPerSec: 40,99
pigeonCruiseTilesPerSec: 40,100
pigeonLandingTilesPerSec: 40,101
simulationTickHz: 20102
});103
const sender = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8, firstName: "Ada", lastName: "Sender" });104
const receiver = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Bob", lastName: "Receiver" });105
const senderId = harness.simulation.spawnCharacter(1, sender);106
const receiverId = harness.simulation.spawnCharacter(2, receiver);107
const bag = harness.simulation.bagOf(senderId);108
const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);109
assert.ok(appleSlot >= 0);110
const senderQty = bag.inventory[appleSlot].quantity;111
const receiverBefore = harness.simulation.bagOf(receiverId);112
const receiverApples = receiverBefore.inventory113
.filter((slot) => slot?.itemId === ItemId.apple)114
.reduce((sum, slot) => sum + slot.quantity, 0);115
116
harness.simulation.dispatchPigeon({117
characterId: sender.character_id,118
destination: { kind: "player", firstName: "Bob", lastName: "Receiver" },119
cargo: { kind: "item", slotIndex: appleSlot, quantity: 1 }120
});121
assert.equal(harness.simulation.bagOf(senderId).inventory[appleSlot].quantity, senderQty - 1);122
123
stepTimes(harness.simulation, 40);124
const receiverAfter = harness.simulation.bagOf(receiverId);125
const receiverApplesAfter = receiverAfter.inventory126
.filter((slot) => slot?.itemId === ItemId.apple)127
.reduce((sum, slot) => sum + slot.quantity, 0);128
assert.equal(receiverApplesAfter, receiverApples + 1);129
assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);130
}131
finally132
{ harness.close(); }133
});@@ -2121,6 +2121,15 @@ goods then appear in the shared vault.
2121
2121
A carrier pigeon must take time to cross the world; long-distance item and
2122
2122
currency delivery is intentionally not instantaneous.
2123
2123
2124
Flight speed is world-tunable in three phases (defaults chosen so a pigeon can
2125
overtake a running player):
2126
2127
| Phase | Distance | Default tiles/s | Setting |
2128
|-------|----------|-----------------|---------|
2129
| Takeoff | first `pigeonPhaseTiles` (default 5) | 3 | `pigeonTakeoffTilesPerSec` |
2130
| Cruise | middle of the route | 8 | `pigeonCruiseTilesPerSec` |
2131
| Landing | last `pigeonPhaseTiles` | 3 | `pigeonLandingTilesPerSec` |
2132
2124
2133
At MMO scale, however, every delivery should not keep an entire trail of regions
2125
2134
fully stimulated merely so a pigeon can advance. The recommended model is a
2126
2135
persistent courier transit record with world position/route/progress that can
@@ -2121,6 +2121,15 @@ goods then appear in the shared vault.2121
A carrier pigeon must take time to cross the world; long-distance item and2121
A carrier pigeon must take time to cross the world; long-distance item and2122
currency delivery is intentionally not instantaneous.2122
currency delivery is intentionally not instantaneous.2123
2123
2124
Flight speed is world-tunable in three phases (defaults chosen so a pigeon can2125
overtake a running player):2126
2127
| Phase | Distance | Default tiles/s | Setting |2128
|-------|----------|-----------------|---------|2129
| Takeoff | first `pigeonPhaseTiles` (default 5) | 3 | `pigeonTakeoffTilesPerSec` |2130
| Cruise | middle of the route | 8 | `pigeonCruiseTilesPerSec` |2131
| Landing | last `pigeonPhaseTiles` | 3 | `pigeonLandingTilesPerSec` |2132
2124
At MMO scale, however, every delivery should not keep an entire trail of regions2133
At MMO scale, however, every delivery should not keep an entire trail of regions2125
fully stimulated merely so a pigeon can advance. The recommended model is a2134
fully stimulated merely so a pigeon can advance. The recommended model is a2126
persistent courier transit record with world position/route/progress that can2135
persistent courier transit record with world position/route/progress that can