Ship letter/courier UX, per-pixel night shade, and follow fixes.
Letters seal on send and open on read; bag send/equip UI and chat opacity polish; sprite darkness follows source alpha instead of a full AABB block.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -19,24 +19,12 @@
19
19
<p id="bag-coins">0 coins</p>
20
20
<div id="equip-grid" class="item-grid equip"></div>
21
21
<div id="bag-grid" class="item-grid"></div>
22
<p id="bag-hint" class="hint">Click a slot, then Drop or Equip.</p>
22
<p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>
23
23
<div class="bag-actions">
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>
29
27
</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>
40
28
</aside>
41
29
<aside id="bank-panel" hidden>
42
30
<header>
@@ -58,8 +46,58 @@
58
46
<div id="incoming-list"></div>
59
47
<h3>Outgoing</h3>
60
48
<div id="outgoing-list"></div>
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>
49
<p class="hint">Right-click a bag item and choose Send to deliver by pigeon to the bank or a player.</p>
50
</aside>
51
52
<div id="send-backdrop" class="modal-backdrop" hidden></div>
53
<aside id="send-panel" hidden>
54
<header>
55
<h2>Send by pigeon</h2>
56
<button id="send-close" type="button">Close</button>
57
</header>
58
<div id="send-item" class="send-item">
59
<img id="send-item-img" alt="">
60
<strong id="send-item-name"></strong>
61
</div>
62
<label class="send-row">Quantity
63
<input id="send-qty" type="number" min="1" step="1" value="1">
64
</label>
65
<p id="send-target-label" class="hint">No target selected.</p>
66
<button id="send-pick-target" type="button">Select target</button>
67
<button id="send-confirm" type="button" disabled>Send</button>
68
<p id="send-status" class="hint"></p>
69
</aside>
70
71
<aside id="send-target-panel" hidden>
72
<header>
73
<h2>Select target</h2>
74
<button id="send-target-close" type="button">Back</button>
75
</header>
76
<div id="send-target-list"></div>
77
<div class="send-search">
78
<input id="send-search-first" type="text" placeholder="First name" autocomplete="off">
79
<input id="send-search-last" type="text" placeholder="Last name" autocomplete="off">
80
<button id="send-search" type="button">Search</button>
81
</div>
82
<div id="send-search-result"></div>
83
</aside>
84
85
<div id="letter-backdrop" class="modal-backdrop" hidden></div>
86
<aside id="letter-panel" hidden>
87
<header>
88
<h2 id="letter-title">Letter</h2>
89
<button id="letter-close" type="button">Close</button>
90
</header>
91
<div id="letter-paper" class="letter-paper">
92
<textarea id="letter-body" maxlength="2000" spellcheck="true" rows="1"></textarea>
93
<pre id="letter-signature" class="letter-signature"></pre>
94
</div>
95
<div class="bag-actions">
96
<button id="letter-save" type="button">Save</button>
97
</div>
98
<p id="letter-status" class="hint"></p>
62
99
</aside>
100
63
101
<div id="nametag" hidden></div>
64
102
<div id="chat-bubbles"></div>
65
103
<div id="chat-bar" hidden>
@@ -19,24 +19,12 @@19
<p id="bag-coins">0 coins</p>19
<p id="bag-coins">0 coins</p>20
<div id="equip-grid" class="item-grid equip"></div>20
<div id="equip-grid" class="item-grid equip"></div>21
<div id="bag-grid" class="item-grid"></div>21
<div id="bag-grid" class="item-grid"></div>22
<p id="bag-hint" class="hint">Click a slot, then Drop or Equip.</p>22
<p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>23
<div class="bag-actions">23
<div class="bag-actions">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>29
</div>27
</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>40
</aside>28
</aside>41
<aside id="bank-panel" hidden>29
<aside id="bank-panel" hidden>42
<header>30
<header>@@ -58,8 +46,58 @@58
<div id="incoming-list"></div>46
<div id="incoming-list"></div>59
<h3>Outgoing</h3>47
<h3>Outgoing</h3>60
<div id="outgoing-list"></div>48
<div id="outgoing-list"></div>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>49
<p class="hint">Right-click a bag item and choose Send to deliver by pigeon to the bank or a player.</p>50
</aside>51
52
<div id="send-backdrop" class="modal-backdrop" hidden></div>53
<aside id="send-panel" hidden>54
<header>55
<h2>Send by pigeon</h2>56
<button id="send-close" type="button">Close</button>57
</header>58
<div id="send-item" class="send-item">59
<img id="send-item-img" alt="">60
<strong id="send-item-name"></strong>61
</div>62
<label class="send-row">Quantity63
<input id="send-qty" type="number" min="1" step="1" value="1">64
</label>65
<p id="send-target-label" class="hint">No target selected.</p>66
<button id="send-pick-target" type="button">Select target</button>67
<button id="send-confirm" type="button" disabled>Send</button>68
<p id="send-status" class="hint"></p>69
</aside>70
71
<aside id="send-target-panel" hidden>72
<header>73
<h2>Select target</h2>74
<button id="send-target-close" type="button">Back</button>75
</header>76
<div id="send-target-list"></div>77
<div class="send-search">78
<input id="send-search-first" type="text" placeholder="First name" autocomplete="off">79
<input id="send-search-last" type="text" placeholder="Last name" autocomplete="off">80
<button id="send-search" type="button">Search</button>81
</div>82
<div id="send-search-result"></div>83
</aside>84
85
<div id="letter-backdrop" class="modal-backdrop" hidden></div>86
<aside id="letter-panel" hidden>87
<header>88
<h2 id="letter-title">Letter</h2>89
<button id="letter-close" type="button">Close</button>90
</header>91
<div id="letter-paper" class="letter-paper">92
<textarea id="letter-body" maxlength="2000" spellcheck="true" rows="1"></textarea>93
<pre id="letter-signature" class="letter-signature"></pre>94
</div>95
<div class="bag-actions">96
<button id="letter-save" type="button">Save</button>97
</div>98
<p id="letter-status" class="hint"></p>62
</aside>99
</aside>100
63
<div id="nametag" hidden></div>101
<div id="nametag" hidden></div>64
<div id="chat-bubbles"></div>102
<div id="chat-bubbles"></div>65
<div id="chat-bar" hidden>103
<div id="chat-bar" hidden>@@ -110,6 +110,8 @@ export function initChat ({ socket, MessageType, getSettings })
110
110
bubbles.set(message.entityId, bubble);
111
111
}
112
112
bubble.element.textContent = message.text;
113
const readability = Math.min(1, Math.max(0, Number(message.readability ?? 1)));
114
bubble.element.style.opacity = String(readability);
113
115
bubble.until = Date.now() + BUBBLE_MS;
114
116
},
115
117
syncSettings ()
@@ -110,6 +110,8 @@ export function initChat ({ socket, MessageType, getSettings })110
bubbles.set(message.entityId, bubble);110
bubbles.set(message.entityId, bubble);111
}111
}112
bubble.element.textContent = message.text;112
bubble.element.textContent = message.text;113
const readability = Math.min(1, Math.max(0, Number(message.readability ?? 1)));114
bubble.element.style.opacity = String(readability);113
bubble.until = Date.now() + BUBBLE_MS;115
bubble.until = Date.now() + BUBBLE_MS;114
},116
},115
syncSettings ()117
syncSettings ()@@ -1,4 +1,11 @@
1
import { itemDefinition, itemAssetPath, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
1
import {
2
itemDefinition,
3
itemDescription,
4
itemAssetPathForStack,
5
ItemId,
6
EQUIPMENT_SLOT,
7
LETTER_MAX_BODY_CHARS
8
} from "/shared/definitions/items.js";
2
9
3
10
const EQUIP_LABELS = {
4
11
[EQUIPMENT_SLOT.head]: "Head",
@@ -9,7 +16,14 @@ const EQUIP_LABELS = {
9
16
[EQUIPMENT_SLOT.offhand]: "Off-hand"
10
17
};
11
18
12
export function initInventory ({ socket, MessageType, game })
19
export function initInventory ({
20
socket,
21
MessageType,
22
contextMenu,
23
resolveSpriteUrl,
24
getFriends,
25
getLocalName
26
})
13
27
{
14
28
const bagPanel = document.getElementById("bag-panel");
15
29
const bagGrid = document.getElementById("bag-grid");
@@ -21,9 +35,27 @@ export function initInventory ({ socket, MessageType, game })
21
35
const vaultCoins = document.getElementById("vault-coins");
22
36
const inheritGrid = document.getElementById("inherit-grid");
23
37
const inheritCoins = document.getElementById("inherit-coins");
38
39
const sendPanel = document.getElementById("send-panel");
40
const sendBackdrop = document.getElementById("send-backdrop");
41
const sendTargetPanel = document.getElementById("send-target-panel");
42
const sendTargetList = document.getElementById("send-target-list");
43
const sendSearchResult = document.getElementById("send-search-result");
44
const letterPanel = document.getElementById("letter-panel");
45
const letterBackdrop = document.getElementById("letter-backdrop");
46
const letterBody = document.getElementById("letter-body");
47
const letterSignature = document.getElementById("letter-signature");
48
const letterSave = document.getElementById("letter-save");
49
const letterTitle = document.getElementById("letter-title");
50
const letterStatus = document.getElementById("letter-status");
51
24
52
let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 };
25
53
let selected = null;
26
54
let bankOpen = false;
55
let sendState = null;
56
let letterState = null;
57
let pendingSearch = false;
58
let localCharacterId = null;
27
59
28
60
document.getElementById("bag-toggle").addEventListener("click", () =>
29
61
{
@@ -50,50 +82,50 @@ export function initInventory ({ socket, MessageType, game })
50
82
{
51
83
socket.send({ type: MessageType.claimInheritance });
52
84
});
53
document.getElementById("bag-pigeon-bank").addEventListener("click", () => sendPigeon({ kind: "bank" }));
54
document.getElementById("bag-pigeon-player").addEventListener("click", () =>
85
86
document.getElementById("send-close").addEventListener("click", () => closeSend());
87
sendBackdrop.addEventListener("click", () => closeSend());
88
document.getElementById("send-pick-target").addEventListener("click", () => openTargetPicker());
89
document.getElementById("send-target-close").addEventListener("click", () =>
90
{
91
sendTargetPanel.hidden = true;
92
});
93
document.getElementById("send-confirm").addEventListener("click", () => confirmSend());
94
document.getElementById("send-search").addEventListener("click", () =>
55
95
{
56
const firstName = document.getElementById("bag-pigeon-first").value.trim();
57
const lastName = document.getElementById("bag-pigeon-last").value.trim();
96
const firstName = document.getElementById("send-search-first").value.trim();
97
const lastName = document.getElementById("send-search-last").value.trim();
58
98
if (!firstName || !lastName)
59
99
{
60
setPigeonStatus("Enter a first and last name, or pick a friend.");
100
sendSearchResult.textContent = "Enter a first and last name.";
61
101
return;
62
102
}
63
sendPigeon({ kind: "player", firstName, lastName });
103
pendingSearch = true;
104
sendSearchResult.textContent = "Searching…";
105
socket.send({ type: MessageType.searchCharacter, firstName, lastName });
64
106
});
65
107
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)
108
document.getElementById("letter-close").addEventListener("click", () => closeLetter());
109
letterBackdrop.addEventListener("click", () => closeLetter());
110
letterSave.addEventListener("click", () =>
77
111
{
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)
112
if (!letterState || letterState.readOnly)
113
{ return; }
114
const body = letterBody.value;
115
socket.send({
116
type: letterState.mode === "edit" ? MessageType.editLetter : MessageType.writeLetter,
117
slotIndex: letterState.slotIndex,
118
body
119
});
120
letterStatus.textContent = "Saving…";
121
});
122
letterBody.addEventListener("input", () =>
94
123
{
95
document.getElementById("bag-pigeon-status").textContent = text;
96
}
124
if (letterState?.readOnly)
125
{ return; }
126
fitLetterBody();
127
refreshLetterSignature();
128
});
97
129
98
130
function render ()
99
131
{
@@ -108,7 +140,7 @@ export function initInventory ({ socket, MessageType, game })
108
140
{
109
141
const def = itemDefinition(slot.itemId);
110
142
const img = document.createElement("img");
111
img.src = itemAssetPath(slot.itemId);
143
img.src = itemAssetPathForStack(slot);
112
144
img.alt = def?.displayName ?? "";
113
145
button.append(img);
114
146
if (slot.quantity > 1)
@@ -122,10 +154,21 @@ export function initInventory ({ socket, MessageType, game })
122
154
button.addEventListener("click", () =>
123
155
{
124
156
selected = index;
125
const def = slot ? itemDefinition(slot.itemId) : null;
126
hint.textContent = def ? `${def.displayName}: ${def.description}` : "Empty slot.";
157
hint.textContent = slot
158
? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}: ${itemDescription(slot, { localCharacterId })}`
159
: "Empty slot.";
127
160
render();
128
161
});
162
button.addEventListener("contextmenu", (event) =>
163
{
164
event.preventDefault();
165
event.stopPropagation();
166
if (!slot)
167
{ return; }
168
selected = index;
169
render();
170
showItemMenu(event.clientX, event.clientY, index, slot);
171
});
129
172
bagGrid.append(button);
130
173
});
131
174
equipGrid.innerHTML = "";
@@ -135,7 +178,14 @@ export function initInventory ({ socket, MessageType, game })
135
178
const button = document.createElement("button");
136
179
button.className = "item-slot";
137
180
button.title = worn ? tooltip(worn) : label;
138
button.textContent = worn ? (itemDefinition(worn.itemId)?.displayName ?? label) : label;
181
if (worn)
182
{
183
const def = itemDefinition(worn.itemId);
184
const img = document.createElement("img");
185
img.src = itemAssetPathForStack(worn);
186
img.alt = def?.displayName ?? label;
187
button.append(img);
188
}
139
189
button.addEventListener("click", () =>
140
190
{
141
191
if (worn)
@@ -145,6 +195,251 @@ export function initInventory ({ socket, MessageType, game })
145
195
}
146
196
}
147
197
198
function showItemMenu (x, y, slotIndex, slot)
199
{
200
const def = itemDefinition(slot.itemId);
201
const items = [];
202
const isOwnLetter = slot.itemId === ItemId.letter
203
&& slot.instance?.kind === "letter"
204
&& Number(slot.instance.authorCharacterId) === Number(localCharacterId);
205
const canSend = slot.itemId !== ItemId.letter || isOwnLetter;
206
207
if (slot.itemId === ItemId.paper)
208
{
209
items.push({
210
label: "Write letter",
211
onSelect: () => openLetter({ mode: "write", slotIndex })
212
});
213
}
214
if (slot.itemId === ItemId.letter && slot.instance?.kind === "letter")
215
{
216
items.push({
217
label: "Read",
218
onSelect: () =>
219
{
220
if (slot.instance?.opened === false)
221
{ socket.send({ type: MessageType.openLetter, slotIndex }); }
222
openLetter({
223
mode: "read",
224
slotIndex,
225
instance: { ...slot.instance, opened: true }
226
});
227
}
228
});
229
if (isOwnLetter)
230
{
231
items.push({
232
label: "Edit letter",
233
onSelect: () => openLetter({
234
mode: "edit",
235
slotIndex,
236
instance: slot.instance
237
})
238
});
239
}
240
}
241
if (def?.equipment?.slot)
242
{
243
items.push({
244
label: "Equip",
245
onSelect: () => socket.send({ type: MessageType.equipItem, slotIndex })
246
});
247
}
248
if (canSend)
249
{
250
items.push({
251
label: "Send",
252
onSelect: () => openSend(slotIndex, slot)
253
});
254
}
255
items.push({
256
label: "Drop",
257
onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })
258
});
259
contextMenu?.show(x, y, items);
260
}
261
262
function openSend (slotIndex, slot)
263
{
264
const def = itemDefinition(slot.itemId);
265
sendState = {
266
slotIndex,
267
itemId: slot.itemId,
268
maxQty: slot.quantity | 0,
269
destination: null
270
};
271
document.getElementById("send-item-img").src = itemAssetPathForStack(slot);
272
document.getElementById("send-item-name").textContent = def?.displayName ?? "Item";
273
const qtyInput = document.getElementById("send-qty");
274
qtyInput.value = "1";
275
qtyInput.max = String(sendState.maxQty);
276
qtyInput.disabled = sendState.maxQty <= 1;
277
document.getElementById("send-target-label").textContent = "No target selected.";
278
document.getElementById("send-confirm").disabled = true;
279
document.getElementById("send-status").textContent = "";
280
sendPanel.hidden = false;
281
sendBackdrop.hidden = false;
282
sendTargetPanel.hidden = true;
283
}
284
285
function closeSend ()
286
{
287
sendState = null;
288
sendPanel.hidden = true;
289
sendBackdrop.hidden = true;
290
sendTargetPanel.hidden = true;
291
}
292
293
function openTargetPicker ()
294
{
295
if (!sendState)
296
{ return; }
297
sendTargetPanel.hidden = false;
298
sendSearchResult.replaceChildren();
299
document.getElementById("send-search-first").value = "";
300
document.getElementById("send-search-last").value = "";
301
renderTargetList();
302
}
303
304
function renderTargetList ()
305
{
306
sendTargetList.replaceChildren();
307
sendTargetList.append(targetRow({
308
kind: "bank",
309
label: "Bank",
310
hint: "Nearest bank → your vault"
311
}));
312
const friends = getFriends?.() ?? [];
313
if (!friends.length)
314
{
315
const empty = document.createElement("p");
316
empty.className = "hint";
317
empty.textContent = "No friends yet.";
318
sendTargetList.append(empty);
319
return;
320
}
321
for (const friend of friends)
322
{ sendTargetList.append(characterTargetRow(friend)); }
323
}
324
325
function targetRow ({ kind, label, hint, onPick })
326
{
327
const row = document.createElement("button");
328
row.type = "button";
329
row.className = "send-target-row";
330
row.innerHTML = `<strong>${label}</strong>${hint ? `<span class="hint">${hint}</span>` : ""}`;
331
row.addEventListener("click", () =>
332
{
333
if (onPick)
334
{ onPick(); }
335
else
336
{ pickTarget({ kind: "bank" }, "Bank"); }
337
});
338
return row;
339
}
340
341
function characterTargetRow (entry)
342
{
343
const row = document.createElement("button");
344
row.type = "button";
345
row.className = "send-target-row";
346
const preview = characterPreview(entry.layers);
347
const text = document.createElement("div");
348
text.className = "send-target-text";
349
text.innerHTML = `<strong>${entry.firstName} ${entry.lastName}</strong>`;
350
row.append(preview, text);
351
row.addEventListener("click", () =>
352
{
353
pickTarget({
354
kind: "player",
355
firstName: entry.firstName,
356
lastName: entry.lastName,
357
characterId: entry.characterId
358
}, `${entry.firstName} ${entry.lastName}`);
359
});
360
return row;
361
}
362
363
function characterPreview (layers)
364
{
365
const wrap = document.createElement("div");
366
wrap.className = "char-preview";
367
for (const layer of layers ?? [])
368
{
369
const url = resolveSpriteUrl?.(layer.sprite);
370
if (!url)
371
{ continue; }
372
const img = document.createElement("img");
373
img.src = url;
374
img.alt = "";
375
wrap.append(img);
376
}
377
return wrap;
378
}
379
380
function pickTarget (destination, label)
381
{
382
if (!sendState)
383
{ return; }
384
sendState.destination = destination;
385
document.getElementById("send-target-label").textContent = `Target: ${label}`;
386
document.getElementById("send-confirm").disabled = false;
387
sendTargetPanel.hidden = true;
388
}
389
390
function confirmSend ()
391
{
392
if (!sendState?.destination)
393
{ return; }
394
const quantity = Math.max(1, Math.min(sendState.maxQty, Number(document.getElementById("send-qty").value) | 0));
395
socket.send({
396
type: MessageType.sendPigeon,
397
destination: sendState.destination,
398
cargo: {
399
kind: "item",
400
slotIndex: sendState.slotIndex,
401
quantity
402
}
403
});
404
document.getElementById("send-status").textContent = "Pigeon dispatched…";
405
}
406
407
function openLetter ({ mode, slotIndex, instance })
408
{
409
letterState = { mode, slotIndex, readOnly: mode === "read", instance: instance ?? null };
410
letterTitle.textContent = mode === "write" ? "Write letter" : mode === "edit" ? "Edit letter" : "Letter";
411
letterBody.value = instance?.body ?? "";
412
letterBody.readOnly = letterState.readOnly;
413
letterBody.maxLength = LETTER_MAX_BODY_CHARS;
414
letterSave.hidden = letterState.readOnly;
415
letterStatus.textContent = "";
416
refreshLetterSignature();
417
letterPanel.hidden = false;
418
letterBackdrop.hidden = false;
419
fitLetterBody();
420
}
421
422
function fitLetterBody ()
423
{
424
letterBody.style.height = "auto";
425
letterBody.style.height = `${Math.max(letterBody.scrollHeight, 128)}px`;
426
}
427
428
function refreshLetterSignature ()
429
{
430
const name = letterState?.instance?.authorDisplayName
431
|| getLocalName?.()
432
|| "Unknown";
433
letterSignature.textContent = `Signed:\n${name}`;
434
}
435
436
function closeLetter ()
437
{
438
letterState = null;
439
letterPanel.hidden = true;
440
letterBackdrop.hidden = true;
441
}
442
148
443
function renderVault (grid, slots)
149
444
{
150
445
grid.innerHTML = "";
@@ -177,12 +472,54 @@ export function initInventory ({ socket, MessageType, game })
177
472
return {
178
473
isOpen ()
179
474
{
180
return !bagPanel.hidden || bankOpen;
475
return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden;
476
},
477
isBlocking ()
478
{
479
// Send/letter dialogs cover the view — keep world clicks blocked.
480
if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden)
481
{ return true; }
482
if (sendBackdrop && !sendBackdrop.hidden)
483
{ return true; }
484
if (letterBackdrop && !letterBackdrop.hidden)
485
{ return true; }
486
const x = GameInput.mousePosition.x;
487
const y = GameInput.mousePosition.y;
488
for (const element of [bagPanel, bankPanel])
489
{
490
if (!element || element.hidden)
491
{ continue; }
492
const box = element.getBoundingClientRect();
493
if (x >= box.left && x < box.right && y >= box.top && y < box.bottom)
494
{ return true; }
495
}
496
return false;
497
},
498
setLocalCharacterId (characterId)
499
{
500
localCharacterId = characterId;
181
501
},
182
502
handleInventory (message)
183
503
{
184
504
bag = { ...bag, ...message };
185
505
render();
506
if (letterState && letterStatus.textContent === "Saving…")
507
{
508
letterStatus.textContent = "Saved.";
509
if (letterState.mode === "write")
510
{ closeLetter(); }
511
else if (letterState.mode === "edit")
512
{
513
const slot = bag.inventory?.[letterState.slotIndex];
514
if (slot?.instance)
515
{
516
letterState.instance = slot.instance;
517
letterBody.value = slot.instance.body ?? "";
518
refreshLetterSignature();
519
fitLetterBody();
520
}
521
}
522
}
186
523
},
187
524
handleBank (message)
188
525
{
@@ -206,21 +543,28 @@ export function initInventory ({ socket, MessageType, game })
206
543
{ return; }
207
544
socket.send({ type: MessageType.bankDeposit, slotIndex: selected });
208
545
},
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
546
handlePigeonDispatched ()
217
547
{
218
setPigeonStatus("Pigeon is in flight.");
548
document.getElementById("send-status").textContent = "Pigeon is in flight.";
549
closeSend();
219
550
},
220
551
handlePigeonDelivered (message)
221
552
{
222
553
const kind = message.destinationKind === "bank" ? "bank vault" : "recipient";
223
setPigeonStatus(`Pigeon delivered to ${kind}.`);
554
hint.textContent = `Pigeon delivered to ${kind}.`;
555
},
556
handleCharacterSearch (message)
557
{
558
if (!pendingSearch)
559
{ return; }
560
pendingSearch = false;
561
sendSearchResult.replaceChildren();
562
if (!message.character)
563
{
564
sendSearchResult.textContent = "No character with that name.";
565
return;
566
}
567
sendSearchResult.append(characterTargetRow(message.character));
224
568
},
225
569
reset ()
226
570
{
@@ -228,7 +572,8 @@ export function initInventory ({ socket, MessageType, game })
228
572
bankPanel.hidden = true;
229
573
bankOpen = false;
230
574
selected = null;
231
setPigeonStatus("");
575
closeSend();
576
closeLetter();
232
577
}
233
578
};
234
579
}
@@ -1,4 +1,11 @@1
import { itemDefinition, itemAssetPath, EQUIPMENT_SLOT } from "/shared/definitions/items.js";1
import {2
itemDefinition,3
itemDescription,4
itemAssetPathForStack,5
ItemId,6
EQUIPMENT_SLOT,7
LETTER_MAX_BODY_CHARS8
} from "/shared/definitions/items.js";2
9
3
const EQUIP_LABELS = {10
const EQUIP_LABELS = {4
[EQUIPMENT_SLOT.head]: "Head",11
[EQUIPMENT_SLOT.head]: "Head",@@ -9,7 +16,14 @@ const EQUIP_LABELS = {9
[EQUIPMENT_SLOT.offhand]: "Off-hand"16
[EQUIPMENT_SLOT.offhand]: "Off-hand"10
};17
};11
18
12
export function initInventory ({ socket, MessageType, game })19
export function initInventory ({20
socket,21
MessageType,22
contextMenu,23
resolveSpriteUrl,24
getFriends,25
getLocalName26
})13
{27
{14
const bagPanel = document.getElementById("bag-panel");28
const bagPanel = document.getElementById("bag-panel");15
const bagGrid = document.getElementById("bag-grid");29
const bagGrid = document.getElementById("bag-grid");@@ -21,9 +35,27 @@ export function initInventory ({ socket, MessageType, game })21
const vaultCoins = document.getElementById("vault-coins");35
const vaultCoins = document.getElementById("vault-coins");22
const inheritGrid = document.getElementById("inherit-grid");36
const inheritGrid = document.getElementById("inherit-grid");23
const inheritCoins = document.getElementById("inherit-coins");37
const inheritCoins = document.getElementById("inherit-coins");38
39
const sendPanel = document.getElementById("send-panel");40
const sendBackdrop = document.getElementById("send-backdrop");41
const sendTargetPanel = document.getElementById("send-target-panel");42
const sendTargetList = document.getElementById("send-target-list");43
const sendSearchResult = document.getElementById("send-search-result");44
const letterPanel = document.getElementById("letter-panel");45
const letterBackdrop = document.getElementById("letter-backdrop");46
const letterBody = document.getElementById("letter-body");47
const letterSignature = document.getElementById("letter-signature");48
const letterSave = document.getElementById("letter-save");49
const letterTitle = document.getElementById("letter-title");50
const letterStatus = document.getElementById("letter-status");51
24
let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 };52
let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 };25
let selected = null;53
let selected = null;26
let bankOpen = false;54
let bankOpen = false;55
let sendState = null;56
let letterState = null;57
let pendingSearch = false;58
let localCharacterId = null;27
59
28
document.getElementById("bag-toggle").addEventListener("click", () =>60
document.getElementById("bag-toggle").addEventListener("click", () =>29
{61
{@@ -50,50 +82,50 @@ export function initInventory ({ socket, MessageType, game })50
{82
{51
socket.send({ type: MessageType.claimInheritance });83
socket.send({ type: MessageType.claimInheritance });52
});84
});53
document.getElementById("bag-pigeon-bank").addEventListener("click", () => sendPigeon({ kind: "bank" }));85
54
document.getElementById("bag-pigeon-player").addEventListener("click", () =>86
document.getElementById("send-close").addEventListener("click", () => closeSend());87
sendBackdrop.addEventListener("click", () => closeSend());88
document.getElementById("send-pick-target").addEventListener("click", () => openTargetPicker());89
document.getElementById("send-target-close").addEventListener("click", () =>90
{91
sendTargetPanel.hidden = true;92
});93
document.getElementById("send-confirm").addEventListener("click", () => confirmSend());94
document.getElementById("send-search").addEventListener("click", () =>55
{95
{56
const firstName = document.getElementById("bag-pigeon-first").value.trim();96
const firstName = document.getElementById("send-search-first").value.trim();57
const lastName = document.getElementById("bag-pigeon-last").value.trim();97
const lastName = document.getElementById("send-search-last").value.trim();58
if (!firstName || !lastName)98
if (!firstName || !lastName)59
{99
{60
setPigeonStatus("Enter a first and last name, or pick a friend.");100
sendSearchResult.textContent = "Enter a first and last name.";61
return;101
return;62
}102
}63
sendPigeon({ kind: "player", firstName, lastName });103
pendingSearch = true;104
sendSearchResult.textContent = "Searching…";105
socket.send({ type: MessageType.searchCharacter, firstName, lastName });64
});106
});65
107
66
function cargoPayload ()108
document.getElementById("letter-close").addEventListener("click", () => closeLetter());67
{109
letterBackdrop.addEventListener("click", () => closeLetter());68
if (selected != null && bag.inventory?.[selected])110
letterSave.addEventListener("click", () =>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
{111
{78
const cargo = cargoPayload();112
if (!letterState || letterState.readOnly)79
if (cargo.kind === "money" && (bag.currency | 0) < cargo.amount)113
{ return; }80
{114
const body = letterBody.value;81
setPigeonStatus("Not enough coins.");115
socket.send({82
return;116
type: letterState.mode === "edit" ? MessageType.editLetter : MessageType.writeLetter,83
}117
slotIndex: letterState.slotIndex,84
if (cargo.kind === "item" && selected == null)118
body85
{119
});86
setPigeonStatus("Select an item slot, or clear selection to send coins.");120
letterStatus.textContent = "Saving…";87
return;121
});88
}122
letterBody.addEventListener("input", () =>89
socket.send({ type: MessageType.sendPigeon, destination, cargo });90
setPigeonStatus("Pigeon dispatched…");91
}92
93
function setPigeonStatus (text)94
{123
{95
document.getElementById("bag-pigeon-status").textContent = text;124
if (letterState?.readOnly)96
}125
{ return; }126
fitLetterBody();127
refreshLetterSignature();128
});97
129
98
function render ()130
function render ()99
{131
{@@ -108,7 +140,7 @@ export function initInventory ({ socket, MessageType, game })108
{140
{109
const def = itemDefinition(slot.itemId);141
const def = itemDefinition(slot.itemId);110
const img = document.createElement("img");142
const img = document.createElement("img");111
img.src = itemAssetPath(slot.itemId);143
img.src = itemAssetPathForStack(slot);112
img.alt = def?.displayName ?? "";144
img.alt = def?.displayName ?? "";113
button.append(img);145
button.append(img);114
if (slot.quantity > 1)146
if (slot.quantity > 1)@@ -122,10 +154,21 @@ export function initInventory ({ socket, MessageType, game })122
button.addEventListener("click", () =>154
button.addEventListener("click", () =>123
{155
{124
selected = index;156
selected = index;125
const def = slot ? itemDefinition(slot.itemId) : null;157
hint.textContent = slot126
hint.textContent = def ? `${def.displayName}: ${def.description}` : "Empty slot.";158
? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}: ${itemDescription(slot, { localCharacterId })}`159
: "Empty slot.";127
render();160
render();128
});161
});162
button.addEventListener("contextmenu", (event) =>163
{164
event.preventDefault();165
event.stopPropagation();166
if (!slot)167
{ return; }168
selected = index;169
render();170
showItemMenu(event.clientX, event.clientY, index, slot);171
});129
bagGrid.append(button);172
bagGrid.append(button);130
});173
});131
equipGrid.innerHTML = "";174
equipGrid.innerHTML = "";@@ -135,7 +178,14 @@ export function initInventory ({ socket, MessageType, game })135
const button = document.createElement("button");178
const button = document.createElement("button");136
button.className = "item-slot";179
button.className = "item-slot";137
button.title = worn ? tooltip(worn) : label;180
button.title = worn ? tooltip(worn) : label;138
button.textContent = worn ? (itemDefinition(worn.itemId)?.displayName ?? label) : label;181
if (worn)182
{183
const def = itemDefinition(worn.itemId);184
const img = document.createElement("img");185
img.src = itemAssetPathForStack(worn);186
img.alt = def?.displayName ?? label;187
button.append(img);188
}139
button.addEventListener("click", () =>189
button.addEventListener("click", () =>140
{190
{141
if (worn)191
if (worn)@@ -145,6 +195,251 @@ export function initInventory ({ socket, MessageType, game })145
}195
}146
}196
}147
197
198
function showItemMenu (x, y, slotIndex, slot)199
{200
const def = itemDefinition(slot.itemId);201
const items = [];202
const isOwnLetter = slot.itemId === ItemId.letter203
&& slot.instance?.kind === "letter"204
&& Number(slot.instance.authorCharacterId) === Number(localCharacterId);205
const canSend = slot.itemId !== ItemId.letter || isOwnLetter;206
207
if (slot.itemId === ItemId.paper)208
{209
items.push({210
label: "Write letter",211
onSelect: () => openLetter({ mode: "write", slotIndex })212
});213
}214
if (slot.itemId === ItemId.letter && slot.instance?.kind === "letter")215
{216
items.push({217
label: "Read",218
onSelect: () =>219
{220
if (slot.instance?.opened === false)221
{ socket.send({ type: MessageType.openLetter, slotIndex }); }222
openLetter({223
mode: "read",224
slotIndex,225
instance: { ...slot.instance, opened: true }226
});227
}228
});229
if (isOwnLetter)230
{231
items.push({232
label: "Edit letter",233
onSelect: () => openLetter({234
mode: "edit",235
slotIndex,236
instance: slot.instance237
})238
});239
}240
}241
if (def?.equipment?.slot)242
{243
items.push({244
label: "Equip",245
onSelect: () => socket.send({ type: MessageType.equipItem, slotIndex })246
});247
}248
if (canSend)249
{250
items.push({251
label: "Send",252
onSelect: () => openSend(slotIndex, slot)253
});254
}255
items.push({256
label: "Drop",257
onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })258
});259
contextMenu?.show(x, y, items);260
}261
262
function openSend (slotIndex, slot)263
{264
const def = itemDefinition(slot.itemId);265
sendState = {266
slotIndex,267
itemId: slot.itemId,268
maxQty: slot.quantity | 0,269
destination: null270
};271
document.getElementById("send-item-img").src = itemAssetPathForStack(slot);272
document.getElementById("send-item-name").textContent = def?.displayName ?? "Item";273
const qtyInput = document.getElementById("send-qty");274
qtyInput.value = "1";275
qtyInput.max = String(sendState.maxQty);276
qtyInput.disabled = sendState.maxQty <= 1;277
document.getElementById("send-target-label").textContent = "No target selected.";278
document.getElementById("send-confirm").disabled = true;279
document.getElementById("send-status").textContent = "";280
sendPanel.hidden = false;281
sendBackdrop.hidden = false;282
sendTargetPanel.hidden = true;283
}284
285
function closeSend ()286
{287
sendState = null;288
sendPanel.hidden = true;289
sendBackdrop.hidden = true;290
sendTargetPanel.hidden = true;291
}292
293
function openTargetPicker ()294
{295
if (!sendState)296
{ return; }297
sendTargetPanel.hidden = false;298
sendSearchResult.replaceChildren();299
document.getElementById("send-search-first").value = "";300
document.getElementById("send-search-last").value = "";301
renderTargetList();302
}303
304
function renderTargetList ()305
{306
sendTargetList.replaceChildren();307
sendTargetList.append(targetRow({308
kind: "bank",309
label: "Bank",310
hint: "Nearest bank → your vault"311
}));312
const friends = getFriends?.() ?? [];313
if (!friends.length)314
{315
const empty = document.createElement("p");316
empty.className = "hint";317
empty.textContent = "No friends yet.";318
sendTargetList.append(empty);319
return;320
}321
for (const friend of friends)322
{ sendTargetList.append(characterTargetRow(friend)); }323
}324
325
function targetRow ({ kind, label, hint, onPick })326
{327
const row = document.createElement("button");328
row.type = "button";329
row.className = "send-target-row";330
row.innerHTML = `<strong>${label}</strong>${hint ? `<span class="hint">${hint}</span>` : ""}`;331
row.addEventListener("click", () =>332
{333
if (onPick)334
{ onPick(); }335
else336
{ pickTarget({ kind: "bank" }, "Bank"); }337
});338
return row;339
}340
341
function characterTargetRow (entry)342
{343
const row = document.createElement("button");344
row.type = "button";345
row.className = "send-target-row";346
const preview = characterPreview(entry.layers);347
const text = document.createElement("div");348
text.className = "send-target-text";349
text.innerHTML = `<strong>${entry.firstName} ${entry.lastName}</strong>`;350
row.append(preview, text);351
row.addEventListener("click", () =>352
{353
pickTarget({354
kind: "player",355
firstName: entry.firstName,356
lastName: entry.lastName,357
characterId: entry.characterId358
}, `${entry.firstName} ${entry.lastName}`);359
});360
return row;361
}362
363
function characterPreview (layers)364
{365
const wrap = document.createElement("div");366
wrap.className = "char-preview";367
for (const layer of layers ?? [])368
{369
const url = resolveSpriteUrl?.(layer.sprite);370
if (!url)371
{ continue; }372
const img = document.createElement("img");373
img.src = url;374
img.alt = "";375
wrap.append(img);376
}377
return wrap;378
}379
380
function pickTarget (destination, label)381
{382
if (!sendState)383
{ return; }384
sendState.destination = destination;385
document.getElementById("send-target-label").textContent = `Target: ${label}`;386
document.getElementById("send-confirm").disabled = false;387
sendTargetPanel.hidden = true;388
}389
390
function confirmSend ()391
{392
if (!sendState?.destination)393
{ return; }394
const quantity = Math.max(1, Math.min(sendState.maxQty, Number(document.getElementById("send-qty").value) | 0));395
socket.send({396
type: MessageType.sendPigeon,397
destination: sendState.destination,398
cargo: {399
kind: "item",400
slotIndex: sendState.slotIndex,401
quantity402
}403
});404
document.getElementById("send-status").textContent = "Pigeon dispatched…";405
}406
407
function openLetter ({ mode, slotIndex, instance })408
{409
letterState = { mode, slotIndex, readOnly: mode === "read", instance: instance ?? null };410
letterTitle.textContent = mode === "write" ? "Write letter" : mode === "edit" ? "Edit letter" : "Letter";411
letterBody.value = instance?.body ?? "";412
letterBody.readOnly = letterState.readOnly;413
letterBody.maxLength = LETTER_MAX_BODY_CHARS;414
letterSave.hidden = letterState.readOnly;415
letterStatus.textContent = "";416
refreshLetterSignature();417
letterPanel.hidden = false;418
letterBackdrop.hidden = false;419
fitLetterBody();420
}421
422
function fitLetterBody ()423
{424
letterBody.style.height = "auto";425
letterBody.style.height = `${Math.max(letterBody.scrollHeight, 128)}px`;426
}427
428
function refreshLetterSignature ()429
{430
const name = letterState?.instance?.authorDisplayName431
|| getLocalName?.()432
|| "Unknown";433
letterSignature.textContent = `Signed:\n${name}`;434
}435
436
function closeLetter ()437
{438
letterState = null;439
letterPanel.hidden = true;440
letterBackdrop.hidden = true;441
}442
148
function renderVault (grid, slots)443
function renderVault (grid, slots)149
{444
{150
grid.innerHTML = "";445
grid.innerHTML = "";@@ -177,12 +472,54 @@ export function initInventory ({ socket, MessageType, game })177
return {472
return {178
isOpen ()473
isOpen ()179
{474
{180
return !bagPanel.hidden || bankOpen;475
return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden;476
},477
isBlocking ()478
{479
// Send/letter dialogs cover the view — keep world clicks blocked.480
if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden)481
{ return true; }482
if (sendBackdrop && !sendBackdrop.hidden)483
{ return true; }484
if (letterBackdrop && !letterBackdrop.hidden)485
{ return true; }486
const x = GameInput.mousePosition.x;487
const y = GameInput.mousePosition.y;488
for (const element of [bagPanel, bankPanel])489
{490
if (!element || element.hidden)491
{ continue; }492
const box = element.getBoundingClientRect();493
if (x >= box.left && x < box.right && y >= box.top && y < box.bottom)494
{ return true; }495
}496
return false;497
},498
setLocalCharacterId (characterId)499
{500
localCharacterId = characterId;181
},501
},182
handleInventory (message)502
handleInventory (message)183
{503
{184
bag = { ...bag, ...message };504
bag = { ...bag, ...message };185
render();505
render();506
if (letterState && letterStatus.textContent === "Saving…")507
{508
letterStatus.textContent = "Saved.";509
if (letterState.mode === "write")510
{ closeLetter(); }511
else if (letterState.mode === "edit")512
{513
const slot = bag.inventory?.[letterState.slotIndex];514
if (slot?.instance)515
{516
letterState.instance = slot.instance;517
letterBody.value = slot.instance.body ?? "";518
refreshLetterSignature();519
fitLetterBody();520
}521
}522
}186
},523
},187
handleBank (message)524
handleBank (message)188
{525
{@@ -206,21 +543,28 @@ export function initInventory ({ socket, MessageType, game })206
{ return; }543
{ return; }207
socket.send({ type: MessageType.bankDeposit, slotIndex: selected });544
socket.send({ type: MessageType.bankDeposit, slotIndex: selected });208
},545
},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 ()546
handlePigeonDispatched ()217
{547
{218
setPigeonStatus("Pigeon is in flight.");548
document.getElementById("send-status").textContent = "Pigeon is in flight.";549
closeSend();219
},550
},220
handlePigeonDelivered (message)551
handlePigeonDelivered (message)221
{552
{222
const kind = message.destinationKind === "bank" ? "bank vault" : "recipient";553
const kind = message.destinationKind === "bank" ? "bank vault" : "recipient";223
setPigeonStatus(`Pigeon delivered to ${kind}.`);554
hint.textContent = `Pigeon delivered to ${kind}.`;555
},556
handleCharacterSearch (message)557
{558
if (!pendingSearch)559
{ return; }560
pendingSearch = false;561
sendSearchResult.replaceChildren();562
if (!message.character)563
{564
sendSearchResult.textContent = "No character with that name.";565
return;566
}567
sendSearchResult.append(characterTargetRow(message.character));224
},568
},225
reset ()569
reset ()226
{570
{@@ -228,7 +572,8 @@ export function initInventory ({ socket, MessageType, game })228
bankPanel.hidden = true;572
bankPanel.hidden = true;229
bankOpen = false;573
bankOpen = false;230
selected = null;574
selected = null;231
setPigeonStatus("");575
closeSend();576
closeLetter();232
}577
}233
};578
};234
}579
}@@ -63,7 +63,7 @@ function renderCharacters (characters)
63
63
64
64
function uiBlocked ()
65
65
{
66
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isOpen() || contextMenu?.isOpen());
66
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || contextMenu?.isOpen());
67
67
}
68
68
69
69
function handleLeftClick (mouseX, mouseY)
@@ -241,15 +241,28 @@ async function main ()
241
241
await preloadCatalogImages(game, catalog);
242
242
applySpriteSheets(game.images, catalog);
243
243
social = initSocial({
244
socket: { send (payload) { socket.send(payload); } },
245
MessageType
246
});
247
contextMenu = initContextMenu();
248
inventory = initInventory({
244
249
socket: { send (payload) { socket.send(payload); } },
245
250
MessageType,
246
onPickPigeonRecipient (firstName, lastName)
251
contextMenu,
252
resolveSpriteUrl (name)
253
{
254
return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
255
},
256
getFriends ()
247
257
{
248
inventory?.fillPigeonRecipient(firstName, lastName);
258
return social?.getFriends?.() ?? [];
259
},
260
getLocalName ()
261
{
262
const you = document.getElementById("you")?.textContent ?? "";
263
return you.split("(")[0].trim() || "Unknown";
249
264
}
250
265
});
251
inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });
252
contextMenu = initContextMenu();
253
266
document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
254
267
chat = initChat({
255
268
socket: { send (payload) { socket.send(payload); } },
@@ -274,6 +287,7 @@ async function main ()
274
287
break;
275
288
case MessageType.enterWorld:
276
289
startPlay(message);
290
inventory?.setLocalCharacterId(message.characterId);
277
291
break;
278
292
case MessageType.chunkSnapshot:
279
293
view?.applySnapshot(message);
@@ -316,6 +330,9 @@ async function main ()
316
330
case MessageType.pigeonDelivered:
317
331
inventory?.handlePigeonDelivered(message);
318
332
break;
333
case MessageType.characterSearchResult:
334
inventory?.handleCharacterSearch(message);
335
break;
319
336
case MessageType.worldStatus:
320
337
if (view)
321
338
{
@@ -346,11 +363,35 @@ async function main ()
346
363
showError(message.message);
347
364
social?.showError(message.message);
348
365
break;
366
case MessageType.forceLogout:
367
returnToMenu(message.reason);
368
break;
349
369
}
350
370
});
351
371
await socket.connect();
352
372
}
353
373
374
function returnToMenu (reason = "")
375
{
376
playing = false;
377
social?.reset();
378
chat?.reset();
379
inventory?.reset();
380
contextMenu?.hide();
381
if (view)
382
{
383
for (const key of [...(view.chunks?.keys?.() ?? [])])
384
{
385
const [chunkX, chunkY] = key.split(",").map(Number);
386
view.removeChunk(chunkX, chunkY);
387
}
388
}
389
overlay.hidden = false;
390
hud.hidden = true;
391
if (reason)
392
{ statusEl.textContent = reason; }
393
}
394
354
395
document.getElementById("create-form").addEventListener("submit", (event) =>
355
396
{
356
397
event.preventDefault();
@@ -366,13 +407,7 @@ document.getElementById("create-form").addEventListener("submit", (event) =>
366
407
document.getElementById("leave").addEventListener("click", () =>
367
408
{
368
409
socket.send({ type: MessageType.leaveWorld });
369
playing = false;
370
social?.reset();
371
chat?.reset();
372
inventory?.reset();
373
contextMenu?.hide();
374
overlay.hidden = false;
375
hud.hidden = true;
410
returnToMenu();
376
411
});
377
412
378
413
main().catch((error) =>
@@ -63,7 +63,7 @@ function renderCharacters (characters)63
63
64
function uiBlocked ()64
function uiBlocked ()65
{65
{66
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isOpen() || contextMenu?.isOpen());66
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || contextMenu?.isOpen());67
}67
}68
68
69
function handleLeftClick (mouseX, mouseY)69
function handleLeftClick (mouseX, mouseY)@@ -241,15 +241,28 @@ async function main ()241
await preloadCatalogImages(game, catalog);241
await preloadCatalogImages(game, catalog);242
applySpriteSheets(game.images, catalog);242
applySpriteSheets(game.images, catalog);243
social = initSocial({243
social = initSocial({244
socket: { send (payload) { socket.send(payload); } },245
MessageType246
});247
contextMenu = initContextMenu();248
inventory = initInventory({244
socket: { send (payload) { socket.send(payload); } },249
socket: { send (payload) { socket.send(payload); } },245
MessageType,250
MessageType,246
onPickPigeonRecipient (firstName, lastName)251
contextMenu,252
resolveSpriteUrl (name)253
{254
return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;255
},256
getFriends ()247
{257
{248
inventory?.fillPigeonRecipient(firstName, lastName);258
return social?.getFriends?.() ?? [];259
},260
getLocalName ()261
{262
const you = document.getElementById("you")?.textContent ?? "";263
return you.split("(")[0].trim() || "Unknown";249
}264
}250
});265
});251
inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });252
contextMenu = initContextMenu();253
document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());266
document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());254
chat = initChat({267
chat = initChat({255
socket: { send (payload) { socket.send(payload); } },268
socket: { send (payload) { socket.send(payload); } },@@ -274,6 +287,7 @@ async function main ()274
break;287
break;275
case MessageType.enterWorld:288
case MessageType.enterWorld:276
startPlay(message);289
startPlay(message);290
inventory?.setLocalCharacterId(message.characterId);277
break;291
break;278
case MessageType.chunkSnapshot:292
case MessageType.chunkSnapshot:279
view?.applySnapshot(message);293
view?.applySnapshot(message);@@ -316,6 +330,9 @@ async function main ()316
case MessageType.pigeonDelivered:330
case MessageType.pigeonDelivered:317
inventory?.handlePigeonDelivered(message);331
inventory?.handlePigeonDelivered(message);318
break;332
break;333
case MessageType.characterSearchResult:334
inventory?.handleCharacterSearch(message);335
break;319
case MessageType.worldStatus:336
case MessageType.worldStatus:320
if (view)337
if (view)321
{338
{@@ -346,11 +363,35 @@ async function main ()346
showError(message.message);363
showError(message.message);347
social?.showError(message.message);364
social?.showError(message.message);348
break;365
break;366
case MessageType.forceLogout:367
returnToMenu(message.reason);368
break;349
}369
}350
});370
});351
await socket.connect();371
await socket.connect();352
}372
}353
373
374
function returnToMenu (reason = "")375
{376
playing = false;377
social?.reset();378
chat?.reset();379
inventory?.reset();380
contextMenu?.hide();381
if (view)382
{383
for (const key of [...(view.chunks?.keys?.() ?? [])])384
{385
const [chunkX, chunkY] = key.split(",").map(Number);386
view.removeChunk(chunkX, chunkY);387
}388
}389
overlay.hidden = false;390
hud.hidden = true;391
if (reason)392
{ statusEl.textContent = reason; }393
}394
354
document.getElementById("create-form").addEventListener("submit", (event) =>395
document.getElementById("create-form").addEventListener("submit", (event) =>355
{396
{356
event.preventDefault();397
event.preventDefault();@@ -366,13 +407,7 @@ document.getElementById("create-form").addEventListener("submit", (event) =>366
document.getElementById("leave").addEventListener("click", () =>407
document.getElementById("leave").addEventListener("click", () =>367
{408
{368
socket.send({ type: MessageType.leaveWorld });409
socket.send({ type: MessageType.leaveWorld });369
playing = false;410
returnToMenu();370
social?.reset();371
chat?.reset();372
inventory?.reset();373
contextMenu?.hide();374
overlay.hidden = false;375
hud.hidden = true;376
});411
});377
412
378
main().catch((error) =>413
main().catch((error) =>@@ -1,4 +1,4 @@
1
export function initSocial ({ socket, MessageType, onPickPigeonRecipient })
1
export function initSocial ({ socket, MessageType })
2
2
{
3
3
const nametag = document.getElementById("nametag");
4
4
const inspect = document.getElementById("inspect-modal");
@@ -95,10 +95,6 @@ export function initSocial ({ socket, MessageType, onPickPigeonRecipient })
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
}));
102
98
row.append(actionButton("Remove", () =>
103
99
{
104
100
socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });
@@ -160,6 +156,10 @@ export function initSocial ({ socket, MessageType, onPickPigeonRecipient })
160
156
if (open)
161
157
{ renderInspect(); }
162
158
},
159
getFriends ()
160
{
161
return social.friends ?? [];
162
},
163
163
inspect (entity)
164
164
{
165
165
if (!entity?.characterId)
@@ -1,4 +1,4 @@1
export function initSocial ({ socket, MessageType, onPickPigeonRecipient })1
export function initSocial ({ socket, MessageType })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,10 +95,6 @@ export function initSocial ({ socket, MessageType, onPickPigeonRecipient })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
}));102
row.append(actionButton("Remove", () =>98
row.append(actionButton("Remove", () =>103
{99
{104
socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });100
socket.send({ type: MessageType.friendRemove, characterId: entry.characterId });@@ -160,6 +156,10 @@ export function initSocial ({ socket, MessageType, onPickPigeonRecipient })160
if (open)156
if (open)161
{ renderInspect(); }157
{ renderInspect(); }162
},158
},159
getFriends ()160
{161
return social.friends ?? [];162
},163
inspect (entity)163
inspect (entity)164
{164
{165
if (!entity?.characterId)165
if (!entity?.characterId)@@ -16,6 +16,27 @@ const SORT_ENTITY = 3;
16
16
const SORT_SPRITE_SHADE = 4;
17
17
const RENDER_LAYER_BLOOM = "bloom";
18
18
19
const SPRITE_SHADE_FRAG = [
20
"precision mediump float;",
21
"varying vec2 v_texCoord;",
22
"uniform sampler2D u_texture;",
23
"uniform float u_alpha;",
24
"void main() {",
25
" vec4 color = texture2D(u_texture, v_texCoord);",
26
" if (color.a <= 0.0) { discard; }",
27
" gl_FragColor = vec4(0.0, 0.0, 0.0, color.a * u_alpha);",
28
"}"
29
].join("\n");
30
31
let spriteShadeShader = null;
32
33
function getSpriteShadeShader ()
34
{
35
if (!spriteShadeShader)
36
{ spriteShadeShader = Shader.fragment(SPRITE_SHADE_FRAG); }
37
return spriteShadeShader;
38
}
39
19
40
export class WorldView
20
41
{
21
42
constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -160,6 +181,8 @@ export class WorldView
160
181
{ return; }
161
182
existing.object?.destroy();
162
183
existing.spriteShade?.destroy();
184
for (const shade of existing.overlayShades ?? [])
185
{ shade.destroy(); }
163
186
for (const overlay of existing.overlays ?? [])
164
187
{ overlay.destroy(); }
165
188
for (const overlay of existing.bloomOverlays ?? [])
@@ -539,6 +562,19 @@ export class WorldView
539
562
for (const overlay of entity.bloomOverlays ?? [])
540
563
{ this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
541
564
entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);
565
const nextOverlayShades = [];
566
for (let index = 0; index < (entity.overlays ?? []).length; index++)
567
{
568
nextOverlayShades.push(this.#placeSpriteShade(
569
entity.overlayShades?.[index] ?? null,
570
entity.overlays[index],
571
entity.visualX,
572
entity.visualY + 0.001
573
));
574
}
575
for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
576
{ entity.overlayShades[index]?.destroy(); }
577
entity.overlayShades = nextOverlayShades;
542
578
}
543
579
544
580
#rebuildChunk (snapshot)
@@ -756,19 +792,27 @@ export class WorldView
756
792
existing?.destroy();
757
793
return null;
758
794
}
759
const shade = this.#ensureSprite(existing, "night-shade", SORT_SPRITE_SHADE);
760
if (!shade)
761
{ return null; }
762
795
const sprite = targetObject.renderer.sprite;
796
if (!existing || existing.renderer.sprite !== sprite)
797
{
798
existing?.destroy();
799
existing = new GameObject(0, 0, sprite, SORT_SPRITE_SHADE);
800
this.scene.addObject(existing);
801
}
802
existing.renderer.sprite = sprite;
803
existing.renderer.shader = getSpriteShadeShader();
804
existing.renderer.subImage = targetObject.renderer.subImage || 0;
805
existing.renderer.mirrorX = !!targetObject.renderer.mirrorX;
806
existing.renderer.mirrorY = !!targetObject.renderer.mirrorY;
763
807
const zoom = this.zoom;
764
808
const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
765
809
const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
766
shade.transform.position.x = center.x;
767
shade.transform.position.y = center.y;
768
shade.transform.size = new vector(draw.w, draw.h);
769
shade.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);
810
existing.transform.position.x = center.x;
811
existing.transform.position.y = center.y;
812
existing.transform.size = new vector(draw.w, draw.h);
813
existing.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);
770
814
this.#markSortDirty();
771
return shade;
815
return existing;
772
816
}
773
817
774
818
#tileFill (existing, name, x, y, layer)
@@ -946,10 +990,14 @@ export class WorldView
946
990
}
947
991
for (const entity of this.entities.values())
948
992
{
949
if (!entity.spriteShade)
950
{ continue; }
951
const tile = this.tiles.get(`${entity.tileX},${entity.tileY}`);
952
entity.spriteShade.renderer.alpha = tile?.shadeAlpha ?? 0;
993
const alpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
994
if (entity.spriteShade)
995
{ entity.spriteShade.renderer.alpha = alpha; }
996
for (const shade of entity.overlayShades ?? [])
997
{
998
if (shade)
999
{ shade.renderer.alpha = alpha; }
1000
}
953
1001
}
954
1002
}
955
1003
@@ -16,6 +16,27 @@ const SORT_ENTITY = 3;16
const SORT_SPRITE_SHADE = 4;16
const SORT_SPRITE_SHADE = 4;17
const RENDER_LAYER_BLOOM = "bloom";17
const RENDER_LAYER_BLOOM = "bloom";18
18
19
const SPRITE_SHADE_FRAG = [20
"precision mediump float;",21
"varying vec2 v_texCoord;",22
"uniform sampler2D u_texture;",23
"uniform float u_alpha;",24
"void main() {",25
" vec4 color = texture2D(u_texture, v_texCoord);",26
" if (color.a <= 0.0) { discard; }",27
" gl_FragColor = vec4(0.0, 0.0, 0.0, color.a * u_alpha);",28
"}"29
].join("\n");30
31
let spriteShadeShader = null;32
33
function getSpriteShadeShader ()34
{35
if (!spriteShadeShader)36
{ spriteShadeShader = Shader.fragment(SPRITE_SHADE_FRAG); }37
return spriteShadeShader;38
}39
19
export class WorldView40
export class WorldView20
{41
{21
constructor (game, scene, catalog = { grounds: {}, blocks: {} })42
constructor (game, scene, catalog = { grounds: {}, blocks: {} })@@ -160,6 +181,8 @@ export class WorldView160
{ return; }181
{ return; }161
existing.object?.destroy();182
existing.object?.destroy();162
existing.spriteShade?.destroy();183
existing.spriteShade?.destroy();184
for (const shade of existing.overlayShades ?? [])185
{ shade.destroy(); }163
for (const overlay of existing.overlays ?? [])186
for (const overlay of existing.overlays ?? [])164
{ overlay.destroy(); }187
{ overlay.destroy(); }165
for (const overlay of existing.bloomOverlays ?? [])188
for (const overlay of existing.bloomOverlays ?? [])@@ -539,6 +562,19 @@ export class WorldView539
for (const overlay of entity.bloomOverlays ?? [])562
for (const overlay of entity.bloomOverlays ?? [])540
{ this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }563
{ this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }541
entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);564
entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);565
const nextOverlayShades = [];566
for (let index = 0; index < (entity.overlays ?? []).length; index++)567
{568
nextOverlayShades.push(this.#placeSpriteShade(569
entity.overlayShades?.[index] ?? null,570
entity.overlays[index],571
entity.visualX,572
entity.visualY + 0.001573
));574
}575
for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)576
{ entity.overlayShades[index]?.destroy(); }577
entity.overlayShades = nextOverlayShades;542
}578
}543
579
544
#rebuildChunk (snapshot)580
#rebuildChunk (snapshot)@@ -756,19 +792,27 @@ export class WorldView756
existing?.destroy();792
existing?.destroy();757
return null;793
return null;758
}794
}759
const shade = this.#ensureSprite(existing, "night-shade", SORT_SPRITE_SHADE);760
if (!shade)761
{ return null; }762
const sprite = targetObject.renderer.sprite;795
const sprite = targetObject.renderer.sprite;796
if (!existing || existing.renderer.sprite !== sprite)797
{798
existing?.destroy();799
existing = new GameObject(0, 0, sprite, SORT_SPRITE_SHADE);800
this.scene.addObject(existing);801
}802
existing.renderer.sprite = sprite;803
existing.renderer.shader = getSpriteShadeShader();804
existing.renderer.subImage = targetObject.renderer.subImage || 0;805
existing.renderer.mirrorX = !!targetObject.renderer.mirrorX;806
existing.renderer.mirrorY = !!targetObject.renderer.mirrorY;763
const zoom = this.zoom;807
const zoom = this.zoom;764
const draw = spriteDrawSize(sprite.width, sprite.height, zoom);808
const draw = spriteDrawSize(sprite.width, sprite.height, zoom);765
const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);809
const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);766
shade.transform.position.x = center.x;810
existing.transform.position.x = center.x;767
shade.transform.position.y = center.y;811
existing.transform.position.y = center.y;768
shade.transform.size = new vector(draw.w, draw.h);812
existing.transform.size = new vector(draw.w, draw.h);769
shade.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);813
existing.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);770
this.#markSortDirty();814
this.#markSortDirty();771
return shade;815
return existing;772
}816
}773
817
774
#tileFill (existing, name, x, y, layer)818
#tileFill (existing, name, x, y, layer)@@ -946,10 +990,14 @@ export class WorldView946
}990
}947
for (const entity of this.entities.values())991
for (const entity of this.entities.values())948
{992
{949
if (!entity.spriteShade)993
const alpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;950
{ continue; }994
if (entity.spriteShade)951
const tile = this.tiles.get(`${entity.tileX},${entity.tileY}`);995
{ entity.spriteShade.renderer.alpha = alpha; }952
entity.spriteShade.renderer.alpha = tile?.shadeAlpha ?? 0;996
for (const shade of entity.overlayShades ?? [])997
{998
if (shade)999
{ shade.renderer.alpha = alpha; }1000
}953
}1001
}954
}1002
}955
1003
@@ -222,16 +222,162 @@ a { color: #d4c48a; }
222
222
gap: 0.35rem;
223
223
}
224
224
225
.pigeon-row {
225
.modal-backdrop {
226
position: fixed;
227
inset: 0;
228
z-index: 5;
229
background: rgba(8, 10, 14, 0.55);
230
}
231
232
#send-panel,
233
#send-target-panel,
234
#letter-panel {
235
position: fixed;
236
z-index: 6;
237
top: 50%;
238
left: 50%;
239
transform: translate(-50%, -50%);
240
width: min(380px, 92vw);
241
max-height: min(80vh, 640px);
242
overflow: auto;
243
background: #1a1e26;
244
border: 1px solid #2c3340;
245
padding: 0.85rem 1rem 1rem;
246
}
247
248
#send-target-panel {
249
z-index: 7;
250
}
251
252
#send-panel header,
253
#send-target-panel header,
254
#letter-panel header {
255
display: flex;
256
justify-content: space-between;
257
align-items: center;
258
gap: 0.5rem;
259
margin-bottom: 0.5rem;
260
}
261
262
#send-panel[hidden],
263
#send-target-panel[hidden],
264
#letter-panel[hidden],
265
.modal-backdrop[hidden] {
266
display: none !important;
267
}
268
269
.send-item {
270
display: flex;
271
align-items: center;
272
gap: 0.75rem;
273
margin: 0.5rem 0;
274
}
275
276
.send-item img {
277
width: 48px;
278
height: 48px;
279
object-fit: contain;
280
image-rendering: pixelated;
281
}
282
283
.send-row {
226
284
display: flex;
227
285
flex-direction: column;
228
gap: 0.2rem;
229
margin: 0.35rem 0;
230
font-size: 0.85rem;
286
gap: 0.25rem;
287
margin: 0.5rem 0;
288
font-size: 0.9rem;
231
289
}
232
290
233
.pigeon-row input {
234
padding: 0.25rem 0.4rem;
291
.send-target-row {
292
display: flex;
293
align-items: center;
294
gap: 0.65rem;
295
width: 100%;
296
text-align: left;
297
margin: 0.3rem 0;
298
}
299
300
.send-target-text {
301
display: flex;
302
flex-direction: column;
303
gap: 0.1rem;
304
}
305
306
.send-search {
307
display: flex;
308
flex-wrap: wrap;
309
gap: 0.35rem;
310
margin-top: 0.75rem;
311
}
312
313
.send-search input {
314
flex: 1 1 6rem;
315
}
316
317
.char-preview {
318
position: relative;
319
width: 36px;
320
height: 48px;
321
flex: 0 0 auto;
322
image-rendering: pixelated;
323
background: #101216;
324
border: 1px solid #2c3340;
325
}
326
327
.char-preview img {
328
position: absolute;
329
inset: 0;
330
width: 100%;
331
height: 100%;
332
object-fit: contain;
333
image-rendering: pixelated;
334
}
335
336
#letter-body {
337
display: block;
338
width: 100%;
339
box-sizing: border-box;
340
margin: 0;
341
padding: 0;
342
border: none;
343
outline: none;
344
resize: none;
345
overflow: hidden;
346
background: transparent;
347
color: inherit;
348
font: inherit;
349
line-height: 1.45;
350
min-height: 8rem;
351
field-sizing: content;
352
}
353
354
.letter-paper {
355
background: #f4f0e4;
356
color: #1c1814;
357
padding: 1.25rem 1.35rem;
358
margin: 0.35rem 0 0.75rem;
359
max-height: min(55vh, 420px);
360
overflow-y: auto;
361
scrollbar-width: none;
362
-ms-overflow-style: none;
363
box-shadow: inset 0 0 0 1px rgba(40, 32, 24, 0.08);
364
}
365
366
.letter-paper::-webkit-scrollbar {
367
display: none;
368
width: 0;
369
height: 0;
370
}
371
372
.letter-signature {
373
margin: 1.35rem 0 0;
374
padding: 0;
375
border: none;
376
background: transparent;
377
white-space: pre-wrap;
378
font: inherit;
379
color: inherit;
380
line-height: 1.45;
235
381
}
236
382
237
383
#friends-panel h2, #friends-panel h3 {
@@ -222,16 +222,162 @@ a { color: #d4c48a; }222
gap: 0.35rem;222
gap: 0.35rem;223
}223
}224
224
225
.pigeon-row {225
.modal-backdrop {226
position: fixed;227
inset: 0;228
z-index: 5;229
background: rgba(8, 10, 14, 0.55);230
}231
232
#send-panel,233
#send-target-panel,234
#letter-panel {235
position: fixed;236
z-index: 6;237
top: 50%;238
left: 50%;239
transform: translate(-50%, -50%);240
width: min(380px, 92vw);241
max-height: min(80vh, 640px);242
overflow: auto;243
background: #1a1e26;244
border: 1px solid #2c3340;245
padding: 0.85rem 1rem 1rem;246
}247
248
#send-target-panel {249
z-index: 7;250
}251
252
#send-panel header,253
#send-target-panel header,254
#letter-panel header {255
display: flex;256
justify-content: space-between;257
align-items: center;258
gap: 0.5rem;259
margin-bottom: 0.5rem;260
}261
262
#send-panel[hidden],263
#send-target-panel[hidden],264
#letter-panel[hidden],265
.modal-backdrop[hidden] {266
display: none !important;267
}268
269
.send-item {270
display: flex;271
align-items: center;272
gap: 0.75rem;273
margin: 0.5rem 0;274
}275
276
.send-item img {277
width: 48px;278
height: 48px;279
object-fit: contain;280
image-rendering: pixelated;281
}282
283
.send-row {226
display: flex;284
display: flex;227
flex-direction: column;285
flex-direction: column;228
gap: 0.2rem;286
gap: 0.25rem;229
margin: 0.35rem 0;287
margin: 0.5rem 0;230
font-size: 0.85rem;288
font-size: 0.9rem;231
}289
}232
290
233
.pigeon-row input {291
.send-target-row {234
padding: 0.25rem 0.4rem;292
display: flex;293
align-items: center;294
gap: 0.65rem;295
width: 100%;296
text-align: left;297
margin: 0.3rem 0;298
}299
300
.send-target-text {301
display: flex;302
flex-direction: column;303
gap: 0.1rem;304
}305
306
.send-search {307
display: flex;308
flex-wrap: wrap;309
gap: 0.35rem;310
margin-top: 0.75rem;311
}312
313
.send-search input {314
flex: 1 1 6rem;315
}316
317
.char-preview {318
position: relative;319
width: 36px;320
height: 48px;321
flex: 0 0 auto;322
image-rendering: pixelated;323
background: #101216;324
border: 1px solid #2c3340;325
}326
327
.char-preview img {328
position: absolute;329
inset: 0;330
width: 100%;331
height: 100%;332
object-fit: contain;333
image-rendering: pixelated;334
}335
336
#letter-body {337
display: block;338
width: 100%;339
box-sizing: border-box;340
margin: 0;341
padding: 0;342
border: none;343
outline: none;344
resize: none;345
overflow: hidden;346
background: transparent;347
color: inherit;348
font: inherit;349
line-height: 1.45;350
min-height: 8rem;351
field-sizing: content;352
}353
354
.letter-paper {355
background: #f4f0e4;356
color: #1c1814;357
padding: 1.25rem 1.35rem;358
margin: 0.35rem 0 0.75rem;359
max-height: min(55vh, 420px);360
overflow-y: auto;361
scrollbar-width: none;362
-ms-overflow-style: none;363
box-shadow: inset 0 0 0 1px rgba(40, 32, 24, 0.08);364
}365
366
.letter-paper::-webkit-scrollbar {367
display: none;368
width: 0;369
height: 0;370
}371
372
.letter-signature {373
margin: 1.35rem 0 0;374
padding: 0;375
border: none;376
background: transparent;377
white-space: pre-wrap;378
font: inherit;379
color: inherit;380
line-height: 1.45;235
}381
}236
382
237
#friends-panel h2, #friends-panel h3 {383
#friends-panel h2, #friends-panel h3 {@@ -190,7 +190,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
190
190
## Inventory, items, equipment, ground drops
191
191
192
192
**Status:** full
193
**Spec:** 32-slot inventory, stacking, equipment slots with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists.
193
**Spec:** 32-slot inventory, stacking, equipment slots with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists. Right-click bag items for Send / Equip / Drop; paper can be written into unique **letter** instances (signed on Save; only the signer may edit).
194
194
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
195
195
196
196
## Combat, skills, groups, pigeons
@@ -190,7 +190,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi190
## Inventory, items, equipment, ground drops190
## Inventory, items, equipment, ground drops191
191
192
**Status:** full 192
**Status:** full 193
**Spec:** 32-slot inventory, stacking, equipment slots with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists. 193
**Spec:** 32-slot inventory, stacking, equipment slots with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists. Right-click bag items for Send / Equip / Drop; paper can be written into unique **letter** instances (signed on Save; only the signer may edit). 194
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`194
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`195
195
196
## Combat, skills, groups, pigeons196
## Combat, skills, groups, pigeons@@ -48,6 +48,9 @@ function itemScanDefs ()
48
48
const defs = {};
49
49
for (const def of Object.values(ITEM_DEFINITIONS))
50
50
{
51
// Items that reuse another folder's art via iconKey skip the scan.
52
if (def.iconKey && def.iconKey !== def.key)
53
{ continue; }
51
54
defs[def.key] = {
52
55
key: def.key,
53
56
id: def.itemId,
@@ -48,6 +48,9 @@ function itemScanDefs ()48
const defs = {};48
const defs = {};49
for (const def of Object.values(ITEM_DEFINITIONS))49
for (const def of Object.values(ITEM_DEFINITIONS))50
{50
{51
// Items that reuse another folder's art via iconKey skip the scan.52
if (def.iconKey && def.iconKey !== def.key)53
{ continue; }51
defs[def.key] = {54
defs[def.key] = {52
key: def.key,55
key: def.key,53
id: def.itemId,56
id: def.itemId,@@ -21,13 +21,14 @@ export function broadcastSpeech (sessions, simulation, speakerSession, rawText)
21
21
if (!other.entityId)
22
22
{ continue; }
23
23
let readable = text;
24
let readability = 1;
24
25
if (other !== speakerSession)
25
26
{
26
27
const listenerPos = simulation.positionOf(other.entityId);
27
28
if (!listenerPos)
28
29
{ continue; }
29
30
const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);
30
const readability = speechReadability(distance, CHUNK_SIZE);
31
readability = speechReadability(distance, CHUNK_SIZE);
31
32
if (readability <= 0)
32
33
{ continue; }
33
34
readable = obscureSpeech(text, readability, messageId ^ other.id);
@@ -42,6 +43,7 @@ export function broadcastSpeech (sessions, simulation, speakerSession, rawText)
42
43
entityId: speakerSession.entityId,
43
44
characterId: speakerSession.characterId,
44
45
text: readable,
46
readability,
45
47
createdAt
46
48
}));
47
49
}
@@ -21,13 +21,14 @@ export function broadcastSpeech (sessions, simulation, speakerSession, rawText)21
if (!other.entityId)21
if (!other.entityId)22
{ continue; }22
{ continue; }23
let readable = text;23
let readable = text;24
let readability = 1;24
if (other !== speakerSession)25
if (other !== speakerSession)25
{26
{26
const listenerPos = simulation.positionOf(other.entityId);27
const listenerPos = simulation.positionOf(other.entityId);27
if (!listenerPos)28
if (!listenerPos)28
{ continue; }29
{ continue; }29
const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);30
const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);30
const readability = speechReadability(distance, CHUNK_SIZE);31
readability = speechReadability(distance, CHUNK_SIZE);31
if (readability <= 0)32
if (readability <= 0)32
{ continue; }33
{ continue; }33
readable = obscureSpeech(text, readability, messageId ^ other.id);34
readable = obscureSpeech(text, readability, messageId ^ other.id);@@ -42,6 +43,7 @@ export function broadcastSpeech (sessions, simulation, speakerSession, rawText)42
entityId: speakerSession.entityId,43
entityId: speakerSession.entityId,43
characterId: speakerSession.characterId,44
characterId: speakerSession.characterId,44
text: readable,45
text: readable,46
readability,45
createdAt47
createdAt46
}));48
}));47
}49
}@@ -1,7 +1,7 @@
1
1
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2
2
import { BlockType } from "../../../shared/definitions/tiles.js";
3
3
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4
import { itemDefinition } from "../../../shared/definitions/items.js";
4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5
5
import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";
6
6
import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7
7
import { GAIT } from "../../../shared/protocol/constants.js";
@@ -95,6 +95,16 @@ export class CourierService
95
95
}
96
96
else if (cargo?.kind === "item")
97
97
{
98
const slot = bag.inventory?.[cargo.slotIndex | 0];
99
if (slot?.itemId === ItemId.letter)
100
{
101
if (Number(slot.instance?.authorCharacterId) !== Number(characterId))
102
{
103
const error = new Error("You can only send letters you wrote.");
104
error.userFacing = true;
105
throw error;
106
}
107
}
98
108
const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);
99
109
if (!taken.ok || !taken.taken)
100
110
{
@@ -103,7 +113,10 @@ export class CourierService
103
113
throw error;
104
114
}
105
115
bag.inventory = taken.slots;
106
takenCargo = { kind: "item", stack: taken.taken };
116
const stack = taken.taken;
117
if (stack.itemId === ItemId.letter && stack.instance)
118
{ stack.instance = { ...stack.instance, opened: false }; }
119
takenCargo = { kind: "item", stack };
107
120
}
108
121
else
109
122
{
@@ -1,7 +1,7 @@1
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";1
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";3
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";4
import { itemDefinition } from "../../../shared/definitions/items.js";4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";5
import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";5
import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";6
import { advanceCourierFlight } from "../../../shared/courier/flight.js";6
import { advanceCourierFlight } from "../../../shared/courier/flight.js";7
import { GAIT } from "../../../shared/protocol/constants.js";7
import { GAIT } from "../../../shared/protocol/constants.js";@@ -95,6 +95,16 @@ export class CourierService95
}95
}96
else if (cargo?.kind === "item")96
else if (cargo?.kind === "item")97
{97
{98
const slot = bag.inventory?.[cargo.slotIndex | 0];99
if (slot?.itemId === ItemId.letter)100
{101
if (Number(slot.instance?.authorCharacterId) !== Number(characterId))102
{103
const error = new Error("You can only send letters you wrote.");104
error.userFacing = true;105
throw error;106
}107
}98
const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);108
const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);99
if (!taken.ok || !taken.taken)109
if (!taken.ok || !taken.taken)100
{110
{@@ -103,7 +113,10 @@ export class CourierService103
throw error;113
throw error;104
}114
}105
bag.inventory = taken.slots;115
bag.inventory = taken.slots;106
takenCargo = { kind: "item", stack: taken.taken };116
const stack = taken.taken;117
if (stack.itemId === ItemId.letter && stack.instance)118
{ stack.instance = { ...stack.instance, opened: false }; }119
takenCargo = { kind: "item", stack };107
}120
}108
else121
else109
{122
{@@ -254,6 +254,42 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
254
254
send(session, { type: MessageType.inventory, ...result.bag });
255
255
}
256
256
break;
257
case MessageType.searchCharacter:
258
requirePlaying(session);
259
{
260
const character = friends.findByFullName(message.firstName, message.lastName);
261
send(session, {
262
type: MessageType.characterSearchResult,
263
character: character ?? null
264
});
265
}
266
break;
267
case MessageType.writeLetter:
268
requirePlaying(session);
269
simulation.enqueue(session.id, {
270
type: "write-letter",
271
characterId: session.characterId,
272
slotIndex: message.slotIndex,
273
body: message.body
274
});
275
break;
276
case MessageType.editLetter:
277
requirePlaying(session);
278
simulation.enqueue(session.id, {
279
type: "edit-letter",
280
characterId: session.characterId,
281
slotIndex: message.slotIndex,
282
body: message.body
283
});
284
break;
285
case MessageType.openLetter:
286
requirePlaying(session);
287
simulation.enqueue(session.id, {
288
type: "open-letter",
289
characterId: session.characterId,
290
slotIndex: message.slotIndex
291
});
292
break;
257
293
case MessageType.editorLoadChunk:
258
294
requireAdmin(session);
259
295
send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
@@ -646,6 +682,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
646
682
{
647
683
for (const session of [...sessions.values()])
648
684
{
685
send(session, {
686
type: MessageType.forceLogout,
687
reason: "Server shutting down."
688
});
649
689
leaveWorld(session);
650
690
try
651
691
{ session.socket.close(1001, "Server shutting down"); }
@@ -254,6 +254,42 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,254
send(session, { type: MessageType.inventory, ...result.bag });254
send(session, { type: MessageType.inventory, ...result.bag });255
}255
}256
break;256
break;257
case MessageType.searchCharacter:258
requirePlaying(session);259
{260
const character = friends.findByFullName(message.firstName, message.lastName);261
send(session, {262
type: MessageType.characterSearchResult,263
character: character ?? null264
});265
}266
break;267
case MessageType.writeLetter:268
requirePlaying(session);269
simulation.enqueue(session.id, {270
type: "write-letter",271
characterId: session.characterId,272
slotIndex: message.slotIndex,273
body: message.body274
});275
break;276
case MessageType.editLetter:277
requirePlaying(session);278
simulation.enqueue(session.id, {279
type: "edit-letter",280
characterId: session.characterId,281
slotIndex: message.slotIndex,282
body: message.body283
});284
break;285
case MessageType.openLetter:286
requirePlaying(session);287
simulation.enqueue(session.id, {288
type: "open-letter",289
characterId: session.characterId,290
slotIndex: message.slotIndex291
});292
break;257
case MessageType.editorLoadChunk:293
case MessageType.editorLoadChunk:258
requireAdmin(session);294
requireAdmin(session);259
send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });295
send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });@@ -646,6 +682,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,646
{682
{647
for (const session of [...sessions.values()])683
for (const session of [...sessions.values()])648
{684
{685
send(session, {686
type: MessageType.forceLogout,687
reason: "Server shutting down."688
});649
leaveWorld(session);689
leaveWorld(session);650
try690
try651
{ session.socket.close(1001, "Server shutting down"); }691
{ session.socket.close(1001, "Server shutting down"); }@@ -1,6 +1,6 @@
1
1
import { Component } from "../ecs/components.js";
2
2
import { BlockType } from "../../../shared/definitions/tiles.js";
3
import { itemDefinition, itemSpriteName } from "../../../shared/definitions/items.js";
3
import { ItemId, itemDefinition, itemSpriteName, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
4
4
import {
5
5
emptyEquipment,
6
6
emptySlots,
@@ -11,6 +11,7 @@ import {
11
11
} from "../../../shared/items/inventory.js";
12
12
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
13
13
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
14
import { randomUUID } from "node:crypto";
14
15
15
16
export function publicGroundItem (item)
16
17
{
@@ -22,7 +23,7 @@ export function publicGroundItem (item)
22
23
itemId: item.stack.itemId,
23
24
quantity: item.stack.quantity,
24
25
displayName: def?.displayName ?? "Item",
25
sprite: itemSpriteName(item.stack.itemId),
26
sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
26
27
expiresAt: item.expiresAt
27
28
};
28
29
}
@@ -79,6 +80,12 @@ export function handleItemCommand (world, sessionId, command, now)
79
80
return bankMoney(world, sessionId, command, "vault", "currency");
80
81
case "claim-inheritance":
81
82
return claimInheritance(world, sessionId, command);
83
case "write-letter":
84
return writeLetter(world, sessionId, command);
85
case "edit-letter":
86
return editLetter(world, sessionId, command);
87
case "open-letter":
88
return openLetter(world, sessionId, command);
82
89
default:
83
90
return null;
84
91
}
@@ -330,6 +337,88 @@ function claimInheritance (world, sessionId, command)
330
337
return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
331
338
}
332
339
340
function writeLetter (world, sessionId, command)
341
{
342
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
343
const inventory = ensureInventory(world.ecs, handle);
344
const slotIndex = command.slotIndex | 0;
345
const slot = inventory.slots[slotIndex];
346
if (!slot || slot.itemId !== ItemId.paper)
347
{ throw userError("Select blank paper."); }
348
const body = normalizeLetterBody(command.body);
349
const appearance = world.ecs.get(handle, Component.appearance);
350
const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim();
351
const letterStack = {
352
itemId: ItemId.letter,
353
quantity: 1,
354
origin: null,
355
instance: {
356
kind: "letter",
357
letterId: randomUUID(),
358
authorCharacterId: command.characterId,
359
authorDisplayName,
360
body,
361
opened: true,
362
writtenAt: Date.now()
363
}
364
};
365
if (slot.quantity <= 1)
366
{
367
inventory.slots[slotIndex] = letterStack;
368
return { events: [], private: bagView(world.ecs, handle) };
369
}
370
const free = inventory.slots.findIndex((entry) => !entry);
371
if (free < 0)
372
{ throw userError("Need a free inventory slot for the letter."); }
373
slot.quantity -= 1;
374
inventory.slots[free] = letterStack;
375
return { events: [], private: bagView(world.ecs, handle) };
376
}
377
378
function editLetter (world, sessionId, command)
379
{
380
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
381
const inventory = ensureInventory(world.ecs, handle);
382
const slotIndex = command.slotIndex | 0;
383
const slot = inventory.slots[slotIndex];
384
if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")
385
{ throw userError("That is not a letter."); }
386
if (slot.instance.authorCharacterId !== command.characterId)
387
{ throw userError("Only the signer can edit this letter."); }
388
const appearance = world.ecs.get(handle, Component.appearance);
389
const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim()
390
|| slot.instance.authorDisplayName;
391
slot.instance = {
392
...slot.instance,
393
authorDisplayName,
394
body: normalizeLetterBody(command.body),
395
writtenAt: Date.now()
396
};
397
return { events: [], private: bagView(world.ecs, handle) };
398
}
399
400
function openLetter (world, sessionId, command)
401
{
402
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
403
const inventory = ensureInventory(world.ecs, handle);
404
const slotIndex = command.slotIndex | 0;
405
const slot = inventory.slots[slotIndex];
406
if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")
407
{ throw userError("That is not a letter."); }
408
if (slot.instance.opened !== false)
409
{ return { events: [], private: bagView(world.ecs, handle) }; }
410
slot.instance = { ...slot.instance, opened: true };
411
return { events: [], private: bagView(world.ecs, handle) };
412
}
413
414
function normalizeLetterBody (raw)
415
{
416
const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd();
417
if (body.length > LETTER_MAX_BODY_CHARS)
418
{ throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); }
419
return body;
420
}
421
333
422
function requireBank (world, handle)
334
423
{
335
424
const position = world.ecs.get(handle, Component.position);
@@ -1,6 +1,6 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { itemDefinition, itemSpriteName } from "../../../shared/definitions/items.js";3
import { ItemId, itemDefinition, itemSpriteName, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";4
import {4
import {5
emptyEquipment,5
emptyEquipment,6
emptySlots,6
emptySlots,@@ -11,6 +11,7 @@ import {11
} from "../../../shared/items/inventory.js";11
} from "../../../shared/items/inventory.js";12
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";12
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";13
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";13
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";14
import { randomUUID } from "node:crypto";14
15
15
export function publicGroundItem (item)16
export function publicGroundItem (item)16
{17
{@@ -22,7 +23,7 @@ export function publicGroundItem (item)22
itemId: item.stack.itemId,23
itemId: item.stack.itemId,23
quantity: item.stack.quantity,24
quantity: item.stack.quantity,24
displayName: def?.displayName ?? "Item",25
displayName: def?.displayName ?? "Item",25
sprite: itemSpriteName(item.stack.itemId),26
sprite: itemSpriteName(item.stack.itemId, item.stack.instance),26
expiresAt: item.expiresAt27
expiresAt: item.expiresAt27
};28
};28
}29
}@@ -79,6 +80,12 @@ export function handleItemCommand (world, sessionId, command, now)79
return bankMoney(world, sessionId, command, "vault", "currency");80
return bankMoney(world, sessionId, command, "vault", "currency");80
case "claim-inheritance":81
case "claim-inheritance":81
return claimInheritance(world, sessionId, command);82
return claimInheritance(world, sessionId, command);83
case "write-letter":84
return writeLetter(world, sessionId, command);85
case "edit-letter":86
return editLetter(world, sessionId, command);87
case "open-letter":88
return openLetter(world, sessionId, command);82
default:89
default:83
return null;90
return null;84
}91
}@@ -330,6 +337,88 @@ function claimInheritance (world, sessionId, command)330
return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };337
return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };331
}338
}332
339
340
function writeLetter (world, sessionId, command)341
{342
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);343
const inventory = ensureInventory(world.ecs, handle);344
const slotIndex = command.slotIndex | 0;345
const slot = inventory.slots[slotIndex];346
if (!slot || slot.itemId !== ItemId.paper)347
{ throw userError("Select blank paper."); }348
const body = normalizeLetterBody(command.body);349
const appearance = world.ecs.get(handle, Component.appearance);350
const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim();351
const letterStack = {352
itemId: ItemId.letter,353
quantity: 1,354
origin: null,355
instance: {356
kind: "letter",357
letterId: randomUUID(),358
authorCharacterId: command.characterId,359
authorDisplayName,360
body,361
opened: true,362
writtenAt: Date.now()363
}364
};365
if (slot.quantity <= 1)366
{367
inventory.slots[slotIndex] = letterStack;368
return { events: [], private: bagView(world.ecs, handle) };369
}370
const free = inventory.slots.findIndex((entry) => !entry);371
if (free < 0)372
{ throw userError("Need a free inventory slot for the letter."); }373
slot.quantity -= 1;374
inventory.slots[free] = letterStack;375
return { events: [], private: bagView(world.ecs, handle) };376
}377
378
function editLetter (world, sessionId, command)379
{380
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);381
const inventory = ensureInventory(world.ecs, handle);382
const slotIndex = command.slotIndex | 0;383
const slot = inventory.slots[slotIndex];384
if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")385
{ throw userError("That is not a letter."); }386
if (slot.instance.authorCharacterId !== command.characterId)387
{ throw userError("Only the signer can edit this letter."); }388
const appearance = world.ecs.get(handle, Component.appearance);389
const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim()390
|| slot.instance.authorDisplayName;391
slot.instance = {392
...slot.instance,393
authorDisplayName,394
body: normalizeLetterBody(command.body),395
writtenAt: Date.now()396
};397
return { events: [], private: bagView(world.ecs, handle) };398
}399
400
function openLetter (world, sessionId, command)401
{402
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);403
const inventory = ensureInventory(world.ecs, handle);404
const slotIndex = command.slotIndex | 0;405
const slot = inventory.slots[slotIndex];406
if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")407
{ throw userError("That is not a letter."); }408
if (slot.instance.opened !== false)409
{ return { events: [], private: bagView(world.ecs, handle) }; }410
slot.instance = { ...slot.instance, opened: true };411
return { events: [], private: bagView(world.ecs, handle) };412
}413
414
function normalizeLetterBody (raw)415
{416
const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd();417
if (body.length > LETTER_MAX_BODY_CHARS)418
{ throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); }419
return body;420
}421
333
function requireBank (world, handle)422
function requireBank (world, handle)334
{423
{335
const position = world.ecs.get(handle, Component.position);424
const position = world.ecs.get(handle, Component.position);@@ -72,15 +72,8 @@ export function stepFollow (world)
72
72
if (world.frozen?.has?.(entity.entityId))
73
73
{ continue; }
74
74
75
const targetHandle = world.ecs.handleOf(targetId);
76
if (targetHandle == null)
77
{
78
follow.targetEntityId = null;
79
follow.trail = [];
80
continue;
81
}
82
const targetPos = world.ecs.get(targetHandle, Component.position);
83
if (!targetPos)
75
const target = resolveFollowTarget(world, targetId);
76
if (!target)
84
77
{
85
78
follow.targetEntityId = null;
86
79
follow.trail = [];
@@ -90,8 +83,8 @@ export function stepFollow (world)
90
83
const dist = chebyshev(
91
84
entity.position.tileX,
92
85
entity.position.tileY,
93
targetPos.tileX,
94
targetPos.tileY
86
target.pos.tileX,
87
target.pos.tileY
95
88
);
96
89
if (dist > FOLLOW_BREAK_TILES)
97
90
{
@@ -101,71 +94,142 @@ export function stepFollow (world)
101
94
continue;
102
95
}
103
96
104
const targetMovement = world.ecs.get(targetHandle, Component.movement);
105
97
if (dist > FOLLOW_ALWAYS_RUN_TILES)
106
98
{ entity.movement.gait = GAIT.run; }
107
99
else if (dist > 1)
108
{ entity.movement.gait = targetMovement?.gait === GAIT.run ? GAIT.run : GAIT.walk; }
100
{ entity.movement.gait = target.gait === GAIT.run ? GAIT.run : GAIT.walk; }
101
102
if (!Array.isArray(follow.trail))
103
{ follow.trail = []; }
104
trimTrailBehindFollower(follow.trail, entity.position);
109
105
110
if (dist <= 1)
106
const targetMoving = (target.pathTiles?.length ?? 0) > 0 || follow.trail.length > 0;
107
// Stay put only when already adjacent and the target is idle — otherwise keep
108
// chasing footsteps (including waiting on the target's current tile).
109
if (dist <= 1 && !targetMoving)
111
110
{
112
111
clearPath(world.ecs, entity.handle);
113
112
continue;
114
113
}
115
114
116
if (!Array.isArray(follow.trail))
117
{ follow.trail = []; }
118
trimTrailBehindFollower(follow.trail, entity.position);
119
120
const targetPath = world.ecs.get(targetHandle, Component.path)?.tiles ?? [];
121
115
const reused = buildFollowPath(
122
116
world,
123
117
entity.entityId,
124
118
entity.position,
125
targetPos,
119
target.pos,
126
120
follow.trail,
127
targetPath
121
target.pathTiles
128
122
);
129
123
130
124
let path = world.ecs.get(entity.handle, Component.path);
131
125
if (!path)
132
126
{ path = world.ecs.add(entity.handle, Component.path, { tiles: [] }); }
133
127
134
if (reused.length)
128
if (reused.waiting)
129
{
130
// Next trail tile is occupied — wait for vacancy instead of detouring.
131
assignFollowPath(entity.movement, path, reused.tiles);
132
continue;
133
}
134
135
if (reused.tiles.length)
135
136
{
136
path.tiles = reused;
137
entity.movement.walkCarry = 0;
137
assignFollowPath(entity.movement, path, reused.tiles);
138
138
continue;
139
139
}
140
140
141
141
// No shared trail/path yet — catch up with a one-shot approach path.
142
queueCatchUp(world, entity.entityId, entity.handle, entity.position, targetPos, path);
142
queueCatchUp(world, entity.entityId, entity.handle, entity.position, target.pos, path);
143
143
}
144
144
}
145
145
146
function resolveFollowTarget (world, targetId)
147
{
148
const targetHandle = world.ecs.handleOf(targetId);
149
if (targetHandle != null)
150
{
151
const pos = world.ecs.get(targetHandle, Component.position);
152
if (!pos)
153
{ return null; }
154
const movement = world.ecs.get(targetHandle, Component.movement);
155
const path = world.ecs.get(targetHandle, Component.path);
156
return {
157
pos,
158
gait: movement?.gait,
159
pathTiles: path?.tiles ?? []
160
};
161
}
162
const ghost = world.ghosts?.get?.(targetId);
163
if (!ghost)
164
{ return null; }
165
return {
166
pos: { tileX: ghost.tileX, tileY: ghost.tileY },
167
gait: ghost.gait,
168
pathTiles: []
169
};
170
}
171
146
172
function buildFollowPath (world, followerId, followerPos, targetPos, trail, targetPathTiles)
147
173
{
148
174
const combined = [];
149
175
for (const tile of trail)
150
176
{ combined.push({ x: tile.x, y: tile.y }); }
177
const lastTrail = combined[combined.length - 1];
178
if (!lastTrail || lastTrail.x !== targetPos.tileX || lastTrail.y !== targetPos.tileY)
179
{ combined.push({ x: targetPos.tileX, y: targetPos.tileY }); }
151
180
for (const tile of targetPathTiles)
152
{ combined.push({ x: tile.x, y: tile.y }); }
181
{
182
const prev = combined[combined.length - 1];
183
if (prev && prev.x === tile.x && prev.y === tile.y)
184
{ continue; }
185
combined.push({ x: tile.x, y: tile.y });
186
}
153
187
154
188
const result = [];
189
let cursorX = followerPos.tileX;
190
let cursorY = followerPos.tileY;
155
191
for (const tile of combined)
156
192
{
157
if (tile.x === targetPos.tileX && tile.y === targetPos.tileY)
158
{ break; }
159
if (tile.x === followerPos.tileX && tile.y === followerPos.tileY)
193
if (tile.x === cursorX && tile.y === cursorY)
160
194
{ continue; }
195
const stepDist = chebyshev(cursorX, cursorY, tile.x, tile.y);
196
if (stepDist > 1)
197
{
198
// Gap between follower and trail — fall through to catch-up.
199
if (!result.length)
200
{ return { tiles: [], waiting: false }; }
201
break;
202
}
161
203
if (!world.walkableFor(followerId, tile.x, tile.y))
162
{ break; }
204
{
205
// Occupied (usually by the follow target) — wait on that footstep.
206
if (!result.length)
207
{ return { tiles: [{ x: tile.x, y: tile.y }], waiting: true }; }
208
break;
209
}
163
210
const prev = result[result.length - 1];
164
211
if (prev && prev.x === tile.x && prev.y === tile.y)
165
212
{ continue; }
166
result.push(tile);
213
result.push({ x: tile.x, y: tile.y });
214
cursorX = tile.x;
215
cursorY = tile.y;
167
216
}
168
return result;
217
return { tiles: result, waiting: false };
218
}
219
220
function assignFollowPath (movement, path, tiles)
221
{
222
const prevNext = path.tiles?.[0];
223
const next = tiles[0];
224
const nextChanged = !next
225
|| !prevNext
226
|| prevNext.x !== next.x
227
|| prevNext.y !== next.y;
228
path.tiles = tiles;
229
// Only reset walk cadence when the immediate step changes; refreshing the
230
// remaining trail every systems tick must not stall walking followers.
231
if (nextChanged)
232
{ movement.walkCarry = 0; }
169
233
}
170
234
171
235
function trimTrailBehindFollower (trail, position)
@@ -184,8 +248,8 @@ function trimTrailBehindFollower (trail, position)
184
248
185
249
function queueCatchUp (world, entityId, handle, position, targetPos, path)
186
250
{
187
const goal = bestAdjacentGoal(world, entityId, position, targetPos);
188
if (!goal)
251
const goal = { x: targetPos.tileX, y: targetPos.tileY };
252
if (position.tileX === goal.x && position.tileY === goal.y)
189
253
{
190
254
path.tiles = [];
191
255
return;
@@ -193,16 +257,24 @@ function queueCatchUp (world, entityId, handle, position, targetPos, path)
193
257
if (path.tiles?.length)
194
258
{
195
259
const last = path.tiles[path.tiles.length - 1];
196
if (last.x === goal.x && last.y === goal.y)
260
const first = path.tiles[0];
261
if (last.x === goal.x && last.y === goal.y
262
&& chebyshev(position.tileX, position.tileY, first.x, first.y) <= 1)
197
263
{ return; }
198
264
}
199
265
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
200
path.tiles = findPath(
266
const nextTiles = findPath(
201
267
position.tileX,
202
268
position.tileY,
203
269
goal.x,
204
270
goal.y,
205
(x, y) => world.walkableFor(entityId, x, y),
271
(x, y) =>
272
{
273
// Plan onto the target tile; movement still waits while they occupy it.
274
if (x === goal.x && y === goal.y)
275
{ return world.isEnterable?.(x, y) ?? world.walkableFor(entityId, x, y); }
276
return world.walkableFor(entityId, x, y);
277
},
206
278
bounds.minX,
207
279
bounds.minY,
208
280
bounds.maxX,
@@ -210,7 +282,9 @@ function queueCatchUp (world, entityId, handle, position, targetPos, path)
210
282
);
211
283
const movement = world.ecs.get(handle, Component.movement);
212
284
if (movement)
213
{ movement.walkCarry = 0; }
285
{ assignFollowPath(movement, path, nextTiles); }
286
else
287
{ path.tiles = nextTiles; }
214
288
}
215
289
216
290
function clearPath (ecs, handle)
@@ -219,29 +293,3 @@ function clearPath (ecs, handle)
219
293
if (path)
220
294
{ path.tiles = []; }
221
295
}
222
223
function bestAdjacentGoal (world, entityId, position, targetPos)
224
{
225
const dirs = [
226
{ x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
227
{ x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
228
];
229
let best = null;
230
let bestDist = Infinity;
231
for (const dir of dirs)
232
{
233
const x = targetPos.tileX + dir.x;
234
const y = targetPos.tileY + dir.y;
235
if (x === position.tileX && y === position.tileY)
236
{ return { x, y }; }
237
if (!world.walkableFor(entityId, x, y))
238
{ continue; }
239
const dist = chebyshev(position.tileX, position.tileY, x, y);
240
if (dist < bestDist)
241
{
242
bestDist = dist;
243
best = { x, y };
244
}
245
}
246
return best;
247
}
@@ -72,15 +72,8 @@ export function stepFollow (world)72
if (world.frozen?.has?.(entity.entityId))72
if (world.frozen?.has?.(entity.entityId))73
{ continue; }73
{ continue; }74
74
75
const targetHandle = world.ecs.handleOf(targetId);75
const target = resolveFollowTarget(world, targetId);76
if (targetHandle == null)76
if (!target)77
{78
follow.targetEntityId = null;79
follow.trail = [];80
continue;81
}82
const targetPos = world.ecs.get(targetHandle, Component.position);83
if (!targetPos)84
{77
{85
follow.targetEntityId = null;78
follow.targetEntityId = null;86
follow.trail = [];79
follow.trail = [];@@ -90,8 +83,8 @@ export function stepFollow (world)90
const dist = chebyshev(83
const dist = chebyshev(91
entity.position.tileX,84
entity.position.tileX,92
entity.position.tileY,85
entity.position.tileY,93
targetPos.tileX,86
target.pos.tileX,94
targetPos.tileY87
target.pos.tileY95
);88
);96
if (dist > FOLLOW_BREAK_TILES)89
if (dist > FOLLOW_BREAK_TILES)97
{90
{@@ -101,71 +94,142 @@ export function stepFollow (world)101
continue;94
continue;102
}95
}103
96
104
const targetMovement = world.ecs.get(targetHandle, Component.movement);105
if (dist > FOLLOW_ALWAYS_RUN_TILES)97
if (dist > FOLLOW_ALWAYS_RUN_TILES)106
{ entity.movement.gait = GAIT.run; }98
{ entity.movement.gait = GAIT.run; }107
else if (dist > 1)99
else if (dist > 1)108
{ entity.movement.gait = targetMovement?.gait === GAIT.run ? GAIT.run : GAIT.walk; }100
{ entity.movement.gait = target.gait === GAIT.run ? GAIT.run : GAIT.walk; }101
102
if (!Array.isArray(follow.trail))103
{ follow.trail = []; }104
trimTrailBehindFollower(follow.trail, entity.position);109
105
110
if (dist <= 1)106
const targetMoving = (target.pathTiles?.length ?? 0) > 0 || follow.trail.length > 0;107
// Stay put only when already adjacent and the target is idle — otherwise keep108
// chasing footsteps (including waiting on the target's current tile).109
if (dist <= 1 && !targetMoving)111
{110
{112
clearPath(world.ecs, entity.handle);111
clearPath(world.ecs, entity.handle);113
continue;112
continue;114
}113
}115
114
116
if (!Array.isArray(follow.trail))117
{ follow.trail = []; }118
trimTrailBehindFollower(follow.trail, entity.position);119
120
const targetPath = world.ecs.get(targetHandle, Component.path)?.tiles ?? [];121
const reused = buildFollowPath(115
const reused = buildFollowPath(122
world,116
world,123
entity.entityId,117
entity.entityId,124
entity.position,118
entity.position,125
targetPos,119
target.pos,126
follow.trail,120
follow.trail,127
targetPath121
target.pathTiles128
);122
);129
123
130
let path = world.ecs.get(entity.handle, Component.path);124
let path = world.ecs.get(entity.handle, Component.path);131
if (!path)125
if (!path)132
{ path = world.ecs.add(entity.handle, Component.path, { tiles: [] }); }126
{ path = world.ecs.add(entity.handle, Component.path, { tiles: [] }); }133
127
134
if (reused.length)128
if (reused.waiting)129
{130
// Next trail tile is occupied — wait for vacancy instead of detouring.131
assignFollowPath(entity.movement, path, reused.tiles);132
continue;133
}134
135
if (reused.tiles.length)135
{136
{136
path.tiles = reused;137
assignFollowPath(entity.movement, path, reused.tiles);137
entity.movement.walkCarry = 0;138
continue;138
continue;139
}139
}140
140
141
// No shared trail/path yet — catch up with a one-shot approach path.141
// No shared trail/path yet — catch up with a one-shot approach path.142
queueCatchUp(world, entity.entityId, entity.handle, entity.position, targetPos, path);142
queueCatchUp(world, entity.entityId, entity.handle, entity.position, target.pos, path);143
}143
}144
}144
}145
145
146
function resolveFollowTarget (world, targetId)147
{148
const targetHandle = world.ecs.handleOf(targetId);149
if (targetHandle != null)150
{151
const pos = world.ecs.get(targetHandle, Component.position);152
if (!pos)153
{ return null; }154
const movement = world.ecs.get(targetHandle, Component.movement);155
const path = world.ecs.get(targetHandle, Component.path);156
return {157
pos,158
gait: movement?.gait,159
pathTiles: path?.tiles ?? []160
};161
}162
const ghost = world.ghosts?.get?.(targetId);163
if (!ghost)164
{ return null; }165
return {166
pos: { tileX: ghost.tileX, tileY: ghost.tileY },167
gait: ghost.gait,168
pathTiles: []169
};170
}171
146
function buildFollowPath (world, followerId, followerPos, targetPos, trail, targetPathTiles)172
function buildFollowPath (world, followerId, followerPos, targetPos, trail, targetPathTiles)147
{173
{148
const combined = [];174
const combined = [];149
for (const tile of trail)175
for (const tile of trail)150
{ combined.push({ x: tile.x, y: tile.y }); }176
{ combined.push({ x: tile.x, y: tile.y }); }177
const lastTrail = combined[combined.length - 1];178
if (!lastTrail || lastTrail.x !== targetPos.tileX || lastTrail.y !== targetPos.tileY)179
{ combined.push({ x: targetPos.tileX, y: targetPos.tileY }); }151
for (const tile of targetPathTiles)180
for (const tile of targetPathTiles)152
{ combined.push({ x: tile.x, y: tile.y }); }181
{182
const prev = combined[combined.length - 1];183
if (prev && prev.x === tile.x && prev.y === tile.y)184
{ continue; }185
combined.push({ x: tile.x, y: tile.y });186
}153
187
154
const result = [];188
const result = [];189
let cursorX = followerPos.tileX;190
let cursorY = followerPos.tileY;155
for (const tile of combined)191
for (const tile of combined)156
{192
{157
if (tile.x === targetPos.tileX && tile.y === targetPos.tileY)193
if (tile.x === cursorX && tile.y === cursorY)158
{ break; }159
if (tile.x === followerPos.tileX && tile.y === followerPos.tileY)160
{ continue; }194
{ continue; }195
const stepDist = chebyshev(cursorX, cursorY, tile.x, tile.y);196
if (stepDist > 1)197
{198
// Gap between follower and trail — fall through to catch-up.199
if (!result.length)200
{ return { tiles: [], waiting: false }; }201
break;202
}161
if (!world.walkableFor(followerId, tile.x, tile.y))203
if (!world.walkableFor(followerId, tile.x, tile.y))162
{ break; }204
{205
// Occupied (usually by the follow target) — wait on that footstep.206
if (!result.length)207
{ return { tiles: [{ x: tile.x, y: tile.y }], waiting: true }; }208
break;209
}163
const prev = result[result.length - 1];210
const prev = result[result.length - 1];164
if (prev && prev.x === tile.x && prev.y === tile.y)211
if (prev && prev.x === tile.x && prev.y === tile.y)165
{ continue; }212
{ continue; }166
result.push(tile);213
result.push({ x: tile.x, y: tile.y });214
cursorX = tile.x;215
cursorY = tile.y;167
}216
}168
return result;217
return { tiles: result, waiting: false };218
}219
220
function assignFollowPath (movement, path, tiles)221
{222
const prevNext = path.tiles?.[0];223
const next = tiles[0];224
const nextChanged = !next225
|| !prevNext226
|| prevNext.x !== next.x227
|| prevNext.y !== next.y;228
path.tiles = tiles;229
// Only reset walk cadence when the immediate step changes; refreshing the230
// remaining trail every systems tick must not stall walking followers.231
if (nextChanged)232
{ movement.walkCarry = 0; }169
}233
}170
234
171
function trimTrailBehindFollower (trail, position)235
function trimTrailBehindFollower (trail, position)@@ -184,8 +248,8 @@ function trimTrailBehindFollower (trail, position)184
248
185
function queueCatchUp (world, entityId, handle, position, targetPos, path)249
function queueCatchUp (world, entityId, handle, position, targetPos, path)186
{250
{187
const goal = bestAdjacentGoal(world, entityId, position, targetPos);251
const goal = { x: targetPos.tileX, y: targetPos.tileY };188
if (!goal)252
if (position.tileX === goal.x && position.tileY === goal.y)189
{253
{190
path.tiles = [];254
path.tiles = [];191
return;255
return;@@ -193,16 +257,24 @@ function queueCatchUp (world, entityId, handle, position, targetPos, path)193
if (path.tiles?.length)257
if (path.tiles?.length)194
{258
{195
const last = path.tiles[path.tiles.length - 1];259
const last = path.tiles[path.tiles.length - 1];196
if (last.x === goal.x && last.y === goal.y)260
const first = path.tiles[0];261
if (last.x === goal.x && last.y === goal.y262
&& chebyshev(position.tileX, position.tileY, first.x, first.y) <= 1)197
{ return; }263
{ return; }198
}264
}199
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);265
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);200
path.tiles = findPath(266
const nextTiles = findPath(201
position.tileX,267
position.tileX,202
position.tileY,268
position.tileY,203
goal.x,269
goal.x,204
goal.y,270
goal.y,205
(x, y) => world.walkableFor(entityId, x, y),271
(x, y) =>272
{273
// Plan onto the target tile; movement still waits while they occupy it.274
if (x === goal.x && y === goal.y)275
{ return world.isEnterable?.(x, y) ?? world.walkableFor(entityId, x, y); }276
return world.walkableFor(entityId, x, y);277
},206
bounds.minX,278
bounds.minX,207
bounds.minY,279
bounds.minY,208
bounds.maxX,280
bounds.maxX,@@ -210,7 +282,9 @@ function queueCatchUp (world, entityId, handle, position, targetPos, path)210
);282
);211
const movement = world.ecs.get(handle, Component.movement);283
const movement = world.ecs.get(handle, Component.movement);212
if (movement)284
if (movement)213
{ movement.walkCarry = 0; }285
{ assignFollowPath(movement, path, nextTiles); }286
else287
{ path.tiles = nextTiles; }214
}288
}215
289
216
function clearPath (ecs, handle)290
function clearPath (ecs, handle)@@ -219,29 +293,3 @@ function clearPath (ecs, handle)219
if (path)293
if (path)220
{ path.tiles = []; }294
{ path.tiles = []; }221
}295
}222
223
function bestAdjacentGoal (world, entityId, position, targetPos)224
{225
const dirs = [226
{ x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },227
{ x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }228
];229
let best = null;230
let bestDist = Infinity;231
for (const dir of dirs)232
{233
const x = targetPos.tileX + dir.x;234
const y = targetPos.tileY + dir.y;235
if (x === position.tileX && y === position.tileY)236
{ return { x, y }; }237
if (!world.walkableFor(entityId, x, y))238
{ continue; }239
const dist = chebyshev(position.tileX, position.tileY, x, y);240
if (dist < bestDist)241
{242
bestDist = dist;243
best = { x, y };244
}245
}246
return best;247
}@@ -188,7 +188,7 @@ test("follower reuses the target vacated trail and waits off their tile", () =>
188
188
Math.abs(followerComps.position.tileY - leaderComps.position.tileY)
189
189
);
190
190
assert.ok(dist >= 1);
191
assert.ok(dist <= 3);
191
assert.ok(dist <= 2, `follower should settle adjacent, dist=${dist}`);
192
192
assert.ok(
193
193
followerComps.position.tileX > 6,
194
194
"follower should have advanced along the leader path"
@@ -197,3 +197,87 @@ test("follower reuses the target vacated trail and waits off their tile", () =>
197
197
finally
198
198
{ harness.close(); }
199
199
});
200
201
test("walking follower keeps pace at short range without stalling walkCarry", () =>
202
{
203
const harness = makeSimulation({ workerCount: 1 });
204
try
205
{
206
harness.simulation.applySettings({ walkTilesPerSecond: 2, simulationTickHz: 20 });
207
const leader = makeCharacter(harness.stateDb, { firstName: "Lead", tileX: 8, tileY: 8 });
208
const follower = makeCharacter(harness.stateDb, { firstName: "Follow", lastName: "Walk", tileX: 6, tileY: 8 });
209
const leaderId = harness.simulation.spawnCharacter(1, leader);
210
const followerId = harness.simulation.spawnCharacter(2, follower);
211
212
harness.simulation.enqueue(2, {
213
type: "follow",
214
characterId: follower.character_id,
215
targetEntityId: leaderId
216
});
217
harness.simulation.step();
218
assert.equal(componentsOf(harness.simulation, followerId).movement.gait, GAIT.walk);
219
220
harness.simulation.enqueue(1, {
221
type: "move-to",
222
characterId: leader.character_id,
223
tileX: 14,
224
tileY: 8
225
});
226
227
// Stay in the walk-match band (dist 2–3): systems ticks must not wipe walkCarry.
228
stepTimes(harness.simulation, 24);
229
const followerComps = componentsOf(harness.simulation, followerId);
230
const leaderComps = componentsOf(harness.simulation, leaderId);
231
assert.equal(followerComps.follow.targetEntityId, leaderId);
232
assert.ok(
233
followerComps.position.tileX >= 8,
234
`walking follower should have moved (at ${followerComps.position.tileX}), leader at ${leaderComps.position.tileX}`
235
);
236
const dist = Math.max(
237
Math.abs(followerComps.position.tileX - leaderComps.position.tileX),
238
Math.abs(followerComps.position.tileY - leaderComps.position.tileY)
239
);
240
assert.ok(dist <= 2, `follower fell behind to dist ${dist}`);
241
}
242
finally
243
{ harness.close(); }
244
});
245
246
test("follower settles on the tile behind an idle leader, not one further back", () =>
247
{
248
const harness = makeSimulation({ workerCount: 1 });
249
try
250
{
251
harness.simulation.applySettings({ walkTilesPerSecond: 4, simulationTickHz: 20 });
252
const leader = makeCharacter(harness.stateDb, { firstName: "Lead", tileX: 8, tileY: 8 });
253
const follower = makeCharacter(harness.stateDb, { firstName: "Follow", lastName: "Close", tileX: 5, tileY: 8 });
254
const leaderId = harness.simulation.spawnCharacter(1, leader);
255
const followerId = harness.simulation.spawnCharacter(2, follower);
256
257
harness.simulation.enqueue(2, {
258
type: "follow",
259
characterId: follower.character_id,
260
targetEntityId: leaderId
261
});
262
harness.simulation.step();
263
harness.simulation.enqueue(1, {
264
type: "move-to",
265
characterId: leader.character_id,
266
tileX: 14,
267
tileY: 8
268
});
269
stepTimes(harness.simulation, 60);
270
271
const followerComps = componentsOf(harness.simulation, followerId);
272
const leaderComps = componentsOf(harness.simulation, leaderId);
273
assert.equal(leaderComps.position.tileX, 14);
274
assert.equal(followerComps.follow.targetEntityId, leaderId);
275
const dist = Math.max(
276
Math.abs(followerComps.position.tileX - leaderComps.position.tileX),
277
Math.abs(followerComps.position.tileY - leaderComps.position.tileY)
278
);
279
assert.equal(dist, 1, `expected adjacent settle, follower=${followerComps.position.tileX} leader=${leaderComps.position.tileX}`);
280
}
281
finally
282
{ harness.close(); }
283
});
@@ -188,7 +188,7 @@ test("follower reuses the target vacated trail and waits off their tile", () =>188
Math.abs(followerComps.position.tileY - leaderComps.position.tileY)188
Math.abs(followerComps.position.tileY - leaderComps.position.tileY)189
);189
);190
assert.ok(dist >= 1);190
assert.ok(dist >= 1);191
assert.ok(dist <= 3);191
assert.ok(dist <= 2, `follower should settle adjacent, dist=${dist}`);192
assert.ok(192
assert.ok(193
followerComps.position.tileX > 6,193
followerComps.position.tileX > 6,194
"follower should have advanced along the leader path"194
"follower should have advanced along the leader path"@@ -197,3 +197,87 @@ test("follower reuses the target vacated trail and waits off their tile", () =>197
finally197
finally198
{ harness.close(); }198
{ harness.close(); }199
});199
});200
201
test("walking follower keeps pace at short range without stalling walkCarry", () =>202
{203
const harness = makeSimulation({ workerCount: 1 });204
try205
{206
harness.simulation.applySettings({ walkTilesPerSecond: 2, simulationTickHz: 20 });207
const leader = makeCharacter(harness.stateDb, { firstName: "Lead", tileX: 8, tileY: 8 });208
const follower = makeCharacter(harness.stateDb, { firstName: "Follow", lastName: "Walk", tileX: 6, tileY: 8 });209
const leaderId = harness.simulation.spawnCharacter(1, leader);210
const followerId = harness.simulation.spawnCharacter(2, follower);211
212
harness.simulation.enqueue(2, {213
type: "follow",214
characterId: follower.character_id,215
targetEntityId: leaderId216
});217
harness.simulation.step();218
assert.equal(componentsOf(harness.simulation, followerId).movement.gait, GAIT.walk);219
220
harness.simulation.enqueue(1, {221
type: "move-to",222
characterId: leader.character_id,223
tileX: 14,224
tileY: 8225
});226
227
// Stay in the walk-match band (dist 2–3): systems ticks must not wipe walkCarry.228
stepTimes(harness.simulation, 24);229
const followerComps = componentsOf(harness.simulation, followerId);230
const leaderComps = componentsOf(harness.simulation, leaderId);231
assert.equal(followerComps.follow.targetEntityId, leaderId);232
assert.ok(233
followerComps.position.tileX >= 8,234
`walking follower should have moved (at ${followerComps.position.tileX}), leader at ${leaderComps.position.tileX}`235
);236
const dist = Math.max(237
Math.abs(followerComps.position.tileX - leaderComps.position.tileX),238
Math.abs(followerComps.position.tileY - leaderComps.position.tileY)239
);240
assert.ok(dist <= 2, `follower fell behind to dist ${dist}`);241
}242
finally243
{ harness.close(); }244
});245
246
test("follower settles on the tile behind an idle leader, not one further back", () =>247
{248
const harness = makeSimulation({ workerCount: 1 });249
try250
{251
harness.simulation.applySettings({ walkTilesPerSecond: 4, simulationTickHz: 20 });252
const leader = makeCharacter(harness.stateDb, { firstName: "Lead", tileX: 8, tileY: 8 });253
const follower = makeCharacter(harness.stateDb, { firstName: "Follow", lastName: "Close", tileX: 5, tileY: 8 });254
const leaderId = harness.simulation.spawnCharacter(1, leader);255
const followerId = harness.simulation.spawnCharacter(2, follower);256
257
harness.simulation.enqueue(2, {258
type: "follow",259
characterId: follower.character_id,260
targetEntityId: leaderId261
});262
harness.simulation.step();263
harness.simulation.enqueue(1, {264
type: "move-to",265
characterId: leader.character_id,266
tileX: 14,267
tileY: 8268
});269
stepTimes(harness.simulation, 60);270
271
const followerComps = componentsOf(harness.simulation, followerId);272
const leaderComps = componentsOf(harness.simulation, leaderId);273
assert.equal(leaderComps.position.tileX, 14);274
assert.equal(followerComps.follow.targetEntityId, leaderId);275
const dist = Math.max(276
Math.abs(followerComps.position.tileX - leaderComps.position.tileX),277
Math.abs(followerComps.position.tileY - leaderComps.position.tileY)278
);279
assert.equal(dist, 1, `expected adjacent settle, follower=${followerComps.position.tileX} leader=${leaderComps.position.tileX}`);280
}281
finally282
{ harness.close(); }283
});@@ -0,0 +1,144 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { ItemId } from "../../shared/definitions/items.js";
4
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
5
6
test("writing paper creates an opened letter only the author can edit", () =>
7
{
8
const harness = makeSimulation({ workerCount: 1 });
9
try
10
{
11
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada", lastName: "Writer" });
12
const entityId = harness.simulation.spawnCharacter(1, character);
13
const bag = harness.simulation.bagOf(entityId);
14
const paperSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.paper);
15
assert.ok(paperSlot >= 0);
16
const paperQty = bag.inventory[paperSlot].quantity;
17
18
harness.simulation.enqueue(1, {
19
type: "write-letter",
20
characterId: character.character_id,
21
slotIndex: paperSlot,
22
body: "Hello from Ada"
23
});
24
harness.simulation.step();
25
const after = harness.simulation.bagOf(entityId);
26
const letterSlot = after.inventory.findIndex((slot) => slot?.itemId === ItemId.letter);
27
assert.ok(letterSlot >= 0);
28
assert.equal(after.inventory[letterSlot].instance.authorCharacterId, character.character_id);
29
assert.equal(after.inventory[letterSlot].instance.body, "Hello from Ada");
30
assert.equal(after.inventory[letterSlot].instance.authorDisplayName, "Ada Writer");
31
assert.equal(after.inventory[letterSlot].instance.opened, true);
32
assert.equal(
33
after.inventory.filter((slot) => slot?.itemId === ItemId.paper)
34
.reduce((sum, slot) => sum + slot.quantity, 0),
35
paperQty - 1
36
);
37
38
harness.simulation.enqueue(1, {
39
type: "edit-letter",
40
characterId: character.character_id,
41
slotIndex: letterSlot,
42
body: "Updated body"
43
});
44
harness.simulation.step();
45
assert.equal(harness.simulation.bagOf(entityId).inventory[letterSlot].instance.body, "Updated body");
46
}
47
finally
48
{ harness.close(); }
49
});
50
51
test("sending a letter seals it closed and rejects other authors", () =>
52
{
53
const harness = makeSimulation({ workerCount: 1 });
54
try
55
{
56
const writer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada", lastName: "Writer" });
57
const other = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Bob", lastName: "Other" });
58
const writerId = harness.simulation.spawnCharacter(1, writer);
59
harness.simulation.spawnCharacter(2, other);
60
const paperSlot = harness.simulation.bagOf(writerId).inventory.findIndex((slot) => slot?.itemId === ItemId.paper);
61
harness.simulation.enqueue(1, {
62
type: "write-letter",
63
characterId: writer.character_id,
64
slotIndex: paperSlot,
65
body: "Secret"
66
});
67
harness.simulation.step();
68
const letterSlot = harness.simulation.bagOf(writerId).inventory.findIndex((slot) => slot?.itemId === ItemId.letter);
69
assert.ok(letterSlot >= 0);
70
71
const sealed = harness.simulation.dispatchPigeon({
72
characterId: writer.character_id,
73
destination: { kind: "player", firstName: "Bob", lastName: "Other" },
74
cargo: { kind: "item", slotIndex: letterSlot, quantity: 1 }
75
});
76
assert.equal(sealed.transit.cargo.stack.instance.opened, false);
77
78
const otherId = harness.simulation.characterEntities.get(other.character_id);
79
const otherBag = harness.simulation.bagOf(otherId);
80
const stealSlot = otherBag.inventory.findIndex((slot) => !slot);
81
assert.ok(stealSlot >= 0);
82
otherBag.inventory[stealSlot] = {
83
itemId: ItemId.letter,
84
quantity: 1,
85
origin: null,
86
instance: {
87
kind: "letter",
88
letterId: "stolen",
89
authorCharacterId: writer.character_id,
90
authorDisplayName: "Ada Writer",
91
body: "Stolen",
92
opened: true,
93
writtenAt: Date.now()
94
}
95
};
96
harness.simulation.applyBag(otherId, otherBag);
97
assert.throws(
98
() => harness.simulation.dispatchPigeon({
99
characterId: other.character_id,
100
destination: { kind: "bank" },
101
cargo: { kind: "item", slotIndex: stealSlot, quantity: 1 }
102
}),
103
/only send letters you wrote/i
104
);
105
}
106
finally
107
{ harness.close(); }
108
});
109
110
test("reading a closed letter opens it", () =>
111
{
112
const harness = makeSimulation({ workerCount: 1 });
113
try
114
{
115
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada", lastName: "Reader" });
116
const entityId = harness.simulation.spawnCharacter(1, character);
117
const bag = harness.simulation.bagOf(entityId);
118
const free = bag.inventory.findIndex((slot) => !slot);
119
bag.inventory[free] = {
120
itemId: ItemId.letter,
121
quantity: 1,
122
origin: null,
123
instance: {
124
kind: "letter",
125
letterId: "mail-1",
126
authorCharacterId: 999,
127
authorDisplayName: "Other Writer",
128
body: "Hello",
129
opened: false,
130
writtenAt: Date.now()
131
}
132
};
133
harness.simulation.applyBag(entityId, bag);
134
harness.simulation.enqueue(1, {
135
type: "open-letter",
136
characterId: character.character_id,
137
slotIndex: free
138
});
139
harness.simulation.step();
140
assert.equal(harness.simulation.bagOf(entityId).inventory[free].instance.opened, true);
141
}
142
finally
143
{ harness.close(); }
144
});
@@ -0,0 +1,144 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { ItemId } from "../../shared/definitions/items.js";4
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";5
6
test("writing paper creates an opened letter only the author can edit", () =>7
{8
const harness = makeSimulation({ workerCount: 1 });9
try10
{11
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada", lastName: "Writer" });12
const entityId = harness.simulation.spawnCharacter(1, character);13
const bag = harness.simulation.bagOf(entityId);14
const paperSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.paper);15
assert.ok(paperSlot >= 0);16
const paperQty = bag.inventory[paperSlot].quantity;17
18
harness.simulation.enqueue(1, {19
type: "write-letter",20
characterId: character.character_id,21
slotIndex: paperSlot,22
body: "Hello from Ada"23
});24
harness.simulation.step();25
const after = harness.simulation.bagOf(entityId);26
const letterSlot = after.inventory.findIndex((slot) => slot?.itemId === ItemId.letter);27
assert.ok(letterSlot >= 0);28
assert.equal(after.inventory[letterSlot].instance.authorCharacterId, character.character_id);29
assert.equal(after.inventory[letterSlot].instance.body, "Hello from Ada");30
assert.equal(after.inventory[letterSlot].instance.authorDisplayName, "Ada Writer");31
assert.equal(after.inventory[letterSlot].instance.opened, true);32
assert.equal(33
after.inventory.filter((slot) => slot?.itemId === ItemId.paper)34
.reduce((sum, slot) => sum + slot.quantity, 0),35
paperQty - 136
);37
38
harness.simulation.enqueue(1, {39
type: "edit-letter",40
characterId: character.character_id,41
slotIndex: letterSlot,42
body: "Updated body"43
});44
harness.simulation.step();45
assert.equal(harness.simulation.bagOf(entityId).inventory[letterSlot].instance.body, "Updated body");46
}47
finally48
{ harness.close(); }49
});50
51
test("sending a letter seals it closed and rejects other authors", () =>52
{53
const harness = makeSimulation({ workerCount: 1 });54
try55
{56
const writer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada", lastName: "Writer" });57
const other = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Bob", lastName: "Other" });58
const writerId = harness.simulation.spawnCharacter(1, writer);59
harness.simulation.spawnCharacter(2, other);60
const paperSlot = harness.simulation.bagOf(writerId).inventory.findIndex((slot) => slot?.itemId === ItemId.paper);61
harness.simulation.enqueue(1, {62
type: "write-letter",63
characterId: writer.character_id,64
slotIndex: paperSlot,65
body: "Secret"66
});67
harness.simulation.step();68
const letterSlot = harness.simulation.bagOf(writerId).inventory.findIndex((slot) => slot?.itemId === ItemId.letter);69
assert.ok(letterSlot >= 0);70
71
const sealed = harness.simulation.dispatchPigeon({72
characterId: writer.character_id,73
destination: { kind: "player", firstName: "Bob", lastName: "Other" },74
cargo: { kind: "item", slotIndex: letterSlot, quantity: 1 }75
});76
assert.equal(sealed.transit.cargo.stack.instance.opened, false);77
78
const otherId = harness.simulation.characterEntities.get(other.character_id);79
const otherBag = harness.simulation.bagOf(otherId);80
const stealSlot = otherBag.inventory.findIndex((slot) => !slot);81
assert.ok(stealSlot >= 0);82
otherBag.inventory[stealSlot] = {83
itemId: ItemId.letter,84
quantity: 1,85
origin: null,86
instance: {87
kind: "letter",88
letterId: "stolen",89
authorCharacterId: writer.character_id,90
authorDisplayName: "Ada Writer",91
body: "Stolen",92
opened: true,93
writtenAt: Date.now()94
}95
};96
harness.simulation.applyBag(otherId, otherBag);97
assert.throws(98
() => harness.simulation.dispatchPigeon({99
characterId: other.character_id,100
destination: { kind: "bank" },101
cargo: { kind: "item", slotIndex: stealSlot, quantity: 1 }102
}),103
/only send letters you wrote/i104
);105
}106
finally107
{ harness.close(); }108
});109
110
test("reading a closed letter opens it", () =>111
{112
const harness = makeSimulation({ workerCount: 1 });113
try114
{115
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Ada", lastName: "Reader" });116
const entityId = harness.simulation.spawnCharacter(1, character);117
const bag = harness.simulation.bagOf(entityId);118
const free = bag.inventory.findIndex((slot) => !slot);119
bag.inventory[free] = {120
itemId: ItemId.letter,121
quantity: 1,122
origin: null,123
instance: {124
kind: "letter",125
letterId: "mail-1",126
authorCharacterId: 999,127
authorDisplayName: "Other Writer",128
body: "Hello",129
opened: false,130
writtenAt: Date.now()131
}132
};133
harness.simulation.applyBag(entityId, bag);134
harness.simulation.enqueue(1, {135
type: "open-letter",136
characterId: character.character_id,137
slotIndex: free138
});139
harness.simulation.step();140
assert.equal(harness.simulation.bagOf(entityId).inventory[free].instance.opened, true);141
}142
finally143
{ harness.close(); }144
});